/****** Object:  StoredProcedure [dbo].[adr_sp_BindControllerIdsByESP]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 27-03-2017
-- Description:	Loads the controller Ids for the selected ESP to Save/Update new Controller in Controller Master.
--				adr_sp_BindControllerIdsByESP	999981,57,0,86,457
-- =============================================
CREATE PROCEDURE [dbo].[adr_sp_BindControllerIdsByESP] 
	-- Add the parameters for the stored procedure here	
	@bigEquipmentId				bigint = NULL, 
	@bigControllerId			bigint = NULL, 
	@tintDCSIMId				tinyint	= NULL,
	@bigOrganizationId			bigint = NULL, 
	@bigUserId					bigint = NULL
AS
BEGIN
	 --SET NOCOUNT ON added to prevent extra result sets from
	 --interfering with SELECT statements.
	SET NOCOUNT ON;
 

	Declare @ControllerType bigint = NULL;
	SET @ControllerType = (Select SubTypeId from rvlfMAKDevices where OrganizationId=@bigOrganizationId AND BoxId=@bigEquipmentId)

    -- Insert statements for procedure here
	DECLARE	@TblUpdate Table(ControllerPositionId int, ControllerPositionName varchar(100))

	IF(@bigControllerId IS NOT NULL OR @bigControllerId <> '' OR @bigControllerId <> '0')
	BEGIN
		INSERT	INTO @TblUpdate
		SELECT  * From adrControllerPositions Where ControllerPositionId In 
		(Select ControllerPositionId FROM adrControllerMaster Where	IsDeleted = 0
		AND		((@bigEquipmentId IS NULL OR @bigEquipmentId = '') OR EquipmentId = @bigEquipmentId)	
		AND		ControllerId = @bigControllerId)
	END

	IF (@ControllerType=1 AND (@ControllerType IS NOT NULL OR @ControllerType <> '' OR @ControllerType <> '0'))
	BEGIN
		--PRINT 'Controller Type is Precicon-III'
			SELECT * FROM adrControllerPositions WHERE (ControllerPositionId between 11 AND 34) AND ControllerPositionId NOT IN 
				(SELECT ControllerPositionId FROM adrControllerMaster Where	IsDeleted = 0
				AND		((@bigEquipmentId IS NULL OR @bigEquipmentId = '' OR @bigEquipmentId = '0') OR EquipmentId = @bigEquipmentId)
				AND		((@tintDCSIMId IS NULL OR @tintDCSIMId = '' OR @tintDCSIMId = '0') OR DCSIMId = @tintDCSIMId))		
			UNION ALL	
				SELECT * FROM @TblUpdate ORDER BY ControllerPositionId
	END
	ELSE IF(@ControllerType=2 AND (@ControllerType IS NOT NULL OR @ControllerType <> '' OR @ControllerType <> '0'))
	BEGIN
		--PRINT 'Controller Type is Precicon-R'
			SELECT * FROM adrControllerPositions WHERE (ControllerPositionId between 1 AND 24) AND ControllerPositionId NOT IN 
				(SELECT ControllerPositionId FROM adrControllerMaster Where	IsDeleted = 0
				AND		((@bigEquipmentId IS NULL OR @bigEquipmentId = '' OR @bigEquipmentId = '0') OR EquipmentId = @bigEquipmentId)
				AND		((@tintDCSIMId IS NULL OR @tintDCSIMId = '' OR @tintDCSIMId = '0') OR DCSIMId = @tintDCSIMId))	
			UNION ALL
				SELECT * FROM @TblUpdate ORDER BY ControllerPositionId
	END
	ELSE
	BEGIN
			SELECT * FROM adrControllerPositions WHERE ControllerPositionId IN 
				(SELECT ControllerPositionId FROM adrControllerMaster Where	IsDeleted = 0
				AND		((@bigEquipmentId IS NULL OR @bigEquipmentId = '' OR @bigEquipmentId = '0') OR EquipmentId = @bigEquipmentId)
				AND		((@tintDCSIMId IS NULL OR @tintDCSIMId = '' OR @tintDCSIMId = '0') OR DCSIMId = @tintDCSIMId))		
			UNION ALL	
				SELECT * FROM @TblUpdate ORDER BY ControllerPositionId

	END
END

GO
/****** Object:  StoredProcedure [dbo].[adr_sp_CheckControllerExists]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 27-03-2017
-- Description:	Check whether the Controller already exists for the selected Equipment in Controller Master.
--				adr_sp_CheckControllerExists	86,18
-- =============================================
CREATE PROCEDURE [dbo].[adr_sp_CheckControllerExists] 
	-- Add the parameters for the stored procedure here	
	@bigEquipmentId				bigint = NULL, 
	@vcControllerName			varchar(50) = NULL,
	@bigOrganizationId			bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT	CM.ControllerId, CM.ControllerName
	FROM	adrControllerMaster CM
	INNER	JOIN rvlfMAKDevices MD ON MD.BoxId = CM.EquipmentId
	WHERE	CM.IsActive = 1 
	AND		CM.IsDeleted = 0
	AND		CM.EquipmentId = @bigEquipmentId
	AND		CM.ControllerName = @vcControllerName
	AND		MD.OrganizationId = @bigOrganizationID
END

GO
/****** Object:  StoredProcedure [dbo].[adr_sp_DevicesDetailedReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 -- ==========================================================================================
-- Author:		Anbarasu.E
-- Create date: 04-03-2016
-- Description:	Get data for Travelled Students Head Count Report
--adr_sp_DevicesDetailedReport 176,'0',86,null,null,null,576
-- ==========================================================================================
CREATE PROCEDURE [dbo].[adr_sp_DevicesDetailedReport]
	-- Add the parameters for the stored procedure here
	@bigFleetID			bigint = NULL,
	@intBoxID			varchar(max) = NULL,
	@bigOrganizationID  bigint = NULL,
	@dtStartDate		DateTime = null,
	@dtEndDate			DateTime = null,
	@bigCustomerId		bigint = NULL,
	@bigQueryingUser	bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	DECLARE @HoursToBeAdded  INT = 0
	DECLARE @MinsToBeAdded  INT = 0
	DECLARE @DefaultDateFormat INT = 0

	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,
			@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		(@bigQueryingUser IS NULL OR @bigQueryingUser='' OR up.UserId = @bigQueryingUser)

	--DECLARE @tblDevices Table(BoxId bigint, EquipmentName varchar(50), EquipmentSrNo varchar(50), WarrantyStDate Datetime, WarrantyEndDate Datetime, 
	--VehicleId bigint, VehicleTypeId int, VehicleTypeName varchar(100), LastLatitude decimal, LastLongitude decimal, LastValidDateTime Datetime, 
	--LastStreetAddress varchar(250), SiteName varchar(50), ControllerId bigint, DCSIMId bigint, CustomerName varchar(50))

	--Insert Into @tblDevices
	Select MD.BoxId, EquipmentName, EquipmentSrNo, 
	Convert(varchar,cast(MD.WarrantyStDate as Date),@DefaultDateFormat) as WarrantyStDate
	, MD.WarrantyEndDate, MD.VehicleId, VT.VehicleTypeId, VT.VehicleTypeName, 
	B.LastLatitude, B.LastLongitude, CM.LastReporteDateTime LastValidDateTime1,
	Convert(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,CM.LastReporteDateTime)) as Date),@DefaultDateFormat) + ' ' +
	Convert(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,CM.LastReporteDateTime)) as time),22) as LastValidDateTime
	, B.LastStreetAddress, F.FleetName SiteName, CM.ControllerId, CM.DCSIMId, Cust.CustomerName,
	CM.ControllerName, CM.PassageId, CM.FieldId, 
	CASE CM.ControllerLocation WHEN 1 THEN 'Inlet' WHEN 2 THEN 'Outlet' WHEN 3 THEN 'Intermediate' ELSE '-' END AS ControllerLocation,
	CASE WHEN DCSIM.DCSIMName IS NULL THEN '-' WHEN DCSIM.DCSIMName = '' THEN '-' ELSE DCSIM.DCSIMName END AS DCSIMName,
	CASE WHEN CM.IsAlarm =1 THEN 'Alarm' ELSE (CASE WHEN DATEDIFF(HH,CM.LastReporteDateTime,GETUTCDATE()) > 1 or CM.LastReporteDateTime is null THEN 'Offline' ELSE 'Online' END) END as DeviceStatus, 
	'SPM' as SPM, 'APM' as APM, CASE WHEN HT_ON_OFF = 1 THEN 'ON' ELSE 'OFF' END as HTStatus,
	Convert(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as Date),@DefaultDateFormat) + ' ' +
	Convert(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate   , 
	case when (@bigCustomerId IS NULL OR @bigCustomerId = '' OR @bigCustomerId = '0') then 'All' else cust.CustomerName end as Customerfilter
	From rvlfMAKDevices MD
	INNER JOIN rvlfBoxId B ON MD.BoxId = B.BoxId
	INNER JOIN rvlfVehicle V ON V.VehicleId = MD.VehicleId
	INNER JOIN rvlfVehicleType VT ON V.VehicleTypeId = VT.VehicleTypeId
	INNER JOIN rvlfFleetVehicles FV ON V.VehicleId = FV.VehicleId 
	INNER JOIN rvlfFleet F ON FV.FleetId = F.FleetId and F.FleetId <> 176
	INNER JOIN adrControllerMaster CM ON MD.BoxId = CM.EquipmentId and CM.IsDeleted = 0 and CM.IsActive = 1
	INNER JOIN rvlfCustomers cust ON Cust.CustomerId = MD.CustomerId
	LEFT OUTER JOIN adrDCSIMMaster DCSIM ON CM.DCSIMId = DCSIM.DCSIMId
	Where (@intBoxID IS NULL OR @intBoxID = '' OR @intBoxID = '0' or MD.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))
	and   (@bigCustomerId IS NULL OR @bigCustomerId = '' OR @bigCustomerId = '0' OR cust.CustomerId = @bigCustomerId)
	and   (@bigOrganizationID IS NULL OR @bigOrganizationID = '' OR @bigOrganizationID = '0' OR MD.OrganizationId = @bigOrganizationID)
	Order By BoxId	 
END

 


GO
/****** Object:  StoredProcedure [dbo].[adr_sp_EquipmentUsageReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 16-05-2017
-- Description:	Fetches data for Equipment Usage Report based on HT-ON/OFF messages.
--				adr_sp_EquipmentUsageReport	
-- =============================================
CREATE PROCEDURE [dbo].[adr_sp_EquipmentUsageReport] 
	-- Add the parameters for the stored procedure here
	@dtStartDate		DateTime = NULL,
	@dtEndDate			DateTime = NULL,
	@bigFleetId			bigint = NULL,
	@bigBoxId			bigint = NULL, 
	@bigOrganizationId	bigint = NULL, 
	@bigUserId			bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @dtFDate			datetime = @dtStartDate                            
	DECLARE @dtEDate			datetime = @dtEndDate                            
	DECLARE @HoursToBeAdded		INT = 0                            
	DECLARE @MinsToBeAdded		INT = 0                             
	DECLARE @DefaultDateFormat	INT = 0                          
                            
	SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                          
	@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(@bigUserId IS NULL OR @bigUserId='' OR up.UserId = @bigUserId) 

    -- Insert statements for procedure here
	SELECT	* FROM rvlfMsgInHst H
	INNER	JOIN rvlfMsgInHstParam_PIII PIII ON H.MessageInID = PIII.Messageinid
	INNER	JOIN rvlfMsgInHstParam_PR PR ON H.MessageInID = PR.Messageinid
	INNER	JOIN rvlfVehicleAssignment VA ON VA.BoxId = H.BoxId
	INNER	JOIN rvlfVehicle V ON V.VehicleId = VA.VehicleId
	INNER	JOIN rvlfFleetVehicles FV ON FV.VehicleId = V.VehicleId
	INNER	JOIN rvlfFleet F ON F.FleetId = FV.FleetID
	WHERE	(@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId=@bigFleetID)
	AND     (@bigBoxId IS NULL OR @bigBoxId='' OR @bigBoxId='0' OR  VA.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@bigBoxId,',')))
	AND		(H.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)
	AND		(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId=@bigOrganizationID)

END

GO
/****** Object:  StoredProcedure [dbo].[adr_sp_GetESPConfigurationData]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 27-03-2017
-- Description:	To get the load data for ESP Controller Master
--				adr_sp_GetESPConfigurationData 86,18
-- =============================================
CREATE PROCEDURE [dbo].[adr_sp_GetESPConfigurationData] 
	-- Add the parameters for the stored procedure here
	@bigOrganizationID	bigint = NULL, 
	@bigUserID			bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT * FROM adrPassageMaster 
	WHERE IsDelete = 0

	SELECT * FROM adrFieldMaster
	WHERE IsDelete = 0

	SELECT * FROM adrDCSIMMaster
	WHERE IsDelete = 0

	SELECT	*, Convert(nvarchar, MD.BoxId) + ' - ' + EquipmentName as EquipmentNameDisplay
	FROM	rvlfMAKDevices MD
	INNER	JOIN rvlfBoxID	B	ON MD.BoxId = B.BoxId
	INNER	JOIN rvlfVehicle V	ON MD.VehicleId = V.VehicleId
	WHERE	MD.OrganizationId = @bigOrganizationID 
	AND		IsDelete = 0
	--and	UserId = @bigUserID
END

GO
/****** Object:  StoredProcedure [dbo].[adr_sp_GetESPLayout]    Script Date: 02/01/2022 04:05:37 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:	Get ESP Layout.
--				adr_sp_GetESPLayout 176,1011,86,457
-- =============================================
CREATE PROCEDURE [dbo].[adr_sp_GetESPLayout] 
	-- Add the parameters for the stored procedure here
	@bigSiteId			bigint = NULL, 
	@bigEquipmentId		bigint = NULL, 
	@bigOrganizationID	bigint = NULL, 
	@bigUserID			bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

--Declare @bigSiteId			bigint =176 
--Declare @bigEquipmentId		bigint = 1011
--Declare @bigOrganizationID	bigint = 86
--Declare @bigUserID	bigint =457


--Select * From adrControllerMaster where EquipmentId=1011 and ControllerID=134
--Update adrControllerMaster SET ControllerPositionID = 12 where EquipmentId=1011 and ControllerID=138
--Update adrControllerMaster SET FieldID = 1 where EquipmentId=1011 and Controllersrno between 19 and 24
--Update adrControllerMaster SET PassageID = 1 where EquipmentId=1011 and Controllersrno between 13 and 24

    -- Insert statements for procedure here
	DECLARE @ControllerDetails Table(ControllerId bigint, EquipmentId bigint, PassageId tinyint, FieldId tinyint, DCSIMId tinyint,
									ControllerLocation tinyint, ControllerPositionId tinyint, ControllerName varchar(50), ControllerType tinyint)

	INSERT	INTO @ControllerDetails
	SELECT	CM.ControllerId, CM.EquipmentId, CM.PassageId, CM.FieldId, CM.DCSIMId, CM.ControllerLocation, 
			CM.ControllerPositionId, CM.ControllerName, VT.VehicleTypeId		
	FROM	adrControllerMaster CM
	INNER JOIN rvlfMAKDevices MD ON CM.EquipmentId = MD.BoxId
	INNER JOIN rvlfBoxID	B	ON MD.BoxId = B.BoxId
	INNER JOIN rvlfVehicle V	ON MD.VehicleId = V.VehicleId
	INNER JOIN rvlfVehicleType VT ON V.VehicleTypeId = VT.VehicleTypeId
	WHERE	MD.BoxId = @bigEquipmentId
	AND		MD.OrganizationId = @bigOrganizationID
	AND		CM.IsDeleted = 0
	ORDER	BY CM.ControllerPositionId


	--============***=============================
	--VehicleTypeID = 2 ===> Precicon-R (1 to 24)
	--VehicleTypeID = 1 ===> Precicon-III (11 to 34)
	
	--Select * FROM @ControllerDetails order by PassageID,DCSIMID,ControllerID,ControllerPositionID
	--============***=============================
	DECLARE @tblPassageLoop Table(ControllerId bigint, EquipmentId bigint, PassageId tinyint, FieldId tinyint, DCSIMId tinyint,
								ControllerLocation tinyint, CntrlrIdByPass tinyint, ControllerName varchar(50), ControllerType tinyint)

	DECLARE @ESPLayoutHTML	Varchar(MAX) = ''

	DECLARE @PassageId tinyint
	SELECT  @PassageId = MIN(PassageId) From @ControllerDetails
	--Print 'Loop 1 Started passage : ' + cast (@PassageId as varchar(10))

	WHILE @PassageId IS NOT NULL
	BEGIN				
		--SELECT	dbo.adr_fn_GetESPLayout(999986, 1, 1, 1, 1, '', 1, 2) AS ESPLayout
		--FROM	@ControllerDetails	WHERE PassageId = @PassageId
		
		Declare @FieldName varchar(50)= null
		Select @FieldName = STUFF((SELECT ',' + Fieldname FROM adrFieldMaster where Isdelete=0 AND
							 FieldID in(Select Distinct(FieldID) from @ControllerDetails Where PassageId = @PassageId ) FOR XML PATH('')),1,1,'')
		

		SET	@ESPLayoutHTML = @ESPLayoutHTML + '<div id="divPassage_' + CAST(@PassageId AS VARCHAR(3)) + '" class="col-sm-5 Passage">'
											+ '<div class="col-sm-12 PassageCaption"><span><b>'
											+ (Select PassageName From adrPassageMaster Where PassageId = @PassageId) +' ('+ @FieldName+ ')' +'</b></span></div>'
		
		INSERT	INTO @tblPassageLoop
		SELECT	ControllerId, @bigEquipmentId, PassageId, FieldId, DCSIMId, ControllerLocation,
				ControllerPositionId AS CntrlrIdByPass, ControllerName, ControllerType 
		FROM	@ControllerDetails	WHERE	PassageId = @PassageId Order By PassageID,DCSIMID,ControllerID,ControllerPositionID
		--SELECT	ControllerId, @bigEquipmentId, PassageId, FieldId, DCSIMId, ControllerLocation,
		--		ROW_NUMBER() OVER (Order By ControllerPositionId) CntrlrIdByPass, ControllerName, ControllerType
		--FROM	@ControllerDetails	WHERE	PassageId = @PassageId
		
		--SELECT * FROM @tblPassageLoop
		--PRINT 'Select the Passage Values==> ' + cast (@PassageId as varchar(10))

		DECLARE @FieldId tinyint
		SELECT  @FieldId = MIN(FieldId) FROM @tblPassageLoop WHERE PassageId = @PassageId
		
		--PRINT 'Select Field values==> ' + cast (@FieldId as varchar(10))

		WHILE @FieldId IS NOT NULL
		BEGIN
		--PRINT 'Select Field values==> ' + cast (@FieldId as varchar(10)) + ' Started..'

			SELECT	@ESPLayoutHTML = @ESPLayoutHTML + '<div id="divField_' + CAST(@FieldId AS VARCHAR(3)) + '" class="$FieldCss$ Field">'  
			
			DECLARE @ControllerLoopId tinyint
			SELECT	@ControllerLoopId = MIN(ControllerId) From @tblPassageLoop  WHERE PassageId = @PassageId AND FieldId = @FieldId

			WHILE @ControllerLoopId IS NOT NULL
			BEGIN				
			--PRINT 'Select ControllerLoop values==> ' + cast (@ControllerLoopId as varchar(10))
			--PRINT '@bigEquipmentId : ' + cast(@bigEquipmentId as Varchar(20))+ '  @PassageId  : ' + cast(@PassageId  as Varchar(20))+ '  @FieldId :  ' + cast(@FieldId as Varchar(20))  +  '  ControllerId :  ' +cast(@ControllerLoopId as Varchar(20))
				SELECT	@ESPLayoutHTML = @ESPLayoutHTML + dbo.adr_fn_GetESPLayout(@bigEquipmentId, PassageId, FieldId, DCSIMId, CntrlrIdByPass, 
																					CntrlrIdByPass, ControllerName, ControllerType) 
				FROM	@tblPassageLoop	WHERE	ControllerId = @ControllerLoopId AND FieldId = @FieldId AND PassageId = @PassageId				

				SELECT	@ControllerLoopId = MIN(ControllerId) FROM @tblPassageLoop 
				WHERE	ControllerId > @ControllerLoopId AND FieldId = @FieldId AND PassageId = @PassageId
			END
			--SELECT	 *, dbo.adr_fn_GetESPLayout(PassageId, FieldId, DCSIMId, ControllerId, ControllerName, ControllerType) AS ESPLayout
			--FROM	@tblPassageLoop	WHERE FieldId = @FieldId and PassageId = @PassageId

			SET		@ESPLayoutHTML = @ESPLayoutHTML + '</div> '
			SELECT	@FieldId = MIN(FieldId) FROM @tblPassageLoop WHERE FieldId > @FieldId and PassageId = @PassageId
		END

		SET		@ESPLayoutHTML = @ESPLayoutHTML + '</div> '
		SELECT	@PassageId = MIN(PassageId) FROM @ControllerDetails WHERE PassageId > @PassageId
		IF @PassageId IS NOT NULL
			SET		@ESPLayoutHTML = @ESPLayoutHTML + '<img src="../images/img-gasflow.png" class="col-xs-1">'

		delete from @tblPassageLoop
	END

	SELECT	@ESPLayoutHTML as ESPLayout

	Select Top 1 ControllerName,LastReporteDateTime From ADRControllerMaster Where EquipmentID = @bigEquipmentId And IsDeleted = 0 order by LastReporteDateTime Desc

END
GO
/****** Object:  StoredProcedure [dbo].[adr_Sp_GetParameterDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [dbo].[adr_Sp_GetParameterDetails]
@bigQueryingUser bigint =NULL,
@OrganizationId bigint =NULL
AS   
/***********************************************************************************************************************************************************************/          
-- Name   : adr_Sp_GetParameterDetails @OrganizationId  = 86
-- Description  : To get the Parameter details for Trend chart.     
-- Author  : Asan raj N        
-- Created Date : Jan-31-2018  
/******************************************************************************************************************************************************/ 
 BEGIN
   SELECT a.ParamvalueId,ap.ParamName,m.EquipmentName,cm.ControllerName,a.MinValue,a.MaxValue,a.ParamId,a.ControllerId,a.EquipmentId,a.fleetId,a.VehicleId
   FROM 
   adr_ParamDetails a INNER JOIN rvlfParamMst ap ON a.ParamId = ap.ParamId 
   INNER JOIN adrControllerMaster cm ON cm.ControllerId = a.ControllerId 
   INNER JOIN rvlfMAKDevices M ON m.VehicleId = a.VehicleId 
   WHERE a.IsDeleted=0 AND a.OrganizationId=@OrganizationId  ORDER BY ParamvalueId
END
GO
/****** Object:  StoredProcedure [dbo].[adr_sp_LoadControllerDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 27-03-2017
-- Description:	Loads all the controllers for the current organization for ESP Controller Master.
--				adr_sp_LoadControllerDetails	231,'',null,86,18
-- =============================================
CREATE PROCEDURE [dbo].[adr_sp_LoadControllerDetails] 
	-- Add the parameters for the stored procedure here	
	@bigSiteId					bigint = NULL, 
	@bigEquipmentId				bigint = NULL, 
	@bigControllerId			bigint = NULL, 
	@bigOrganizationID			bigint = NULL, 
	@bigUserID					bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF @bigSiteId IS NOT NULL AND @bigSiteId <> 0
	BEGIN
		IF @bigEquipmentId IS NULL OR @bigEquipmentId = '' OR @bigEquipmentId = 0
		BEGIN
			SELECT	CM.ControllerId, CM.ControllerPositionId, CM.ControllerName, CM.ControllerSrNo, CM.ControllerType, CM.EquipmentId, CM.PassageId, CM.FieldId, 
					CM.DCSIMId, CM.ControllerLocation LocationId, MD.BoxId, MD.EquipmentName, PM.PassageName, FM.FieldName, DM.DCSIMName,
					CASE CM.ControllerLocation WHEN 1 THEN 'Inlet' WHEN 2 THEN 'Outlet' WHEN 3 THEN 'Intermediate' ELSE '' END AS ControllerLocation,
					CAST(CM.WarrantyStartDate AS DATE) as WarrantyStartDate, CAST(CM.WarrantyEndDate AS DATE) as WarrantyEndDate
			FROM	adrControllerMaster CM
			INNER	JOIN rvlfMAKDevices MD ON MD.BoxId = CM.EquipmentId
			INNER	JOIN adrPassageMaster PM ON PM.PassageId = CM.PassageId	
			INNER	JOIN adrFieldMaster FM ON FM.FieldId = CM.FieldId
			LEFT	OUTER	JOIN adrDCSIMMaster DM ON DM.DCSIMId = CM.DCSIMId
			WHERE	CM.IsActive = 1 
			AND		CM.IsDeleted = 0
			AND		MD.OrganizationId = @bigOrganizationID
			AND		CM.EquipmentId in 
					(Select MD.BoxId From rvlfMAKDevices MD 
					Inner Join rvlfBoxId B On B.BoxId = MD.BoxId
					Inner Join rvlfVehicleAssignment VA on VA.BoxId = B.BoxId
					Inner Join rvlfVehicle V on V.VehicleId = VA.VehicleId
					Inner Join rvlfFleetVehicles FV On FV.VehicleId = V.VehicleId 
					Where FV.FleetId = @bigSiteId)
			AND		((@bigControllerId IS NULL OR @bigControllerId = '' OR @bigControllerId = 0) OR CM.ControllerId = @bigControllerId)
			ORDER	BY MD.BoxId, CM.DCSIMId, CM.PassageId, CM.FieldId, CM.ControllerPositionId
		END
		ELSE
		BEGIN
			SELECT	CM.ControllerId, CM.ControllerPositionId, CM.ControllerName, CM.ControllerSrNo, CM.ControllerType, CM.EquipmentId, CM.PassageId, CM.FieldId, 
					CM.DCSIMId, CM.ControllerLocation LocationId, MD.BoxId, MD.EquipmentName, PM.PassageName, FM.FieldName, DM.DCSIMName,
					CASE CM.ControllerLocation WHEN 1 THEN 'Inlet' WHEN 2 THEN 'Outlet' WHEN 3 THEN 'Intermediate' ELSE '' END AS ControllerLocation,
					CAST(CM.WarrantyStartDate AS DATE) as WarrantyStartDate, CAST(CM.WarrantyEndDate AS DATE) as WarrantyEndDate
			FROM	adrControllerMaster CM
			INNER	JOIN rvlfMAKDevices MD ON MD.BoxId = CM.EquipmentId
			INNER	JOIN adrPassageMaster PM ON PM.PassageId = CM.PassageId	
			INNER	JOIN adrFieldMaster FM ON FM.FieldId = CM.FieldId
			LEFT	OUTER	JOIN adrDCSIMMaster DM ON DM.DCSIMId = CM.DCSIMId
			WHERE	CM.IsActive = 1 
			AND		CM.IsDeleted = 0
			AND		MD.OrganizationId = @bigOrganizationID
			AND		((@bigEquipmentId IS NULL OR @bigEquipmentId = '' OR @bigEquipmentId = 0) OR CM.EquipmentId = @bigEquipmentId)
			AND		((@bigControllerId IS NULL OR @bigControllerId = '' OR @bigControllerId = 0) OR CM.ControllerId = @bigControllerId)
			ORDER	BY MD.BoxId, CM.DCSIMId, CM.PassageId, CM.FieldId, CM.ControllerPositionId
		END
	END
	ELSE
	BEGIN
		SELECT	CM.ControllerId, CM.ControllerPositionId, CM.ControllerName, CM.ControllerSrNo, CM.ControllerType, CM.EquipmentId, CM.PassageId, CM.FieldId, 
				CM.DCSIMId, CM.ControllerLocation LocationId, MD.BoxId, MD.EquipmentName, PM.PassageName, FM.FieldName, DM.DCSIMName,
				CASE CM.ControllerLocation WHEN 1 THEN 'Inlet' WHEN 2 THEN 'Outlet' WHEN 3 THEN 'Intermediate' ELSE '' END AS ControllerLocation,
				CAST(CM.WarrantyStartDate AS DATE) as WarrantyStartDate, CAST(CM.WarrantyEndDate AS DATE) as WarrantyEndDate
		FROM	adrControllerMaster CM
		INNER	JOIN rvlfMAKDevices MD ON MD.BoxId = CM.EquipmentId
		INNER	JOIN adrPassageMaster PM ON PM.PassageId = CM.PassageId	
		INNER	JOIN adrFieldMaster FM ON FM.FieldId = CM.FieldId
		LEFT	OUTER	JOIN adrDCSIMMaster DM ON DM.DCSIMId = CM.DCSIMId
		WHERE	CM.IsActive = 1 
		AND		CM.IsDeleted = 0
		AND		MD.OrganizationId = @bigOrganizationID
		AND		((@bigEquipmentId IS NULL OR @bigEquipmentId = '' OR @bigEquipmentId = 0) OR CM.EquipmentId = @bigEquipmentId)
		AND		((@bigControllerId IS NULL OR @bigControllerId = '' OR @bigControllerId = 0) OR CM.ControllerId = @bigControllerId)
		ORDER	BY MD.BoxId, CM.DCSIMId, CM.PassageId, CM.FieldId, CM.ControllerPositionId
	END
END

GO
/****** Object:  StoredProcedure [dbo].[adr_sp_LoadControllersByDCSIM]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 06-04-2017
-- Description:	Loads all the controllers for the Selected ESP and DCSIM.
--				adr_sp_LoadControllersByDCSIM	999981,0,86,18
-- =============================================
CREATE PROCEDURE [dbo].[adr_sp_LoadControllersByDCSIM] 
	-- Add the parameters for the stored procedure here	
	@bigEquipmentId				bigint = NULL, 
	@tintDSCIMId				bigint = NULL, 
	@bigOrganizationID			bigint = NULL, 
	@bigUserID					bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT	CM.ControllerId, CM.ControllerName,* 
	FROM	adrControllerMaster CM
	INNER	JOIN rvlfMAKDevices MD ON MD.BoxId = CM.EquipmentId
	INNER	JOIN adrPassageMaster PM ON PM.PassageId = CM.PassageId	
	INNER	JOIN adrFieldMaster FM ON FM.FieldId = CM.FieldId
	LEFT OUTER	JOIN adrDCSIMMaster DM ON DM.DCSIMId = CM.DCSIMId
	WHERE	CM.IsActive = 1 
	AND		CM.IsDeleted = 0
	AND		MD.OrganizationId = @bigOrganizationID
	AND		((@bigEquipmentId IS NULL OR @bigEquipmentId = '') OR CM.EquipmentId = @bigEquipmentId)
	AND		((@tintDSCIMId IS NULL OR @tintDSCIMId = '') OR CM.DCSIMId = @tintDSCIMId)
END

GO
/****** Object:  StoredProcedure [dbo].[adr_sp_LoadControllersByVehicleId]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 27-03-2017
-- Description:	Loads all the controllers for the current organization for ESP Controller Master.
--				adr_sp_LoadControllersByVehicleId	805,86,292
-- =============================================
CREATE PROCEDURE [dbo].[adr_sp_LoadControllersByVehicleId] 
	-- Add the parameters for the stored procedure here	
	@bigVehicleId				BIGINT = NULL, 
	@bigOrganizationID			BIGINT = NULL, 
	@bigUserID					BIGINT = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @bigEquipmentId		BIGINT = NULL
	SELECT	@bigEquipmentId = MD.BoxId 
	FROM	rvlfVehicleAssignment VA
	INNER	JOIN rvlfMAKDevices MD ON VA.BoxId = MD.BoxId
	WHERE	VA.VehicleId = @bigVehicleId
    
	-- Insert statements for procedure here
	SELECT	CM.ControllerId, CM.ControllerPositionId, CM.ControllerName, CM.ControllerSrNo, CM.ControllerType, CM.EquipmentId, CM.PassageId, CM.FieldId, 
			CM.DCSIMId, CM.ControllerLocation LocationId, MD.BoxId, MD.EquipmentName, PM.PassageName, FM.FieldName, DM.DCSIMName,
			CASE CM.ControllerLocation WHEN 1 THEN 'Inlet' WHEN 2 THEN 'Outlet' WHEN 3 THEN 'Intermediate' ELSE '' END AS ControllerLocation,
			CAST(CM.WarrantyStartDate AS DATE) as WarrantyStartDate, CAST(CM.WarrantyEndDate AS DATE) as WarrantyEndDate
	FROM	adrControllerMaster CM
	INNER	JOIN rvlfMAKDevices MD ON MD.BoxId = CM.EquipmentId
	INNER	JOIN adrPassageMaster PM ON PM.PassageId = CM.PassageId	
	INNER	JOIN adrFieldMaster FM ON FM.FieldId = CM.FieldId
	LEFT	OUTER JOIN adrDCSIMMaster DM ON DM.DCSIMId = CM.DCSIMId
	WHERE	CM.IsActive = 1 
	AND		CM.IsDeleted = 0
	AND		MD.OrganizationId = @bigOrganizationID
	AND		((@bigEquipmentId IS NULL OR @bigEquipmentId = '') OR CM.EquipmentId = @bigEquipmentId)
	ORDER	BY cm.DCSIMId, ControllerPositionId ASC
END
GO
/****** Object:  StoredProcedure [dbo].[adr_sp_LoadSitesWithESPs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 01-04-2017
-- Description:	Load Sites and ESP data for ESP Layout.
--				adr_sp_LoadSitesWithESPs 86,457
-- =============================================
CREATE PROCEDURE [dbo].[adr_sp_LoadSitesWithESPs] 
	-- Add the parameters for the stored procedure here
	@bigOrganizationID	bigint = NULL, 
	@bigUserID			bigint = NULL,
	@IsAnglerAdmin		bit = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here	
	
	SELECT	* FROM	rvlfFleet F
	INNER	JOIN rvlfFleetUsers FU ON F.FleetId = FU.FleetId
	WHERE	OrganizationId = @bigOrganizationID
	AND		(@IsAnglerAdmin = 1 Or FU.UserId = @bigUserID)

	SELECT	MD.BoxId, EquipmentName, EquipmentSrNo, V.VehicleID, FV.FleetId 
	FROM	rvlfMAKDevices MD
	INNER	JOIN rvlfBoxID	B	ON MD.BoxId = B.BoxId
	INNER	JOIN rvlfVehicle V	ON MD.VehicleId = V.VehicleId
	INNER	JOIN rvlfFleetVehicles FV ON V.VehicleId = FV.VehicleId
	WHERE	MD.OrganizationId = @bigOrganizationID 
	AND		MD.IsDelete = 0
	AND		FV.IsActive = 1
END

GO
/****** Object:  StoredProcedure [dbo].[adr_sp_SaveandupdateParameters]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[adr_sp_SaveandupdateParameters]
@intBoxId  varchar(50)=NULL,
@FleetId bigint =NULL,
@ControllerId bigint =NULL,
@vehicleId bigint =NULL,
@ParamId int = NULL,
@ParamvalueId int = 0,
@MaxValue int = NULL,
@MinValue int = NULL,
@userId bigint =NULL,
@OrganizationId bigint =NULL,
@OperationType int =NULL,
@IsDeleted int =0
AS
-- =============================================
-- Author:		Asan Raj N
-- Create date: 27-Jan-2018
-- Description:	Save,Update and Delete parameter details
--				adr_sp_SaveandupdateParameters 
-- =============================================
BEGIN
DECLARE @bigEquipmentId		BIGINT = NULL
	SELECT	@bigEquipmentId = MD.BoxId 
	FROM	rvlfVehicleAssignment VA
	INNER	JOIN rvlfMAKDevices MD ON VA.BoxId = MD.BoxId
	WHERE	VA.VehicleId = @vehicleId

select @bigEquipmentId

IF(@ParamvalueId =0 OR @OperationType=1)
BEGIN
  INSERT INTO adr_ParamDetails(ParamId,ControllerId,EquipmentId,MaxValue,MinValue,Createdon,CreatedBY,OrganizationId,IsDeleted,FleetId,vehicleId)
  VALUES(@ParamId,@ControllerId,@bigEquipmentId,@MaxValue,@MinValue,GETDATE(),@userId,@OrganizationId,0,@FleetId,@vehicleId)
END
ELSE IF(@OperationType=2)
 BEGIN
  UPDATE adr_ParamDetails SET ParamId = @ParamId,ControllerId=@ControllerId,EquipmentId=@bigEquipmentId,MaxValue=@MaxValue,
  MinValue=@MinValue,ModifiedOn = GETDATE(),ModifiedBy=@userId,OrganizationId=@OrganizationId,FleetId = @FleetId,vehicleId=@vehicleId
  WHERE ParamvalueId=@ParamvalueId
 END
ELSE 
 BEGIN
  UPDATE adr_ParamDetails SET IsDeleted =@IsDeleted WHERE ParamvalueId=@ParamvalueId
 END 
END
GO
/****** Object:  StoredProcedure [dbo].[adr_sp_SaveUpdateDeleteController]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 27-03-2017
-- Description:	Save, Update and Delete operations for ESP Controller Master.
-- =============================================
CREATE PROCEDURE [dbo].[adr_sp_SaveUpdateDeleteController] 
	-- Add the parameters for the stored procedure here
	@bigEquipmentId				bigint = NULL,
	@bigControllerId			bigint = NULL,
	@intControllerPositionId	int = NULL,
	@vcControllerName			varchar(50) = NULL,
	@vcControllerSrNo			varchar(100) = NULL,
	@tiPassageId				tinyint,
	@tiFieldId					tinyint,
	@tiDCSIMId					tinyint,
	@tiControllerLocationId		tinyint,
	@dtWarrantyStartDate		datetime,
	@dtWarrantyEndDate			datetime,
	@bigOrganizationID			bigint = NULL, 
	@bigUserID					bigint = NULL,
	@OperationType				int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF(@OperationType = 1)
	BEGIN
		INSERT	INTO adrControllerMaster(EquipmentId, ControllerPositionId, ControllerName, ControllerSrNo, PassageId, FieldId, 
										DCSIMId, ControllerLocation, WarrantyStartDate, WarrantyEndDate, IsActive, CreatedBy, CreatedDate)
		VALUES	(@bigEquipmentId, @intControllerPositionId, @vcControllerName, @vcControllerSrNo, @tiPassageId, @tiFieldId, 
				@tiDCSIMId, @tiControllerLocationId, @dtWarrantyStartDate, @dtWarrantyEndDate, 1, @bigUserID, GETDATE())
	END
	ELSE IF(@OperationType = 2)
	BEGIN
		UPDATE	adrControllerMaster 
		SET		EquipmentId = @bigEquipmentId,
				ControllerPositionId = @intControllerPositionId,
				ControllerName = @vcControllerName, 
				ControllerSrNo = @vcControllerSrNo, 
				PassageId = @tiPassageId,
				FieldId = @tiFieldId,
				DCSIMId = @tiDCSIMId,
				ControllerLocation = @tiControllerLocationId,
				WarrantyStartDate = @dtWarrantyStartDate,
				WarrantyEndDate = @dtWarrantyEndDate,
				ModifiedBy = @bigUserID,
				ModifiedDate = GETDATE()
		WHERE	ControllerID = @bigControllerId
	END
	ELSE
	BEGIN
		UPDATE	adrControllerMaster 
		SET		IsDeleted = 1
		WHERE	ControllerID = @bigControllerId
	END
END

GO
/****** Object:  StoredProcedure [dbo].[adr_sp_SaveUpdateDeleteESPConfigData]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 27-03-2017
-- Description:	Save, Update and Delete operations for ESP Configuration Shortcut data like Passages, Fields and DCSIMs.
-- =============================================
CREATE PROCEDURE [dbo].[adr_sp_SaveUpdateDeleteESPConfigData] 
	-- Add the parameters for the stored procedure here	
	@tiPassageId				tinyint = NULL,
	@tiFieldId					tinyint = NULL,
	@tiDCSIMId					tinyint = NULL,
	@vcPopupDataName			varchar(50) = NULL,
	@vcPopupDataDescription		varchar(50) = NULL,
	@bigOrganizationID			bigint = NULL, 
	@bigUserID					bigint = NULL,
	@OperationType				int = NULL,
	@DataType					varchar(1) = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF(@OperationType = 1)
	BEGIN
		IF(@DataType = 'P')
		BEGIN
			INSERT	INTO adrPassageMaster(PassageName, [Description])
			VALUES	(@vcPopupDataName, @vcPopupDataDescription)
		END
		IF(@DataType = 'F')
		BEGIN
			INSERT	INTO adrFieldMaster(FieldName, [Description])
			VALUES	(@vcPopupDataName, @vcPopupDataDescription)
		END
		IF(@DataType = 'D')
		BEGIN
			INSERT	INTO adrDCSIMMaster(DCSIMName, [Description])
			VALUES	(@vcPopupDataName, @vcPopupDataDescription)
		END
	END
	ELSE IF(@OperationType = 2)
	BEGIN
		IF(@DataType = 'P')
		BEGIN
			UPDATE	adrPassageMaster
			SET		PassageName = @vcPopupDataName, 
					[Description] = @vcPopupDataDescription
			WHERE	PassageId = @tiPassageId
		END
		IF(@DataType = 'F')
		BEGIN
			UPDATE	adrFieldMaster
			SET		FieldName = @vcPopupDataName, 
					[Description] = @vcPopupDataDescription
			WHERE	FieldId = @tiFieldId
		END
		IF(@DataType = 'D')
		BEGIN
			UPDATE	adrDCSIMMaster
			SET		DCSIMName = @vcPopupDataName, 
					[Description] = @vcPopupDataDescription
			WHERE	DCSIMId = @tiDCSIMId
		END
	END
	ELSE
	BEGIN
		IF(@DataType = 'P')
		BEGIN
			UPDATE	adrPassageMaster
			SET		IsDelete = 1
			WHERE	PassageId = @tiPassageId
		END
		IF(@DataType = 'F')
		BEGIN
			UPDATE	adrFieldMaster
			SET		IsDelete = 1
			WHERE	FieldId = @tiFieldId
		END
		IF(@DataType = 'D')
		BEGIN
			UPDATE	adrDCSIMMaster
			SET		IsDelete = 1
			WHERE	DCSIMId = @tiDCSIMId
		END
	END
END

GO
/****** Object:  StoredProcedure [dbo].[AuditTA_SP_GetAuditTrailSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [dbo].[AuditTA_SP_GetAuditTrailSettings]
@bigOrganizationId			bigint	= NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here				
	
	SELECT	o.id AS 'TableId',
			CAST(o.Name AS varchar(75)) AS 'TableName', 
			CAST(p.Value AS varchar(75)) AS 'Description',
			SUBSTRING(CAST(p.Value AS varchar(75)),LEN(CAST(p.Value AS varchar(75))) 
			- CHARINDEX('|', REVERSE(CAST(p.Value AS varchar(75)))) + 2,5) as ModuleId,m.ModuleName,ISNULL(AT.Status,0) Status,
			STUFF((SELECT ',' + CAST(TableID AS NVARCHAR) FROM rvlfAuditTable Where Status = 1 FOR XML PATH('')), 1, 1, '') SelectedTablesList
	FROM	sysobjects o
	INNER	JOIN sys.extended_properties p	ON o.id = p.major_id
	INNER	JOIN rvlfModule m				
	ON		SUBSTRING(CAST(p.Value AS varchar(75)),LEN(CAST(p.Value AS varchar(75))) - CHARINDEX('|', REVERSE(CAST(p.Value AS varchar(75)))) + 2,5) = m.ModuleID
	LEFT	OUTER JOIN rvlfAuditTable AT	ON o.id = AT.TableID 
	WHERE	p.minor_id = 0 AND o.xtype='U' and o.name like 'rvlf%'
	ORDER	BY o.id, o.Name			 
		
	SELECT	o.id AS 'TableId',
			CAST(o.id AS nvarchar(100)) + CAST(c.colid AS nvarchar(10)) AS 'ColumnId',
			CAST(c.Name AS varchar(75)) AS 'ColumnName', 
			CAST(p.Value AS varchar(max)) AS 'Description', 
			ISNULL(AF.InsertBit,0) InsertBit, ISNULL(AF.UpdateBit,0) UpdateBit, ISNULL(AF.DeleteBit,0) DeleteBit, ISNULL(AF.Status,0) Status,
			STUFF((SELECT ',' + CAST(FieldID AS NVARCHAR) FROM rvlfAuditField Where InsertBit = 1 FOR XML PATH('')), 1, 1, '') InsertColumnsList,  
			STUFF((SELECT ',' + CAST(FieldID AS NVARCHAR) FROM rvlfAuditField Where UpdateBit = 1 FOR XML PATH('')), 1, 1, '') UpdateColumnsList, 
			STUFF((SELECT ',' + CAST(FieldID AS NVARCHAR) FROM rvlfAuditField Where DeleteBit = 1 FOR XML PATH('')), 1, 1, '') DeleteColumnsList
	FROM	sysobjects o 
	INNER	JOIN sys.extended_properties p	ON o.id = p.major_id
	INNER	JOIN dbo.syscolumns c			ON p.minor_id = c.colorder
	LEFT	OUTER JOIN rvlfAuditField AF	ON AF.FieldID = CAST(o.id AS NVARCHAR(100)) + CAST(c.colid AS NVARCHAR(10))
	WHERE	o.id = c.id AND o. id in (SELECT o.id FROM sysobjects o INNER JOIN sys.extended_properties p ON o.id = p.major_id
		 								WHERE p.minor_id = 0 AND o.xtype='U' and o.name like 'rvlf%')
	and		p.name ='ADT_Description'

	
	--SELECT	AuditTableId, TableID, TableName, TableDescription, Status, M.ModuleName, 
	--		STUFF((SELECT ',' + CAST(TableID AS NVARCHAR) FROM rvlfAuditTable Where Status = 1 FOR XML PATH('')), 1, 1, '') SelectedTablesList  
	--FROM	rvlfAuditTable AT
	--INNER	JOIN rvlfModule M ON AT.ModuleId = M.ModuleID

	--SELECT	AuditFieldId, FieldID ColumnId, TableID, FieldName ColumnName, FieldDescription Description, InsertBit, UpdateBit, DeleteBit, Status,
	--		STUFF((SELECT ',' + CAST(FieldID AS NVARCHAR) FROM rvlfAuditField Where InsertBit = 1 FOR XML PATH('')), 1, 1, '') InsertColumnsList,  
	--		STUFF((SELECT ',' + CAST(FieldID AS NVARCHAR) FROM rvlfAuditField Where UpdateBit = 1 FOR XML PATH('')), 1, 1, '') UpdateColumnsList, 
	--		STUFF((SELECT ',' + CAST(FieldID AS NVARCHAR) FROM rvlfAuditField Where DeleteBit = 1 FOR XML PATH('')), 1, 1, '') DeleteColumnsList  
	--FROM	rvlfAuditField
END

GO
/****** Object:  StoredProcedure [dbo].[AuditTA_sp_InserAuditTable]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [dbo].[AuditTA_sp_InserAuditTable]  
	-- Add the parameters for the stored procedure here
	--@tableName			NVARCHAR(100),
	--@tableDescription		NVARCHAR(100),
	--@tableStatus			BIT,
	@vcTableIDs				VARCHAR(1000) = NULL,  
	@vcInsertColumnIDs		VARCHAR(1000) = NULL,
	@vcUpdateColumnIDs		VARCHAR(1000) = NULL,
	@vcDeleteColumnIDs		VARCHAR(1000) = NULL,
	@bigUserId				BIGINT	= NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	
	--Tables List
		
	DECLARE @TablesList Table(TableId bigint, TableName nvarchar(100), Description nvarchar(1000), ModuleId bigint, ModuleName nvarchar(100), Status bit)
	Insert Into @TablesList (TableId,TableName,Description,ModuleId,ModuleName)
	Exec [AuditTA_SP_SelectAllTableNames]
	
	Update @TablesList Set Status = Case When TableId In (Select * From rvlf_fn_ConvertArrayToTable(@vcTableIDs,',')) Then 1 Else 0 End
	
	DELETE FROM rvlfAuditTable
	INSERT INTO rvlfAuditTable(TableID, TableName, TableDescription, Status, ModuleId, CreatedBy, CreatedDate)
	Select TableID, TableName, Description, Status, ModuleId, @bigUserId, GETUTCDATE() From @TablesList

	SET @vcTableIDs = STUFF((SELECT ',' + CAST(TableId AS VARCHAR) FROM @TablesList FOR XML PATH('')), 1, 1, '')
	--Columns List

	DECLARE @ColumnList Table(TableId bigint, ColumnId bigint, ColumnName nvarchar(100), Description nvarchar(1000), 
							  InsertStatus bit, UpdateStatus bit, DeleteStatus bit, Status bit)
	Insert Into @ColumnList (TableId, ColumnId, ColumnName, Description)
	Exec [AuditTA_SP_SelectAllColumnNames] @vcTableIDs
	
	Update @ColumnList Set InsertStatus  = Case When ColumnId In (Select * From rvlf_fn_ConvertArrayToTable(@vcInsertColumnIDs,',')) Then 1 Else 0 End	
	Update @ColumnList Set UpdateStatus  = Case When ColumnId In (Select * From rvlf_fn_ConvertArrayToTable(@vcUpdateColumnIDs,',')) Then 1 Else 0 End
	Update @ColumnList Set DeleteStatus  = Case When ColumnId In (Select * From rvlf_fn_ConvertArrayToTable(@vcDeleteColumnIDs,',')) Then 1 Else 0 End
	Update @ColumnList Set Status		 = Case When InsertStatus = 1 Or UpdateStatus = 1 Or DeleteStatus = 1 Then 1 Else 0 End

	DELETE FROM rvlfAuditField
	INSERT INTO rvlfAuditField(TableID, FieldID, FieldName, FieldDescription, InsertBit, UpdateBit, DeleteBit, Status, CreatedBy, CreatedDate)
	Select *, @bigUserId, GETUTCDATE() From @ColumnList
	
		
	-- Trigger creation code invoke
	
	DECLARE @TableNames nvarchar(MAX), @InsertFields nvarchar(MAX), @UpdateFields nvarchar(MAX), @DeleteFields nvarchar(MAX)

	DECLARE @TableId bigint
	SELECT @TableId = MIN(TableId) From @TablesList Where Status = 1

	WHILE @TableId IS NOT NULL
	BEGIN
		SELECT	@TableNames   = STUFF((SELECT ',' + TableName FROM @TablesList Where TableId = @TableId FOR XML PATH('')), 1, 1, '') 
		SELECT	@InsertFields = STUFF((SELECT ',' + ColumnName FROM @ColumnList Where TableId = @TableId and InsertStatus = 1 FOR XML PATH('')), 1, 1, '')
		SELECT	@UpdateFields = STUFF((SELECT ',' + ColumnName FROM @ColumnList Where TableId = @TableId and UpdateStatus = 1 FOR XML PATH('')), 1, 1, '')
		SELECT	@DeleteFields = STUFF((SELECT ',' + ColumnName FROM @ColumnList Where TableId = @TableId and DeleteStatus = 1 FOR XML PATH('')), 1, 1, '')

		--Select @TableNames TableNames, @InsertFields InsertFields, @UpdateFields UpdateFields, @DeleteFields DeleteFields
	
		Exec [AuditTA_sp_CreateTrigger] @TableNames, @InsertFields, @UpdateFields, @DeleteFields
	
		SELECT @TableId = MIN(TableId) From @TablesList Where TableId > @TableId and Status = 1
	END
	

	--Disabling Triggers for a Tables which were selected previously but not on the current operation
	
	SELECT @TableId = MIN(TableId) From @TablesList Where Status = 0
	
	DECLARE @Sql nvarchar(1000) = null

	WHILE @TableId IS NOT NULL
	BEGIN
		SELECT	@TableNames = TableName FROM @TablesList Where TableId = @TableId
		SET		@Sql = 'ALTER TABLE [dbo].['+ @TableNames +'] DISABLE TRIGGER ALL'
		EXEC	(@Sql)
		SELECT	@TableId = MIN(TableId) From @TablesList Where TableId > @TableId and Status = 0
	END


	---- Old backup ----
	
	--DECLARE @tableId AS DECIMAL
	--SELECT tableId = (select @@identity) 
	--DECLARE @recCount as int
	--SET @recCount = (SELECT COUNT(*) FROM rvlfAuditTable WHERE TableName=@tableName)
	
	--IF(@recCount>0)
	--Begin
	--	UPDATE rvlfAuditTable SET status=@tableStatus WHERE TableName=@tableName
	--	SELECT tableId = (SELECT TableId FROM rvlfAuditTable WHERE TableName=@tableName)
	--End
	--ELSE
	--Begin
	--	INSERT INTO rvlfAuditTable(TableName, TableDescription, Status) VALUES(@tableName, @tableDescription, @tableStatus)
	--	SELECT tableId = (select @@identity)
	--End    
END
-- [AuditTA_sp_InserAuditTable]  '334780400,782625831,830626002,1712881319,1920882060',
--'3347804002,3347804004,3347804007,3347804009,33478040012,33478040013,33478040014,33478040020,8306260021,8306260022,7826258311,7826258312',
--'3347804002,3347804004,3347804007,3347804009,33478040012,33478040013,33478040014,33478040020,8306260021,8306260022,7826258311',
--'3347804002,3347804004,3347804007,3347804009,33478040012,33478040013,33478040014,33478040020,8306260021,8306260022', 18


--declare @sql nvarchar(100)
--select @sql = 'drop trigger ' + so.name
--from sysobjects so, syscomments sc
--where type = 'TR'
--and so.id = sc.id
--and so.name like '%rvlfLandmark%'
--Select @sql
--exec @sql


GO
/****** Object:  StoredProcedure [dbo].[AuditTA_sp_InsertAuditField]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[AuditTA_sp_InsertAuditField] 
	-- Add the parameters for the stored procedure here
	@tableId decimal,
    @fieldName nvarchar(100),
	@fieldDescription nvarchar(100),
    @insertBitStatus bit,
    @updateBitStatus bit,
    @deleteBitStatus bit,
    @fieldStatus bit
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	declare @recCount as int
	set @recCount = (select count(*) from rvlfAuditField where TableID=@tableId and FieldName=@fieldName)
	Declare @TableName varchar(max)
	Declare @DataType varchar(40)
	set @TableName=(select TableName from rvlfAuditTable where TableID=@tableId)
		
	select @DataType=name from sys.types where user_type_id=(
	select user_type_id from sys.columns where object_id=(select object_id from sys.tables where name=CONVERT(varchar(max),@TableName))
	and name=+convert(varchar(max),@fieldName))
	
	if (@recCount>0)
		Begin
			update rvlfAuditField set DataType=@DataType,InsertBit=@insertBitStatus,UpdateBit=@updateBitStatus,DeleteBit=@deleteBitStatus,Status= @fieldStatus 
			where TableID=@tableId and FieldName=@fieldName
		End
	Else
		Begin
			INSERT INTO rvlfAuditField(TableID,FieldName,FieldDescription,InsertBit,UpdateBit,DeleteBit,Status,DataType) VALUES(@tableId,@fieldName,@fieldDescription,@insertBitStatus,@updateBitStatus,@deleteBitStatus,@fieldStatus,@DataType)
		End	
END



GO
/****** Object:  StoredProcedure [dbo].[AuditTA_sp_IsAuditTrailSaved]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [dbo].[AuditTA_sp_IsAuditTrailSaved] 
	-- Add the parameters for the stored procedure here
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT COUNT(*) FROM rvlfAuditTable
    
END

GO
/****** Object:  StoredProcedure [dbo].[AuditTA_sp_SelectAllAuditColumnNames]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [dbo].[AuditTA_sp_SelectAllAuditColumnNames] 
	-- Add the parameters for the stored procedure here
	@tableId decimal
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT * FROM rvlfAuditField WHERE TableID = @tableId
END

GO
/****** Object:  StoredProcedure [dbo].[AuditTA_sp_SelectAllAuditRecords]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE Proc [dbo].[AuditTA_sp_SelectAllAuditRecords]
(
@OprDate datetime=null,
@intBoxID varchar(1500)=null,--moduleid
@bigOrganizationId bigint=null,
@bigQueryingUser bigint,
@dtStartDate datetime=null,
@dtEndDate datetime=null
)
as
--Pages - Report - audit trail report, View audit trail in configuration
--AuditTA_sp_SelectAllAuditRecords null,null,6,290,'01-may-2016 08:00 AM','05-may-2016 10:00 PM'
begin
 DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                            
  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit                            
                               
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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)                                   
  FROM rvlfUserPreferences up                             
   INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                             
  WHERE up.UserId = @bigQueryingUser  
  SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))
 
select aop.FieldID,aop.ID,isnull(aop.NewValue,'-') as NewValue,isnull(aop.OldValue,'-') as OldValue,aop.Opr,
--Convert(varchar,aop.OprDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(aop.OprDate as time),22) as OprDate,
OprDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,aop.OprDate),        

aop.RecordID,aop.TableID,aop.UserId,at.TableName,af.FieldName,
m.ModuleID,m.ModuleName,u.UserName 
, Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,            
 Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,            
 Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+
  Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate    
from rvlfAuditOperation Aop inner join rvlfAuditTable AT
on aop.TableID=AT.TableID
inner join rvlfAuditField AF on aop.FieldID=af.FieldID
inner join rvlfModule M on at.ModuleId=m.ModuleID
left join rvlfUser u on Aop.userid=u.UserId
where at.Status=1 and af.Status=1 and ((af.InsertBit=1 and aop.Opr='Insert') or (af.UpdateBit=1 and aop.Opr='Update')or(af.DeleteBit=1 and aop.Opr='Delete'))
AND (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR 
     aop.OprDate BETWEEN @dtStartDate AND @dtEndDate)   
	 AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' or AT.ModuleId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))
	 --and u.OrganizationId=@bigOrganizationId
end

 
 
  

GO
/****** Object:  StoredProcedure [dbo].[AuditTA_sp_SelectAllAuditTableNames]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[AuditTA_sp_SelectAllAuditTableNames] 
	-- Add the parameters for the stored procedure here
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	

	select M.Moduleid,ModuleName from rvlfmodule M inner join rvlfaudittable AT on m.moduleid=AT.moduleid
where at.status=1
group by  M.Moduleid,ModuleName
SELECT * FROM rvlfAuditTable WHERE Status = 1

END
 

GO
/****** Object:  StoredProcedure [dbo].[AuditTA_SP_SelectAllColumnNames]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [dbo].[AuditTA_SP_SelectAllColumnNames]
	@tableIds nvarchar(1000)
AS
BEGIN	
	SET NOCOUNT ON;
    -- Insert statements for procedure here
		DECLARE @version as nvarchar(50)
		SET @version = ''
		SET @version = (SELECT left(@@version,26))		
		
		SELECT	o.id AS 'TableId',
				CAST(o.id AS nvarchar(100)) + CAST(c.colid AS nvarchar(10)) AS 'ColumnId',
				CAST(c.Name AS varchar(75)) AS 'ColumnName', 
				CAST(p.Value AS varchar(max)) AS 'Description' 
		FROM	sysobjects o 
		INNER	JOIN sys.extended_properties p ON o.id = p.major_id
		INNER	JOIN dbo.syscolumns c			 ON p.minor_id = c.colorder
		WHERE	o.id = c.id AND o.id IN (Select * From rvlf_fn_ConvertArrayToTable(@tableIds,',')) AND p.minor_id <> 0 AND p.name ='ADT_Description'
		ORDER	BY o.id, p.minor_id		
END


GO
/****** Object:  StoredProcedure [dbo].[AuditTA_SP_SelectAllTableNames]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[AuditTA_SP_SelectAllTableNames]	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here				
			SELECT o.id AS 'TableId',
			CAST(o.Name AS varchar(75)) AS 'TableName', 
			CAST(p.Value AS varchar(75)) AS 'Description',
			SUBSTRING(CAST(p.Value AS varchar(75)),LEN(CAST(p.Value AS varchar(75))) 
			- CHARINDEX('|', REVERSE(CAST(p.Value AS varchar(75)))) + 2,5) as ModuleId,m.ModuleName
			FROM sysobjects o
			INNER JOIN sys.extended_properties p
			ON o.id = p.major_id
			inner join rvlfModule m on SUBSTRING(CAST(p.Value AS varchar(75)),LEN(CAST(p.Value AS varchar(75))) 
			- CHARINDEX('|', REVERSE(CAST(p.Value AS varchar(75)))) + 2,5)=m.ModuleID
			WHERE p.minor_id = 0 AND o.xtype='U' and o.name like 'rvlf%'
			ORDER BY o.id, o.Name			 
END

GO
/****** Object:  StoredProcedure [dbo].[AuditTA_SP_SelectAllTablesAndColumns]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [dbo].[AuditTA_SP_SelectAllTablesAndColumns]	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here				
	SELECT	o.id AS 'TableId',
			CAST(o.Name AS varchar(75)) AS 'TableName', 
			CAST(p.Value AS varchar(75)) AS 'Description',
			SUBSTRING(CAST(p.Value AS varchar(75)),LEN(CAST(p.Value AS varchar(75))) 
			- CHARINDEX('|', REVERSE(CAST(p.Value AS varchar(75)))) + 2,5) as ModuleId,m.ModuleName
	FROM	sysobjects o
	INNER	JOIN sys.extended_properties p	ON o.id = p.major_id
	inner join rvlfModule m on SUBSTRING(CAST(p.Value AS varchar(75)),LEN(CAST(p.Value AS varchar(75))) 
			- CHARINDEX('|', REVERSE(CAST(p.Value AS varchar(75)))) + 2,5)=m.ModuleID
	WHERE	p.minor_id = 0 AND o.xtype='U' and o.name like 'rvlf%'
	ORDER	BY o.id, o.Name			 
		
		--UNION ALL
					
	SELECT	o.id AS 'TableId',
			CAST(o.id AS nvarchar(100)) + CAST(c.colid AS nvarchar(10)) AS 'ColumnId',
			CAST(c.Name AS varchar(75)) AS 'ColumnName', 
			CAST(p.Value AS varchar(max)) AS 'Description' 
	FROM	sysobjects o 
	INNER	JOIN sys.extended_properties p	ON o.id = p.major_id
	INNER JOIN dbo.syscolumns c				ON p.minor_id = c.colorder
	WHERE o.id = c.id AND o. id in (SELECT o.id FROM sysobjects o INNER JOIN sys.extended_properties p ON o.id = p.major_id
		 							WHERE p.minor_id = 0 AND o.xtype='U' and o.name like 'rvlf%')
	and p.name ='ADT_Description'
END

GO
/****** Object:  StoredProcedure [dbo].[GetCamData]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[GetCamData]
(
  @intBoxID int,        
  @intImageID int
)
as 
BEGIN    
DECLARE @str varchar(max)
SELECT @str = COALESCE(@str + ',', '') + ImageData FROM rvlfCameraImages where boxid = @intBoxID and imageid =@intImageID order by CamMasterID
SELECT @str
END


GO
/****** Object:  StoredProcedure [dbo].[GetEmailsForAlarms]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[GetEmailsForAlarms](@uiMsgInID uniqueidentifier)
AS
BEGIN
SELECT h.MessageInID, h.DateTimeReceived, h.BoxId, m.BoxMsgInTypeDesc,s.CreateAlarm , v.* ,
		(CASE WHEN v.Notify = 1 THEN 'Notify' WHEN v.Warning = 1 THEN 'Warning'
		ELSE 'Critical' END) as Subjectsufix, i.MessageTemplate, h.*,(CASE WHEN m.BoxMsgInTypeDesc<>'Sensor' 
		THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN SUBSTRING (CustomProp,
		CHARINDEX(':',CustomProp,1)+1,CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) 
		ELSE '' END) as Duration 
	FROM rvlfMsgInHst h 
		INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId
		INNER JOIN rvlfBoxMsgSeverity b ON (h.BoxId = b.BoxId AND h.BoxMsgInTypeId = b.BoxMsgInTypeId)
		INNER JOIN rvlfSeverity s ON b.AlarmLevelID = s.AlarmLevelId
		INNER JOIN rvlfVehicleAssignment a ON h.BoxId = a.BoxId 
		INNER JOIN rvlfVehicle v ON a.VehicleId = v.VehicleId 
		INNER JOIN rvlfmsgInTemplates i On h.BoxMsgInTypeId = i.BoxMsgInTypeId
		WHERE s.CreateAlarm=1 AND h.MessageInID = @uiMsgInID AND
		(v.Notify = 1 OR v.Warning = 1 Or v.Critical =1)		
		END


GO
/****** Object:  StoredProcedure [dbo].[MQTT_SP_SaveMessages]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[MQTT_SP_SaveMessages]
	@ClientID varchar(30),
	@Topic nvarchar(100),
	@Message nvarchar(max)
AS
BEGIN
	SET NOCOUNT ON;	
	Insert into MQTT_Messages(ClientID,topic,message) values(@ClientID,@Topic,@Message)
END

GO
/****** Object:  StoredProcedure [dbo].[prcSendMSMQMessage]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[prcSendMSMQMessage]
   @msmqPath varchar(255),
   @messageLabel varchar(255),
   @messageBody varchar(1000)
 
AS
 
DECLARE @msmqQueue INT
DECLARE @result INT
 
-- Create the SQLMSMQ Object.
EXECUTE @result = sp_OACreate 'SqlMsmq', @msmqQueue OUT, 1
IF @result <> 0 GOTO ErrorHandler
 
-- Send the message using the Send method
EXECUTE @result = sp_OAMethod @msmqQueue, 'SendMessage', NULL, @msmqPath, @messageLabel, @messageBody
IF @result <> 0 GOTO ErrorHandler
 
GOTO DestroyObjects
 
ErrorHandler:
 
DECLARE @source varchar(53)
DECLARE @description VARCHAR(200)
EXECUTE sp_OAGetErrorInfo @msmqQueue, @source OUT, @description OUT, NULL, NULL
RAISERROR(@description, 16, 1)
 
GOTO DestroyObjects
 
DestroyObjects:
-- Destroy the SQLMSMQ object.
EXECUTE @result = sp_OADestroy @msmqQueue
 
RETURN


GO
/****** Object:  StoredProcedure [dbo].[rvfl_sp_GetRoutesLandmarks]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvfl_sp_GetRoutesLandmarks] --null,null,6      
@routeId Varchar(max)=null,      
@UserId bigint=null,      
@OrganizationId Bigint      
as      
--\**********************************************      
-- rvfl_sp_GetRoutesLandmarks null,null,6      
-- get lanmarks based on route details      
-- 21-Dec-2013      
-- Gopal.R      
--**********************************************      
begin      
Select LM.LandmarkID,RM.RouteName+' - '+ LM.LandmarkName + '|' AS LandmarkName,LM.Latitude,LM.Longitude,  
LM.LandmarkCategoryID,RD.RouteID,RM.GRouteID from rvlfLandmark LM   
inner join rvlfRouteDetails RD on LM.LandmarkID=RD.LndID      
inner join rvlfRouteMaster RM on RD.RouteID=RM.RouteID      
Where (@routeId is null or @routeId='' or RD.RouteID in(select * from  dbo.rvlf_fn_ConvertArrayToTable(@routeId,','))) and LM.OrganizationId=@OrganizationId       
end 





GO
/****** Object:  StoredProcedure [dbo].[rvlf_DeviceAlarm]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- rvlf_DeviceAlarm @bigQueryingUser=N'10607',@intBoxID=N'477315716271',@OrganizationId=N'86',@dtStartDate=N'9-Jun-2021 12:00:00 AM',@dtEndDate=N'9-Jul-2021 1:13:44 PM',@VehicleId=N'11055'
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_DeviceAlarm]
	-- Add the parameters for the stored procedure here
	@intBoxID Varchar(Max) = null,
	@VehicleId Varchar(Max) = NULL,
	@dtStartDate datetime = NULL,
	@dtEndDate datetime = NULL,
	@LastHours int = NULL,
	@OrganizationId bigint=NULL,
	@bigQueryingUser bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0, @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit
	
	DECLARE @Lang varchar(50), @LangSetting varchar(20)

	SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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

	--if(@LastHours <> 0)
	--	Begin
	--		SET @dtEndDate=@dtStartDate
	--		SET @dtStartDate= DATEADD(HOUR,(-1 * @LastHours) ,@dtStartDate)
	--	End

	SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))
	SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))

	Select A.AlarmId,DateTimeCreated=CONVERT(varchar(max),dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateTimeCreated),21),a.BoxId,A.StreetAddress,PM.ParamDescription as AlarmDesc,A.AlarmLevelId,st.AlarmLevelName,MD.VehicleId, MD.EquipmentName,GM.GatewayId,VT.VehicleTypeId,VT.VehicleTypeName from rvlfAlarm A 
	inner join rvlfParamMst PM on PM.ParamName=A.Description
	inner join rvlfSeverity St on st.AlarmLevelId=A.AlarmLevelId
	inner join rvlfVehicleAssignment VA on A.BoxId=VA.BoxId 
	inner join rvlfVehicle V on VA.VehicleId=V.VehicleId 
	inner join rvlfMAKDevices MD on MD.VehicleId=V.VehicleId
	inner join rvlfGatewayMaster GM on GM.GatewayMasterId=MD.CustomerId
	inner join rvlfVehicleType VT on V.VehicleTypeId=VT.VehicleTypeId 
	where 
	(@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR a.BoxId = @intBoxID)
	and (@VehicleId IS NULL OR @VehicleId='' OR @VehicleId='0' OR v.VehicleId = @VehicleId)
    AND (a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
    AND v.OrganizationId = @OrganizationId ORDER BY DateTimeCreated DESC

END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_fn_GetSensorMaskInformation_test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_fn_GetSensorMaskInformation_test]
(
	@vcSnsMask varchar(8)
)
-- RETURNS varchar(800)
AS
BEGIN
	DECLARE @vcSensorMask varchar(800)
	
	IF @vcSnsMask IS NOT NULL OR 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 class=''sensordetails''>'
		SELECT @intIterator = MIN(SensorId ) FROM rvlfSensor
		WHILE @intIterator IS NOT NULL
		BEGIN
		print Substring(@vcSnsMask,@intIndex,1)
			SELECT @vcSensorName=SensorName , @vcActionOn =ActionOn , @vcActionOff = ActionOff FROM rvlfSensor
			WHERE SensorId = @intIterator
		print @vcSensorName
		print @vcActionon
		print @vcActionoff
			SET @vcSensorMask = @vcSensorMask + '<tr><td>'+ @vcSensorName +'</td><td>:</td><td>' 
				+ CASE WHEN SUBSTRING(@vcSnsMask,@intIndex,1) = 1 THEN @vcActionOn ELSE @vcActionOff END + '</td></tr>'
			SELECT @intIterator = MIN(SensorId ) FROM rvlfSensor WHERE SensorId > @intIterator
			SET @intIndex = @intIndex-1
			print @vcSensorMask
			print @intIndex
		END
		--SET @vcSensorMask = '<table class=''sensordetails''><tr><td>Door </td><td>:</td><td> ' + CASE WHEN SUBSTRING(@vcSnsMask,8,1) = 1 THEN 'Open' ELSE 'Closed' END + '</td></tr>'--Char(13)
		--SET @vcSensorMask = @vcSensorMask + '<tr><td>Trunk </td><td>:</td><td> ' + CASE WHEN SUBSTRING(@vcSnsMask,7,1) = 1 THEN 'Open' ELSE 'Closed' END + '</td></tr>'--Char(13)
		--SET @vcSensorMask = @vcSensorMask + '<tr><td>Ignition </td><td>:</td><td> ' + CASE WHEN SUBSTRING(@vcSnsMask,6,1) = 1 THEN 'On' ELSE 'Off' END + '</td></tr>'--Char(13)
		--SET @vcSensorMask = @vcSensorMask + '<tr><td>Main Battery </td><td>:</td><td> ' + CASE WHEN SUBSTRING(@vcSnsMask,5,1) = 1 THEN 'Low' ELSE 'Ok' END +'</td></tr>'--Char(13)
		--SET @vcSensorMask = @vcSensorMask + '<tr><td>Backup Battery </td><td>:</td><td> ' + CASE WHEN SUBSTRING(@vcSnsMask,4,1) = 1 THEN 'Low' ELSE 'Ok' END + '</td></tr>'--Char(13)
		--SET @vcSensorMask = @vcSensorMask + '<tr><td>Driver Panic Button </td><td>:</td><td> ' + CASE WHEN SUBSTRING(@vcSnsMask,3,1) = 1 THEN 'Open' ELSE 'Closed' END + '</td></tr>'--Char(13)
		--SET @vcSensorMask = @vcSensorMask + '<tr><td>User defined Input 2 </td><td>:</td><td> ' + CASE WHEN SUBSTRING(@vcSnsMask,2,1) = 1 THEN 'Open' ELSE 'Closed' END + '</td></tr>'--Char(13)
		SET @vcSensorMask = @vcSensorMask + '</table>'--Char(13)
	END
	-- Return the result of the function
	print @vcSensorMask

END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_GetCompactorType]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_GetCompactorType](
@VehicleId BIGINT = NULL,
@OrganizationId BIGINT = NULL,
@UserId  BIGINT = NULL
)
AS 
BEGIN
SELECT v.VehicleId,VehicleDescription,Isnull(MD.VFantype,'0') AS Compactor, v.VehicleTypeId, EConsumptionType, ISNULL(MD.isAddParams,'0') AS AddParam FROM rvlfMAKDevices MD 
     INNER JOIN rvlfVehicleAssignment va ON MD.BoxId = va.BoxId
     INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId WHERE v.VehicleId = @VehicleId and MD.IsDelete =0
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_GetDeviceSeverity]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- EXEC rvlf_GetDeviceSeverity @DeviceID=11055
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_GetDeviceSeverity] 
	-- Add the parameters for the stored procedure here
	@DeviceID bigint = null,
	@BoxID nvarchar(100)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @Currenttype int=0

	select @Currenttype=B.DeviceStatus from rvlfBoxId B inner join rvlfVehicleAssignment VA on B.BoxId=VA.BoxId where (@deviceID IS NULL OR @deviceID='0' OR VA.VehicleId=@deviceID) AND (@BoxID IS NULL OR @BoxID='' OR b.BoxId=@BoxID)

	select AlarmLevelId,AlarmLevelName,'1' as ActiveStatus from rvlfSeverity where AlarmLevelId=isnull(@Currenttype,0)
	UNION ALL
	select AlarmLevelId,AlarmLevelName,'0' as ActiveStatus from rvlfSeverity where AlarmLevelId<>isnull(@Currenttype,0)
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_GetNotificationsList]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Procedure [dbo].[rvlf_GetNotificationsList]  
AS  
/******************************************************************************/  
-- Name  : rvlf_GetNotificationsList  
-- Description : To get the list for which the notification has to be sent  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 06-Jun-2009 MJJC Created Intial Version   
--    : 29-Jul-2009 MJJC Changed to have new logic  
/******************************************************************************/  
BEGIN  
SET NOCOUNT ON   
/**********************************************************************************/  
/**************************** Vehicle Level Notification ****************************/  
/**********************************************************************************/  
 /**************************** Based on Box Message Severity ****************************/  
  SELECT h.MessageInID,  
   /**************** Map to user preferences *******************/  
     ISNULL(n.Email,0) as CanSendEmail, ISNULL(n.SMS,0) as CanSendSMS, u.UserName, u.Email as Email, u.MobileNo,  
   /**************** Map to user preferences *******************/  
     
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(4, v.VehicleId, 1,0,0),'') as Email,  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(4, v.VehicleId, 0,0,0),'') as SMSUserNameList,  
    
   CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
    '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
    cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   WHEN h.ValidGps = 0 THEN   
    h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
    +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   ELSE h.StreetAddress END AS StreetAddress,  
     
   /**************** Map to user preferences *******************/    
   CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
   CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
     
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
     
   /**************** Map to user preferences *******************/  
     
   h.BoxId, m.BoxMsgInTypeDesc,s.CreateAlarm ,   
   v.VehicleDescription, v.VehicleId, v.Color,v.LicensePlate,   
   s.AlarmLevelName as Subjectsufix, i.MessageTemplate, (CASE WHEN m.BoxMsgInTypeDesc<>'Sensor'   
   THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN   
   SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,  
   CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END) as Duration,   
   CASE WHEN h.BoxMsgInTypeId = 4 OR h.BoxMsgInTypeId=28 THEN m.BoxMsgInTypeDesc ELSE  
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails  
   FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfBoxMsgSeverity ms ON h.BoxId = ms.BoxId and ms.BoxMsgInTypeId = h.BoxMsgInTypeId  
   INNER JOIN rvlfSeverity s ON ms.AlarmLevelID = s.AlarmLevelId   
     
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
     
   INNER JOIN rvlfmsgInTemplates i On i.BoxMsgInTypeId =  
   (CASE WHEN EXISTS (SELECT BoxMsgInTypeID FROM rvlfMsgInTemplates   
  WHERE BoxMsgInTypeID = h.BoxMsgInTypeId ) THEN  
   h.BoxMsgInTypeId  ELSE  0 END)  
    WHERE h.IsNotificationSent=0 and h.StreetAddress IS NOT NULL and s.CanSendNotification = 1 and h.BoxMsgInTypeId not in (5,6,2,3)  
   AND  ( case when  
   (case when v.Notify='true' then 'Notify' else '' end +      
   case when v.Warning='true' then 'Warning' else '' end +   
   case when v.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
   (case  when v.Notify='true' then (case when (v.Warning='true' or v.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +      
   case when v.Warning='true' then (case when v.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +   
   case when v.Critical='true' then 'Critical' else '' end)  
   end LIKE '%'+s.AlarmLevelName +'%') AND s.CanSendNotification = 1  
   AND LEN(u.Email) > 0  
  
 /**************************** Based on Default Severity ****************************/     
     SELECT h.MessageInID,   
    
   /**************** Map to user preferences *******************/  
     ISNULL(n.Email,0) as CanSendEmail, ISNULL(n.SMS,0) as CanSendSMS, u.UserName, u.Email as Email, u.MobileNo,  
   /**************** Map to user preferences *******************/  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(4, v.VehicleId, 1,0,0),'') as Email,  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(4, v.VehicleId, 0,0,0),'') as SMSUserNameList,  
    
   CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
    '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
    cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   WHEN h.ValidGps = 0 THEN   
    h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
    +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   ELSE h.StreetAddress END AS StreetAddress,  
   /**************** Map to user preferences *******************/    
   CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
   CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
     
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
     
   /**************** Map to user preferences *******************/  
   --CAST(h.Speed as varchar(10)) + ' KMPH' + '  ' + CAST((h.Speed*0.62) as varchar(10)) +' MPH' as Speed,  
     
   --CASE WHEN v.TimeZone IS Not NULL THEN   
   -- DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))  
   --ELSE h.OriginDateTime END OriginDateTime, h.DateTimeReceived,   
   h.BoxId, m.BoxMsgInTypeDesc,s.CreateAlarm ,   
   v.VehicleDescription, v.VehicleId, v.Color,v.LicensePlate,   
   s.AlarmLevelName as Subjectsufix, i.MessageTemplate, h.*,(CASE WHEN m.BoxMsgInTypeDesc<>'Sensor'   
   THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN   
   SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,  
   CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END) as Duration,   
   CASE WHEN h.BoxMsgInTypeId = 4 OR h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc ELSE  
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails  
   FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfBoxProtocolMsgInType ms ON h.BoxMsgInTypeId = ms.BoxMsgInTypeId  
   INNER JOIN rvlfSeverity s ON ms.DefaultAlarmLevel = s.AlarmLevelId   
     
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
     
   INNER JOIN rvlfmsgInTemplates i On i.BoxMsgInTypeId =  
   (CASE WHEN EXISTS (SELECT BoxMsgInTypeID FROM rvlfMsgInTemplates   
  WHERE BoxMsgInTypeID = h.BoxMsgInTypeId ) THEN  
   h.BoxMsgInTypeId  ELSE  0 END)  
    WHERE h.IsNotificationSent=0  and h.StreetAddress IS NOT NULL  and h.StreetAddress IS NOT NULL and s.CanSendNotification = 1 and h.BoxMsgInTypeId not in (5,6,2,3)  
   AND  ( case when  
   (case when v.Notify='true' then 'Notify' else '' end +      
   case when v.Warning='true' then 'Warning' else '' end +   
   case when v.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
   (case  when v.Notify='true' then (case when (v.Warning='true' or v.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +      
   case when v.Warning='true' then (case when v.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +   
   case when v.Critical='true' then 'Critical' else '' end)  
   end LIKE '%'+s.AlarmLevelName +'%') AND h.BoxMsgInTypeId NOT IN   
    (SELECT BoxMsgInTypeId  FROM rvlfBoxMsgSeverity bms WHERE bms.BoxId = h.BoxId ) AND s.CanSendNotification = 1  
      
    /**************************** Based on Sensor Severity ****************************/  
     SELECT h.MessageInID,   
      /**************** Map to user preferences *******************/  
     ISNULL(n.Email,0) as CanSendEmail, ISNULL(n.SMS,0) as CanSendSMS, u.UserName, u.Email as Email, u.MobileNo,  
   /**************** Map to user preferences *******************/  
    
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(4, v.VehicleId, 1,0,0),'') as Email,  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(4, v.VehicleId, 0,0,0),'') as SMSUserNameList,  
     
   CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
    '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
    cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   WHEN h.ValidGps = 0 THEN   
    h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
    +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   ELSE h.StreetAddress END AS StreetAddress,  
     
   --CAST(h.Speed as varchar(10)) + ' KMPH' + '  ' + CAST((h.Speed*0.62) as varchar(10)) +' MPH' as Speed,  
     
   --CASE WHEN v.TimeZone IS Not NULL THEN   
   -- DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))  
   --ELSE h.OriginDateTime END OriginDateTime, h.DateTimeReceived,  
   /**************** Map to user preferences *******************/    
   CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
   CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
     
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
     
   /**************** Map to user preferences *******************/  
    h.BoxId, m.BoxMsgInTypeDesc,s.CreateAlarm ,   
   v.VehicleDescription, v.VehicleId, v.Color,v.LicensePlate,   
   s.AlarmLevelName as Subjectsufix, i.MessageTemplate, h.*,(CASE WHEN m.BoxMsgInTypeDesc<>'Sensor'   
   THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN SUBSTRING (CustomProp,   
   CHARINDEX(':',CustomProp,1)+1,  
   CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END) as Duration,  
   SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,   
   CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1) As SensorStatus,  
   rs.SensorName,  
   CASE WHEN h.BoxMsgInTypeId = 4 OR h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc ELSE  
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails  
  FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfSensor rs ON CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,1) As tinyint) = rs.SensorId  
   INNER JOIN rvlfBoxSensorsCfg bs ON bs.SensorId = rs.SensorId AND h.BoxId = bs.BoxId  
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfSeverity s ON s.AlarmLevelId =  
    (CASE WHEN SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,  
     CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1)   
     IN ('OPEN','ON','NORMAL','OK')  
     THEN bs.AlarmLevelOn ELSE bs.AlarmLevelOff END)  
       
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
     
   INNER JOIN rvlfmsgInTemplates i On i.BoxMsgInTypeId =  
   (CASE WHEN EXISTS (SELECT BoxMsgInTypeID FROM rvlfMsgInTemplates   
    WHERE BoxMsgInTypeID = h.BoxMsgInTypeId ) THEN  
   h.BoxMsgInTypeId  ELSE  0 END)  
    WHERE h.BoxMsgInTypeId = 11 /*in (2,3)*/ AND h.IsNotificationSent = 0 and h.StreetAddress IS NOT NULL  
   AND (case when  
   (case when v.Notify='true' then 'Notify' else '' end +      
   case when v.Warning='true' then 'Warning' else '' end +   
   case when v.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
   (case  when v.Notify='true' then (case when (v.Warning='true' or v.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +      
   case when v.Warning='true' then (case when v.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +   
   case when v.Critical='true' then 'Critical' else '' end)  
   end LIKE '%'+s.AlarmLevelName +'%') AND s.CanSendNotification = 1  
/**********************************************************************************/  
  
/**********************************************************************************/  
/**************************** Fleet Level Notification ****************************/  
/**********************************************************************************/  
 /**************************** Based on Box Message Severity ****************************/  
  SELECT h.MessageInID, f.fleetName,  
    
   /**************** Map to user preferences *******************/  
     ISNULL(n.Email,0) as CanSendEmail, ISNULL(n.SMS,0) as CanSendSMS, u.UserName, u.Email as Email, u.MobileNo,  
   /**************** Map to user preferences *******************/  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(3, f.FleetId, 1,0,0),'') as Email,  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(3, f.FleetId, 0,0,0),'') as SMSUserNameList,  
    
   CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
    '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
    cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   WHEN h.ValidGps = 0 THEN   
    h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
    +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   ELSE h.StreetAddress END AS StreetAddress,  
   /**************** Map to user preferences *******************/    
   CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
   CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
     
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
     
   /**************** Map to user preferences *******************/  
     
   --CAST(h.Speed as varchar(10)) + ' KMPH' + '  ' + CAST((h.Speed*0.62) as varchar(10)) +' MPH' as Speed,  
   --CASE WHEN f.TimeZone IS Not NULL THEN   
   -- DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))  
   --ELSE h.OriginDateTime END OriginDateTime, h.DateTimeReceived,  
    h.BoxId, m.BoxMsgInTypeDesc,s.CreateAlarm ,   
    v.VehicleDescription, v.VehicleId, v.Color,v.LicensePlate,   
    i.MessageTemplate, h.*,(CASE WHEN m.BoxMsgInTypeDesc<>'Sensor'   
   THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN SUBSTRING   
   (CustomProp, CHARINDEX(':',CustomProp,1)+1, CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END)   
   ELSE '' END) as Duration , s.AlarmLevelName as Subjectsufix,   
   CASE WHEN h.BoxMsgInTypeId = 4 OR h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc ELSE  
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails  
  from rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
   INNER JOIN rvlfFleet f On fv.FleetId = f.FleetId  
   INNER JOIN rvlfBoxMsgSeverity ms ON h.BoxId = ms.BoxId and ms.BoxMsgInTypeId = h.BoxMsgInTypeId  
   INNER JOIN rvlfSeverity s ON ms.AlarmLevelID = s.AlarmLevelId   
     
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
     
   INNER JOIN rvlfmsgInTemplates i On i.BoxMsgInTypeId =  
  (CASE WHEN EXISTS (SELECT BoxMsgInTypeID FROM rvlfMsgInTemplates   
   WHERE BoxMsgInTypeID = h.BoxMsgInTypeId ) THEN  
  h.BoxMsgInTypeId  ELSE  0 END)  
 WHERE h.IsNotificationSent=0  and h.StreetAddress IS NOT NULL  and h.StreetAddress IS NOT NULL and s.CanSendNotification = 1 and h.BoxMsgInTypeId not in (5,6,2,3)  
 AND  ( case when  
    (case when f.Notify='true' then 'Notify' else '' end +      
    case when f.Warning='true' then 'Warning' else '' end +   
    case when f.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
    (case  when f.Notify='true' then (case when (f.Warning='true' or f.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +      
    case when f.Warning='true' then (case when f.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +   
    case when f.Critical='true' then 'Critical' else '' end)  
    end LIKE '%'+s.AlarmLevelName +'%') AND s.CanSendNotification = 1  
       
     /**************************** Based on Default Severity ****************************/     
      SELECT h.MessageInID, f.fleetName,  
    
   /**************** Map to user preferences *******************/  
    ISNULL(n.Email,0) as CanSendEmail, ISNULL(n.SMS,0) as CanSendSMS, u.UserName, u.Email as Email, u.MobileNo,  
   /**************** Map to user preferences *******************/  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(3, f.FleetId, 1,0,0),'') as Email,  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(3, f.FleetId, 0,0,0),'') as SMSUserNameList,  
    
   CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
    '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
    cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   WHEN h.ValidGps = 0 THEN   
    h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
    +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   ELSE h.StreetAddress END AS StreetAddress,  
     
   --CAST(h.Speed as varchar(10)) + ' KMPH' + '  ' + CAST((h.Speed*0.62) as varchar(10)) +' MPH' as Speed,  
   --CASE WHEN f.TimeZone IS Not NULL THEN   
   -- DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))  
   --ELSE h.OriginDateTime END OriginDateTime, h.DateTimeReceived,   
     
   /**************** Map to user preferences *******************/    
   CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
   CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
     
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
     
   /**************** Map to user preferences *******************/  
   v.VehicleDescription, v.VehicleId, v.Color,v.LicensePlate,   
   h.BoxId, m.BoxMsgInTypeDesc,s.CreateAlarm ,   
    i.MessageTemplate, h.*,(CASE WHEN m.BoxMsgInTypeDesc<>'Sensor'   
   THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN SUBSTRING   
   (CustomProp, CHARINDEX(':',CustomProp,1)+1, CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END)   
   ELSE '' END) as Duration , s.AlarmLevelName as Subjectsufix,   
   CASE WHEN h.BoxMsgInTypeId = 4 OR h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc ELSE  
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails  
  from rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
   INNER JOIN rvlfFleet f On fv.FleetId = f.FleetId  
   INNER JOIN rvlfBoxProtocolMsgInType ms ON h.BoxMsgInTypeId = ms.BoxMsgInTypeId  
   INNER JOIN rvlfSeverity s ON ms.DefaultAlarmLevel = s.AlarmLevelId   
     
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
     
   INNER JOIN rvlfmsgInTemplates i On i.BoxMsgInTypeId =  
   (CASE WHEN EXISTS (SELECT BoxMsgInTypeID FROM rvlfMsgInTemplates   
    WHERE BoxMsgInTypeID = h.BoxMsgInTypeId ) THEN  
   h.BoxMsgInTypeId  ELSE  0 END)  
  WHERE h.IsNotificationSent=0  and h.StreetAddress IS NOT NULL and s.CanSendNotification = 1 and h.BoxMsgInTypeId not in (5,6,2,3)  
  AND  ( case when  
  (case when f.Notify='true' then 'Notify' else '' end +      
  case when f.Warning='true' then 'Warning' else '' end +   
  case when f.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
  (case  when f.Notify='true' then (case when (f.Warning='true' or f.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +      
  case when f.Warning='true' then (case when f.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +   
  case when f.Critical='true' then 'Critical' else '' end)  
  end LIKE '%'+s.AlarmLevelName +'%') AND h.BoxMsgInTypeId NOT IN   
     (SELECT BoxMsgInTypeId  FROM rvlfBoxMsgSeverity bms WHERE bms.BoxId = h.BoxId ) AND s.CanSendNotification = 1  
      
    /**************************** Based on Sensor Severity ****************************/  
     SELECT   
      h.MessageInID, f.fleetName,  
   /**************** Map to user preferences *******************/  
     ISNULL(n.Email,0) as CanSendEmail, ISNULL(n.SMS,0) as CanSendSMS, u.UserName, u.Email as Email, u.MobileNo,  
   /**************** Map to user preferences *******************/  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(3, f.FleetId, 1,0,0),'') as Email,  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(3, f.FleetId, 0,0,0),'') as SMSUserNameList,  
    
   CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
    '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
    cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   WHEN h.ValidGps = 0 THEN   
    h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
    +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   ELSE h.StreetAddress END AS StreetAddress,  
     
   --CAST(h.Speed as varchar(10)) + ' KMPH' + '  ' + CAST((h.Speed*0.62) as varchar(10)) +' miles/hr' as Speed,  
   /**************** Map to user preferences *******************/    
   CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
   CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
     
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
     
   /**************** Map to user preferences *******************/  
   v.VehicleDescription, v.VehicleId, v.Color,v.LicensePlate,   
   --CASE WHEN f.TimeZone IS Not NULL THEN   
   -- DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))  
   --ELSE h.OriginDateTime END OriginDateTime, h.DateTimeReceived,  
    h.BoxId, m.BoxMsgInTypeDesc,s.CreateAlarm ,   
    i.MessageTemplate, h.*,(CASE WHEN m.BoxMsgInTypeDesc<>'Sensor'   
   THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN SUBSTRING   
   (CustomProp, CHARINDEX(':',CustomProp,1)+1, CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END)   
   ELSE '' END) as Duration , s.AlarmLevelName as Subjectsufix,   
   CASE WHEN h.BoxMsgInTypeId = 4  OR h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc ELSE  
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails,  
   SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,   
   CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1) As SensorStatus,  
   rs.SensorName  
  FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfSensor rs ON CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,1) As tinyint) = rs.SensorId  
   INNER JOIN rvlfBoxSensorsCfg bs ON bs.SensorId = rs.SensorId AND h.BoxId = bs.BoxId  
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
   INNER JOIN rvlfFleet f On fv.FleetId = f.FleetId  
   INNER JOIN rvlfSeverity s ON s.AlarmLevelId =  
    (CASE WHEN SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,  
     CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1)   
     IN ('OPEN','ON','NORMAL','OK')  
     THEN bs.AlarmLevelOn ELSE bs.AlarmLevelOff END)  
     
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
     
   INNER JOIN rvlfmsgInTemplates i On i.BoxMsgInTypeId =  
   (CASE WHEN EXISTS (SELECT BoxMsgInTypeID FROM rvlfMsgInTemplates   
  WHERE BoxMsgInTypeID = h.BoxMsgInTypeId ) THEN  
   h.BoxMsgInTypeId  ELSE  0 END)  
    WHERE h.BoxMsgInTypeId = 11 /*in (2,3) */ AND h.IsNotificationSent = 0 and h.StreetAddress is not null  
   AND (case when  
   (case when f.Notify='true' then 'Notify' else '' end +      
   case when f.Warning='true' then 'Warning' else '' end +   
   case when f.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
   (case  when f.Notify='true' then (case when (f.Warning='true' or f.Critical='true')  
    then 'Notify;' else 'Notify' end ) else '' end +      
   case when f.Warning='true' then (case when f.Critical='true' then 'Warning;'   
   else 'Warning' end ) else '' end +   
   case when f.Critical='true' then 'Critical' else '' end)  
   end LIKE '%'+s.AlarmLevelName +'%') AND s.CanSendNotification = 1  
    
 /**************************** Geozone Level Notification ****************************/  
/**********************************************************************************/  
/**************************** Geozone Level Notification **************************/  
/**********************************************************************************/  
 SELECT h.MessageInID,g.geozonename,  
   /**************** Map to user preferences *******************/  
   ISNULL(n.Email,0) as CanSendEmail, ISNULL(n.SMS,0) as CanSendSMS, u.UserName, u.Email as Email, u.MobileNo,  
   /**************** Map to user preferences *******************/  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(1, g.GeozoneNo, 1,0,0),'') as Email,  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(1, g.GeozoneNo, 0,0,0),'') as SMSUserNameList,  
     
   CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
    '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
    cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   WHEN h.ValidGps = 0 THEN   
    h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
    +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   ELSE h.StreetAddress END AS StreetAddress,  
     
  -- CAST(h.Speed as varchar(10)) + ' KMPH' + '  ' + CAST((h.Speed*0.62) as varchar(10)) +' miles/hr' as Speed,  
     
  --CASE WHEN g.TimeZone IS Not NULL THEN   
  -- DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))  
  --ELSE h.OriginDateTime END OriginDateTime, h.DateTimeReceived,  
  /**************** Map to user preferences *******************/    
   CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
   CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
     
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
     
   /**************** Map to user preferences *******************/  
   h.BoxId, m.BoxMsgInTypeDesc,s.CreateAlarm ,   
  v.VehicleDescription, v.VehicleId, v.Color,v.LicensePlate,   
  s.AlarmLevelName as Subjectsufix, i.MessageTemplate, h.*,(CASE WHEN m.BoxMsgInTypeDesc<>'Sensor'   
  THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN SUBSTRING   
  (CustomProp, CHARINDEX(':',CustomProp,1)+1,  
  CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END) as Duration,  
  dbo.rvlf_fn_GetAlarmDetails(CAST( SUBSTRING(h.CustomProp,  
    CHARINDEX('=',h.CustomProp,1)+1,(CHARINDEX(';',h.CustomProp,1)  
    - CHARINDEX('=',h.CustomProp,1))-1) as bigint), h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime )  
     as MessageDetails  
 FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment a ON h.BoxId = a.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
  INNER JOIN rvlfVehicle v ON a.VehicleId = v.VehicleId   
  INNER JOIN rvlfmsgInTemplates i On i.BoxMsgInTypeId =  
  (CASE WHEN EXISTS (SELECT BoxMsgInTypeID FROM rvlfMsgInTemplates   
   WHERE BoxMsgInTypeID = h.BoxMsgInTypeId ) THEN  
  h.BoxMsgInTypeId  ELSE  0 END)  
  INNER JOIN rvlfOrganizationGeozone g ON g.OrganizationId = v.OrganizationId  
    
  /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON g.GeozoneNo = n.TypeID and n.NotificationType=1  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
  /**************** Map to user preferences *******************/  
    
  INNER JOIN rvlfSeverity s ON g.SeverityId = s.AlarmLevelId  
  WHERE s.CanSendNotification=1 AND h.BoxMsgInTypeId in (5,6) AND--h.StreetAddress IS NOT NULL  AND  
  s.CanSendNotification=1 AND h.IsNotificationSent = 0 and h.StreetAddress IS NOT NULL  
  AND g.GeozoneId = (CAST( SUBSTRING(h.CustomProp,  
    CHARINDEX('=',h.CustomProp,1)+1,(CHARINDEX(';',h.CustomProp,1)  
    - CHARINDEX('=',h.CustomProp,1))-1) as bigint)) AND s.CanSendNotification = 1  
  
/**********************************************************************************/      
/**************************** Landmark Level Notification *************************/  
/**********************************************************************************/  
 SELECT h.MessageInID,   
    
   /**************** Map to user preferences *******************/  
     ISNULL(n.Email,0) as CanSendEmail, ISNULL(n.SMS,0) as CanSendSMS, u.UserName, u.Email as Email, u.MobileNo,  
   /**************** Map to user preferences *******************/  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(2, fm.LandmarkID, 1,0,0),'') as Email,  
   --ISNULL(dbo.rvlf_fn_GetNotificationsList(2, fm.LandmarkID, 0,0,0),'') as SMSUserNameList,  
    
   CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
    '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
    cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   WHEN h.ValidGps = 0 THEN   
    h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
    +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
   ELSE h.StreetAddress END AS StreetAddress,  
     
   --CAST(h.Speed as varchar(10)) + ' KMPH' + '  ' + CAST((h.Speed*0.62) as varchar(10)) +' miles/hr' as Speed,  
     
   --CASE WHEN fm.TimeZone IS Not NULL THEN   
   -- DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))  
   --ELSE h.OriginDateTime END OriginDateTime, h.DateTimeReceived,   
   /**************** Map to user preferences *******************/    
   CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
   CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
     
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
     
   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
     
   /**************** Map to user preferences *******************/  
   h.BoxId, m.BoxMsgInTypeDesc,   
   v.VehicleDescription, v.VehicleId, v.Color,v.LicensePlate,   
   CASE WHEN fm.Notify = 1 THEN 'Notify' WHEN fm.Warning=1 THEN 'Warning' ELSE 'Critical' END AS Subjectsufix,   
   i.MessageTemplate, h.*,(CASE WHEN m.BoxMsgInTypeDesc<>'Sensor'   
   THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN   
   SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,  
   CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END) as Duration,   
   (CASE WHEN SUBSTRING(h.SensorMask,6,1) = 1 THEN 'Trip Start' ELSE 'Trip End' END) + ' - ' + fm.LandmarkName  as MessageDetails  
   --(CASE WHEN h.BoxMsgInTypeId = 4 THEN m.BoxMsgInTypeDesc ELSE  
   -- dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInId, h.Origindatetime) END) + ' - ' + fm.LandmarkName  as MessageDetails  
   FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   INNER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON fm.LandmarkID = n.TypeID and n.NotificationType=2  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
    /************************************************************** Based on Rights************/   
   INNER join rvlfUserGroupSecurity US on m.OperationTypeID = US.OperationTypeId
   INNER JOIN rvlfUserGroupAssignment UA on US.UserGroupId = UA.UserGroupId and UA.UserId = n.UserID
   /**************** Map to user preferences *******************/  --and h.BoxMsgInTypeId not in (5,6,19,20,21,22,28,35,34,31)
   INNER JOIN rvlfmsgInTemplates i On i.BoxMsgInTypeId =  
   (CASE WHEN EXISTS (SELECT BoxMsgInTypeID FROM rvlfMsgInTemplates   
  WHERE BoxMsgInTypeID = h.BoxMsgInTypeId ) THEN  
   h.BoxMsgInTypeId  ELSE  0 END)  
   WHERE h.IsNotificationSent=0 and h.StreetAddress IS NOT NULL and (fm.Notify=1 OR fm.Warning=1 OR fm.Critical=1)  
  AND (h.MessageInID in (SELECT StartMessageInID FROM rvlfTripDetails) OR h.MessageInID in (SELECT EndMessageInID  FROM rvlfTripDetails) )  
  
SET NOCOUNT OFF  
END  
  
GO
/****** Object:  StoredProcedure [dbo].[rvlf_ModuleInfromation]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- EXEC rvlf_ModuleInfromation  @OrganizationId=86,@bigQueryingUser=10607
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_ModuleInfromation]
	-- Add the parameters for the stored procedure here
	@bigQueryingUser bigint=0,
	@OrganizationId bigint = null,
	@deviceID bigint =null,
	@BoxID nvarchar(100) =null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0, @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit            
	DECLARE @dtStartDate datetime
    
	SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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)
  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      
   
 SELECT V.VehicleId,v.VehicleDescription,v.VehicleTypeId,t.VehicleTypeName,b.LastStreetAddress,
 LastCommunicatedDateTime= DATEADD(HOUR,@HoursToBeAdded, DATEADD(MINUTE,@MinsToBeAdded,b.LastCommunicatedDateTime)),GT.GatewayId,St.AlarmLevelName As DeviceStatus,b.BoxId FROM rvlfVehicle v  
 Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
 INNER JOIN rvlfOrganization g ON v.OrganizationId = g.OrganizationId
 INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
 inner join rvlfBoxId b on b.BoxId=md.BoxId
 inner join rvlfGatewayMaster GT on GT.GatewayMasterId=MD.CustomerId
 left join rvlfSeverity ST on St.AlarmLevelId=b.DeviceStatus
 where v.OrganizationId=@OrganizationId and
 (@deviceID IS NULL OR @deviceID='0' OR V.VehicleId=@deviceID) AND
 (@BoxID IS NULL OR @BoxID='' OR b.BoxId=@BoxID)
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_Proc_UploadServicelogImage]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthkeyan
-- Create date: 08-Jan-2019
-- Description:	Update the Service call log image from the mobile app
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_Proc_UploadServicelogImage]
	-- Add the parameters for the stored procedure here
	@ServiceLogID bigint,
	@Image1 varchar(2000)=null,
	@Image2 varchar(2000)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if(@Image1 is null)
		begin
			update rvlfAdhocServices set photo1=@Image2 where AdhocServiceId=@ServiceLogID
		end
	else if(@Image2 is null)
		begin
			update rvlfAdhocServices set photo1=@Image1 where AdhocServiceId=@ServiceLogID
		end
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AcceptOrCloseAlarms]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_AcceptOrCloseAlarms]
	@vcAlarmIds varchar(200),
	@bitIsAccept bit = 1,
	@dtTransactionDateTime datetime,
	@bigUserId bigint = 0,
	@comments varchar(150)    
AS
/******************************************************************************/
--	Name		:	rvlf_sp_AcceptOrCloseAlarms
--	Description	:	To accept or close alarms based on the criteria passed.
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	15-Jul-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
		 
	BEGIN TRAN MessageOutTransaction
	BEGIN TRY
		IF @bitIsAccept = 1
		BEGIN
			UPDATE rvlfAlarm SET
				AcceptedBy = @bigUserId , 
				DateTimeAccepted = @dtTransactionDateTime,
				Comments=@comments    
			 WHERE AlarmId in ( SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcAlarmIds,','))
		END
		ELSE
		BEGIN
			UPDATE rvlfAlarm SET
				ClosedBy = @bigUserId , /*AcceptedBy = ISNULL(AcceptedBy,@bigUserId) ,
				DateTimeAccepted = ISNULL(DateTimeAccepted,@dtTransactionDateTime),*/
				DateTimeClosed = @dtTransactionDateTime,
				Comments=@comments    
			 WHERE AlarmId in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcAlarmIds,','))
		END
		---- To insert the information in the message in history table
		--UPDATE rvlfAlarm Set 
		COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during insert of the message sent : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AccidentGroup]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create proc [dbo].[rvlf_sp_AccidentGroup]  
@bigOrganizationId bigint  
as  
begin  
select AccidentReasonGroupID,AccidentReasonGroupName from rvlfAccidentReasonGroups where OrganizationId=@bigOrganizationId and Status=1  
end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_Alarmconfig]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_Alarmconfig]
(
	@MReason varchar(100)=NULL,
	@MCorrectiveAction varchar(max)=NULL,
	@paramID int=NULL,
	@ItemDetailsXML XML =NULL,
	@bigUserID bigint=null,
	@Status char='S'
)
as 
	begin
		SET NOCOUNT ON;
		DECLARE @ErrorMessage varchar(3000)
		DECLARE @docHandle int
		DECLARE @tblItemDetailsXML TABLE (RowIndex bigint,AlarmParamID int,AlarmParamName varchar(100),Reason varchar(1000),CorrectiveAction Varchar(max))
		EXEC sp_xml_preparedocument @docHandle OUTPUT, @ItemDetailsXML
		INSERT INTO @tblItemDetailsXML
		SELECT * FROM OPENXML(@docHandle, '/DocumentElement/ItemDetails')
		WITH
		(
			RowIndex bigint 'RowIndex',
			AlarmParamID int 'AlarmParamID'
			,AlarmParamName varchar(100) 'AlarmParamName'
			,Reason varchar(1000) 'Reason'
			,CorrectiveAction Varchar(max) 'CorrectiveAction'
		)
		IF(@Status='I')
			BEGIN
				DELETE FROM rvlfAlarmconfig where Paramid=@paramID
				INSERT INTO rvlfAlarmconfig (Paramid,AlarmParamID,AlarmParamName,Reason,CorrectiveAction,Modifiedby,Modifieddate)
				SELECT @paramID, AlarmParamID,AlarmParamName ,Reason ,CorrectiveAction,@bigUserID,getutcdate() from @tblItemDetailsXML
				UPDATE rvlfParamMst set MReason=@MReason,MCorrectiveAction=@MCorrectiveAction where ParamId=@paramID
			END
		Else if (@Status='E')
			Begin
				select * from rvlfParamMst where ParamId=@paramID
				select * from rvlfAlarmconfig where ParamId=@paramID
			End
		Else
			Begin
				select distinct t1.Paramid,ParamName,
				STUFF((SELECT ', ' + AlarmParamName FROM rvlfAlarmconfig t2 where t1.ParamId = t2.Paramid FOR XML PATH ('')), 1, 1, '') AS Alarmchklist
				from rvlfParamMst t1 where ParamDescription is not null order by ParamName
			End
	end
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AlarmMessageReceived]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Kalaivanan.E
-- Create date: 15-Dec-2017
-- Description:	Categorize the alarm and Insert rvlfAlarm & AlarmTransaction Tables
--				UpDate Alarm if it is closed
-- =============================================
CREATE PROCEDURE  [dbo].[rvlf_sp_AlarmMessageReceived]
@vcCustomProp varchar(max),
@tiBoxMsgInTypeId TINYINT,
@ControllerID int,
@DCSIM int,
@intBoxID varchar(10),
@dtOriginDateTime datetime,
@msgIDCurrentPacket uniqueidentifier,
@msgIDLastPacket uniqueidentifier
AS
BEGIN
SET NOCOUNT ON;
Declare @CmdID int  =null
Declare @dLatitude1 decimal(10,6) = 0
Declare @dLongitude1 decimal(10,6) = 0
Declare @tiValidGps1 smallint = 0
Declare @AlarmTransactionData table
(
	MessageInID uniqueidentifier,AlarmLevelId smallint,DateTimeCreated datetime,BoxId varchar(10),AlarmType tinyint,Lat decimal(10,6),Long decimal(10,6),[Description] varchar(250),
	StreetAddress varchar(250),DriverId bigint,ControllerID tinyint,AcceptedBy bigint,DateTimeAccepted datetime,AlarmRepeatFlag tinyint,DCSIM tinyint,AlarmID int
)

Declare @vcCustomProp1 varchar(max) = @vcCustomProp,@tiBoxMsgInTypeId1 TINYINT = @tiBoxMsgInTypeId,
@ControllerID1 int = @ControllerID,@DCSIM1 int = @DCSIM,@CmdID1 int = @CmdID,@intBoxID1 varchar(10) = @intBoxID,
@dtOriginDateTime1 datetime = @dtOriginDateTime,
@uiMsgInID uniqueidentifier = @msgIDCurrentPacket,@msgIDLastPacket1 uniqueidentifier = @msgIDLastPacket
Declare @Controller_Name varchar(50)
Select @Controller_Name=ControllerName From ADRCOntrollerMaster where MessageInID=@uiMsgInID

--Select top 1 @msgIDLastPacket1 = messageinid from rvlfMsgInHst h where boxid= @intBoxID1 and BoxMsgInTypeId in (@tiBoxMsgInTypeId1)  and 
--		(@ControllerID1 IS NULL or @ControllerID1 = '' OR h.ControllerID IN(@ControllerID1)) and (@CmdID1 IS NULL or @CmdID1 = '' OR h.CmdId IN(@CmdID1)) AND (@DCSIM1 is null or @DCSIM1='' or DCSIM=@DCSIM1) order by OriginDateTime desc

--Select * from rvlfAlarm where MessageInID IN(@msgIDLastPacket1)
		
		IF(@tiBoxMsgInTypeId1 = 24) -- ** Pricicon-R Critical Parameter Message
		BEGIN
			DECLARE @AVC_Status_Word1 VARCHAR(1500), @AVC_Status_Word2 VARCHAR(1500) ,@AVC_Alarm_Word VARCHAR(1500)
			SELECT @AVC_Status_Word1=REPLACE(REPLACE(FieldValue,'AVC_Status_Word1=',''),']','') FROM dbo.rvlf_fn_ConvertArrayToTable(@vcCustomProp1,';') WHERE FieldValue LIKE 'AVC_Status_Word1%'
			SELECT @AVC_Status_Word2=REPLACE(REPLACE(FieldValue,'AVC_Status_Word2=','') ,']','')FROM dbo.rvlf_fn_ConvertArrayToTable(@vcCustomProp1,';') WHERE FieldValue LIKE 'AVC_Status_Word2%'
			SELECT @AVC_Alarm_Word=REPLACE(REPLACE(FieldValue,'AVC_Alarm_Word=','')  ,']','') FROM dbo.rvlf_fn_ConvertArrayToTable(@vcCustomProp1,';') WHERE FieldValue LIKE 'AVC_Alarm_Word%'
			
			IF (LEN(@AVC_Status_Word1) <> 0 or LEN(@AVC_Status_Word2) <> 0 or LEN(@AVC_Alarm_Word) <> 0)
			BEGIN
				INSERT INTO @AlarmTransactionData(MessageInID,AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,DriverId,ControllerID,AcceptedBy,DateTimeAccepted,AlarmRepeatFlag,DCSIM,AlarmID)
					SELECT @uiMsgInID,A.AlarmLevelID, @dtOriginDateTime1,@intBoxID1, @tiBoxMsgInTypeId1,@dLatitude1,@dLongitude1,REPLACE(A.AlarmFaultDescription,':true',''),CASE WHEN @tiValidGps1 = 0 THEN NULL ELSE 'N/A' END,
							 NULL,@ControllerID1,NULL,NULL,
							 CASE WHEN A.AlarmFaultDescription IN (Select C.[Description] from rvlfAlarmTransaction C where C.MessageInID = @msgIDLastPacket1) THEN 0 ELSE 1 END,@DCSIM1,
							 CASE WHEN A.AlarmFaultDescription IN (Select D.[Description] from rvlfAlarmTransaction D where D.MessageInID = @msgIDLastPacket1) THEN 
							 (Select E.AlarmID from rvlfAlarmTransaction E where E.MessageInID IN(@msgIDLastPacket1) AND E.[Description] in (A.AlarmFaultDescription)) ELSE 0 END 
					  FROM 
						   (SELECT b.AlarmLevelID,REPLACE(FieldValue,']','') AS AlarmFaultDescription FROM dbo.rvlf_fn_ConvertArrayToTableWithIdentity(REPLACE(@AVC_Status_Word1+'|'+@AVC_Status_Word2+'|'+@AVC_Alarm_Word,'[',''),'|') a
								left join rvlfAlarmsSeverity b on a.FieldValue=b.AlarmParameter
							) A 
					  WHERE A.AlarmLevelId > 0   and len(a.AlarmFaultDescription)>1 
			END
		END

		IF(@tiBoxMsgInTypeId1 = 4) -- ** Pricicon-III Critical Parameter Message
		BEGIN
			Declare @Replace varchar(1000)='Trip_Status=,Trip_ACK=,Alarm_Status=,Alarm_ACK=,AlarmWord=,Trip_Condition:,Trip_Acknowledged_Status:,Alarm_Condition:,Alarm_Acknowledgment_status:,[,],:true'  
			DECLARE @TripSTS VARCHAR(1500),@TripACK VARCHAR(1500),@alarmSTS VARCHAR(1500),@alarmACK VARCHAR(1500)
			SELECT @TripSTS= FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(@vcCustomProp1,';') WHERE FieldValue LIKE 'Trip_Status%'                      
			SELECT @TripACK=FieldValue  FROM dbo.rvlf_fn_ConvertArrayToTable(@vcCustomProp1,';') WHERE FieldValue LIKE 'Trip_ACK%'          
			SELECT @alarmSTS=FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(@vcCustomProp1,';') WHERE FieldValue LIKE 'Alarm_Status%'             
			SELECT @alarmACK=FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(@vcCustomProp1,';') WHERE FieldValue LIKE 'Alarm_ACK%' 
			SELECT @TripSTS=replace(@TripSTS, FieldValue, ''),@TripACK=replace(@TripACK, FieldValue, ''),@alarmSTS=replace(@alarmSTS, FieldValue, ''),
							@alarmACK=replace(@alarmACK, FieldValue, '') FROM dbo.rvlf_fn_ConvertArrayToTableWithIdentity (@Replace,',') a

			IF (LEN(@TripSTS) <> 0 or LEN(@TripACK) <> 0 or LEN(@alarmSTS) <> 0 or LEN(@alarmACK) <> 0)          
			 BEGIN     
				INSERT INTO @AlarmTransactionData(MessageInID,AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,DriverId,ControllerID,AcceptedBy,DateTimeAccepted,AlarmRepeatFlag,DCSIM,AlarmID)    
				  SELECT @uiMsgInID,A.AlarmLevelID, @dtOriginDateTime1,@intBoxID1, @tiBoxMsgInTypeId1,@dLatitude1,@dLongitude1,REPLACE(A.AlarmFaultDescription,':true',''),CASE WHEN @tiValidGps1 = 0 THEN NULL ELSE 'N/A' END,
							NULL,@ControllerID1,case when ack is not null then 0 end,case when ack is not null then @dtOriginDateTime1 end,
							CASE WHEN A.AlarmFaultDescription IN (Select C.[Description] from rvlfAlarmTransaction C where C.MessageInID = @msgIDLastPacket1) THEN 0 ELSE 1 END,@DCSIM1,
							CASE WHEN A.AlarmFaultDescription IN (Select D.[Description] from rvlfAlarmTransaction D where D.MessageInID = @msgIDLastPacket1) THEN 
							(Select E.AlarmID from rvlfAlarmTransaction E where E.MessageInID IN(@msgIDLastPacket1) AND E.[Description] in (A.AlarmFaultDescription)) ELSE 0 END
				  FROM
						(SELECT AlarmLevelID,REPLACE(a.FieldValue,']','') AS AlarmFaultDescription,c.FieldValue as ack  FROM dbo.rvlf_fn_ConvertArrayToTableWithIdentity(REPLACE(@TripSTS+'|'+@alarmSTS ,'[',''),'|')a
				  left join rvlfAlarmsSeverity b on a.FieldValue=b.AlarmParameter
				  left outer join dbo.rvlf_fn_ConvertArrayToTableWithIdentity(replace(REPLACE(@TripACK+'|'+@alarmACK,'[',''),'_ACK',''),'|')as  c on a.FieldValue=c.FieldValue where len(a.FieldValue)>1) A 
				  WHERE A.AlarmLevelId > 0   and len(a.AlarmFaultDescription)>1  
			  END
		END

		INSERT INTO @AlarmTransactionData (MessageInID,AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,DriverId,ControllerID,AcceptedBy,DateTimeAccepted,AlarmRepeatFlag,DCSIM,AlarmID)
			Select @msgIDLastPacket1,[AlarmLevelId],[DateTimeCreated],BoxId,[AlarmType],Lat,Long,[Description],StreetAddress,NULL,ControllerID,NULL,NULL,2,DCSIM,[AlarmId] from rvlfAlarmTransaction C 
				Where C.[Description] Not IN (Select [Description] from @AlarmTransactionData) AND C.MessageInID = @msgIDLastPacket1

		--To Update the Alarm is Closed I,e..Previous cycle Alarm is Closed
		--Select * From rvlfAlarmTransaction WHERE [MessageInID] = @msgIDLastPacket1 AND [Description] IN (Select [Description] from @AlarmTransactionData Where AlarmRepeatFlag = 2)
		Declare @CurDateTimeForAlarm Datetime
		 Select @CurDateTimeForAlarm = GetUTCDate()
		IF EXISTS(Select AlarmId From rvlfAlarmTransaction WHERE [MessageInID] = @msgIDLastPacket1 AND [Description] IN (Select [Description] from @AlarmTransactionData Where AlarmRepeatFlag = 2))
		BEGIN
			--UPDATE [rvlfAlarm] SET [IsClosed]=1,[ClosedBy]=0,[DateTimeClosed]=GETUTCDATE() WHERE [MessageInID] = @msgIDLastPacket1 AND [Description] Not IN (Select [Description] from @AlarmTransactionData)
			UPDATE [rvlfAlarm] SET [IsClosed]=1,[ClosedBy]=0,[DateTimeClosed] = @CurDateTimeForAlarm WHERE AlarmId IN 
					(Select AlarmId From rvlfAlarmTransaction WHERE [MessageInID] = @msgIDLastPacket1 AND [Description] IN (Select [Description] from @AlarmTransactionData Where AlarmRepeatFlag = 2))
			EXEC rvlf_sp_LogNotificaitons_ForAlarms @CurDateTimeForAlarm,NULL,@tiBoxMsgInTypeId1

			--To Update EndDate and Time for Alarms 1.HT_ON_OFF 2.Contractor_Open
			IF((Select Count(*) FROM @AlarmTransactionData where [Description] in('HT_ON_OFF') AND [AlarmRepeatFlag] = 2 AND ControllerID = @ControllerID1 AND BoxId = @intBoxID1)>1)
			Begin
				-- Log Alarm to Table for KPI Calculation for the Device Type Pricicon-III
				EXEC rvlf_sp_TripDetails_adr @intBoxID1,@ControllerID1,@Controller_Name,@tiBoxMsgInTypeId1,'HT_ON_OFF',@CurDateTimeForAlarm,1
			End
			Else If((Select Count(*) FROM @AlarmTransactionData where [Description] in('Contactor_Open') AND [AlarmRepeatFlag] = 2 AND ControllerID = @ControllerID1 AND BoxId = @intBoxID1)>1)
			Begin
				-- Log Alarm to Table for KPI Calculation for the Device Type Pricicon-R
				EXEC rvlf_sp_TripDetails_adr @intBoxID1,@ControllerID1,@Controller_Name,@tiBoxMsgInTypeId1,'Contactor_Open',@CurDateTimeForAlarm,1
			End
		END
		
		--Select * From @AlarmTransactionData 

		--IF a Alarm is Already Exists so,Logged in AlarmTransaction Table
	 INSERT INTO [rvlfAlarmTransaction]([AlarmId],[MessageInID],[AlarmLevelId],[DateTimeCreated],[BoxId],[AlarmType],[Lat],[Long],[Description],[StreetAddress],[DriverId],[ControllerID],[AcceptedBy],[DateTimeAccepted],[AlarmRepeatFlag],[DCSIM])	
		SELECT AlarmID,@uiMsgInID,AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,DriverId,ControllerID,AcceptedBy,DateTimeAccepted,AlarmRepeatFlag,DCSIM
			FROM @AlarmTransactionData WHERE [AlarmRepeatFlag] = 0

		----New Occurance of Alarm means,Logged into Alarm & AlarmTransaction Table
		IF EXISTS(Select AlarmID FROM @AlarmTransactionData WHERE [AlarmRepeatFlag] = 1)
		BEGIN
			INSERT INTO [rvlfAlarm](MessageInID,AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,DriverId,ControllerID,AcceptedBy,DateTimeAccepted,AlarmRepeatFlag,DCSIM)
					SELECT @uiMsgInID,AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,DriverId,ControllerID,AcceptedBy,DateTimeAccepted,AlarmRepeatFlag,DCSIM
					FROM @AlarmTransactionData 
					WHERE [AlarmRepeatFlag] = 1

			EXEC rvlf_sp_LogNotificaitons_ForAlarms NULL,@uiMsgInID,@tiBoxMsgInTypeId1

			INSERT INTO [rvlfAlarmTransaction]([AlarmId],[MessageInID],[AlarmLevelId],[DateTimeCreated],[BoxId],[AlarmType],[Lat],[Long],[Description],[StreetAddress],[DriverId],[ControllerID],[AcceptedBy],[DateTimeAccepted],[AlarmRepeatFlag],[DCSIM])	
				SELECT B.AlarmID,@uiMsgInID AS MessageInID,A.AlarmLevelId,A.DateTimeCreated,A.BoxId,A.AlarmType,A.Lat,A.Long,A.[Description],A.StreetAddress,A.DriverId,A.ControllerID,A.AcceptedBy,A.DateTimeAccepted,A.AlarmRepeatFlag,A.DCSIM
				FROM @AlarmTransactionData A inner JOIN rvlfAlarm B ON A.MessageInID = B.MessageInID 
				WHERE A.[AlarmRepeatFlag] = 1 AND B.[Description] IN (A.[Description])

			--To Update StartDate and Time for Alarms 1.HT_ON_OFF 2.Contractor_Open
			IF((Select Count(*) FROM @AlarmTransactionData where [Description] in('HT_ON_OFF') AND [AlarmRepeatFlag] = 1 AND ControllerID = @ControllerID1 AND BoxId = @intBoxID1)>1)
			Begin
				-- Log Alarm to Table for KPI Calculation for the Device Type Pricicon-III
				EXEC rvlf_sp_TripDetails_adr @intBoxID1,@ControllerID1,@Controller_Name,@tiBoxMsgInTypeId1,'HT_ON_OFF',@dtOriginDateTime1,0
			End
			Else If((Select Count(*) FROM @AlarmTransactionData where [Description] in('Contactor_Open') AND [AlarmRepeatFlag] = 1 AND ControllerID = @ControllerID1 AND BoxId = @intBoxID1)>1)
			Begin
				-- Log Alarm to Table for KPI Calculation for the Device Type Pricicon-R
				EXEC rvlf_sp_TripDetails_adr @intBoxID1,@ControllerID1,@Controller_Name,@tiBoxMsgInTypeId1,'Contactor_Open',@dtOriginDateTime1,0
			End
		END
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AlarmMessageReceived_VXL]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE  [dbo].[rvlf_sp_AlarmMessageReceived_VXL]
@vcCustomProp varchar(max),
@tiBoxMsgInTypeId TINYINT,
@ControllerID int,
@DCSIM int,
@intBoxID varchar(10),
@dtOriginDateTime datetime,
@msgIDCurrentPacket uniqueidentifier,
@msgIDLastPacket uniqueidentifier
AS
BEGIN
SET NOCOUNT ON;
Declare @dLatitude1 decimal(10,6) = 0
Declare @dLongitude1 decimal(10,6) = 0
Declare @tiValidGps1 smallint = 0
Declare @AlarmTransactionData table
(	MessageInID uniqueidentifier,AlarmLevelId smallint,DateTimeCreated datetime,BoxId varchar(10),AlarmType tinyint,Lat decimal(10,6),Long decimal(10,6),[Description] varchar(250) COLLATE SQL_Latin1_General_CP1_CI_AS,
	StreetAddress varchar(250) COLLATE SQL_Latin1_General_CP1_CI_AS,DriverId bigint,ControllerID tinyint,AcceptedBy bigint,DateTimeAccepted datetime,AlarmRepeatFlag tinyint,DCSIM tinyint,AlarmID int,Rootcause nvarchar(MAX),Correctiveaction nvarchar(MAX))

Declare @vcCustomProp1 varchar(max) = @vcCustomProp,@tiBoxMsgInTypeId1 TINYINT = @tiBoxMsgInTypeId,@intBoxID1 varchar(10) = @intBoxID,@dtOriginDateTime1 datetime = @dtOriginDateTime,
@uiMsgInID uniqueidentifier = @msgIDCurrentPacket,@msgIDLastPacket1 uniqueidentifier = @msgIDLastPacket

declare @alarms varchar(1000) 
declare @paramvalue varchar(10) 
declare @filedvalue varchar(10)
declare @clmnvalue1 varchar(10)
declare @Qry nvarchar(max)=null
declare @equipmenttypeid int 
declare @VFantype tinyint
declare @Tqry nvarchar(max)
declare @alamtbl table (id int,alarmparam varchar(5))
CREATE TABLE #alams (alarmname varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS,Reason nvarchar(MAX) COLLATE SQL_Latin1_General_CP1_CI_AS,CorrectiveAction varchar(MAX) COLLATE SQL_Latin1_General_CP1_CI_AS)
Declare @CurDateTimeForAlarm Datetime = GETUTCDATE()
declare @DigitalInputs char(2)

SELECT @equipmenttypeid=SubTypeId,@VFantype=VFantype from rvlfMAKDevices where BoxId=@intBoxID1
print 'alarms in'
If @tiBoxMsgInTypeId1 IN (1)
begin
SELECT @alarms=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'AlarmMsg=|',';')
--SELECT @alarms=REPLACE(REPLACE(FieldValue,'AlarmMsg=',''),']','') FROM dbo.rvlf_fn_ConvertArrayToTable(@vcCustomProp,';') WHERE FieldValue LIKE 'AlarmMsg%'
--declare @alams table (alarmname varchar(100))
insert into @alamtbl
select * from dbo.rvlf_fn_ConvertArrayToTableWithIdentity(@alarms,'|')

select @DigitalInputs=LastSensorMask from rvlfBoxId where BoxId=@intBoxID

DECLARE @id int =(select min(id) from @alamtbl)
WHILE @id is not null
BEGIN
SELECT @filedvalue= alarmparam ,@clmnvalue1=replace(replace(replace(alarmparam,'R',''),'Y',''),'B','') from @alamtbl where id=@id
--set @paramvalue =RTrim(dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,@filedvalue+'=',';')) 
Declare @dd varchar(1000)='T1,T2,T3,T4,T5,P1,P2,P3,P4,DPs,DPp,DPp1,VR1,VY1,VB1,CR1,CY1,CB1,WH1,PF1,PO1,CR2,CY2,CB2,WH2,PF2,PO2'
If (CHARINDEX(@filedvalue,@dd,0) >0)
Begin
   set @paramvalue =RTrim(dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,@filedvalue+'=',';')) 
End
else
Begin  
  set @Tqry = 'select @d='+@filedvalue+' from rvlfMsgInHst_Primary p inner join rvlfMsgInHst_Secondary s on p.MessageInID=s.MessageInID inner join rvlfMsgInHst_FibreCompactor f on  s.MessageInID=f.MessageInID where p.MessageInID='+''''+ convert(varchar(40




),@msgIDCurrentPacket)+''''  
  declare @xx varchar(1000)
  set @xx = 0
  exec sp_executesql @Tqry, N'@d varchar(1000) out', @paramvalue out  
End

IF(@paramvalue is not null and @paramvalue !='NaN' and @paramvalue !='Not')
BEGIN
--print N'insert into #alams select case when cast('+@paramvalue+' as float)< '+@clmnvalue1+'_Min then ''' +@filedvalue+'_Min'' when cast('+@paramvalue+' as float)> '
--+@clmnvalue1+'_Max then '''+@filedvalue+'_Max'' end from rvlfParamRange where Boxid=''AA0001'''
--print 'Enter1'
SET @qry=N'insert into #alams(alarmname) select case when cast('+@paramvalue+' as float)< '+@clmnvalue1+'_Min then ''' +replace(replace(@filedvalue,'Y','R'),'B','R')+
'_Min'' when cast('+@paramvalue+' as float)> '+@clmnvalue1+'_Max then '''+@filedvalue+'_Max'' end from rvlfParamRange where Boxid='''+@intBoxID+''''

EXECUTE(@qry)
--print 'Enter2'
END
SELECT @id=min(id) from @alamtbl where id>@id
END
 --select replace(replace(alarmname,'Y','R'),'B','R'),* from #alams
--drop table #alams
--INSERT INTO @AlarmTransactionData(MessageInID,AlarmLevelId,DateTimeCreated,BoxId,AlarmType,[Description],StreetAddress,AcceptedBy,DateTimeAccepted,AlarmRepeatFlag,AlarmID)
--SELECT distinct @uiMsgInID,3, @dtOriginDateTime1,@intBoxID1, @tiBoxMsgInTypeId1, alarmname, 'N/A' ,
--NULL,NULL, CASE WHEN alarmname IN (Select C.[Description] from rvlfAlarmTransaction C where C.MessageInID = @msgIDLastPacket1) THEN 0 ELSE 1 END,
--CASE WHEN alarmname IN (Select D.[Description] from rvlfAlarmTransaction D where D.MessageInID = @msgIDLastPacket1) THEN 
--(Select E.AlarmID from rvlfAlarmTransaction E where E.MessageInID IN(@msgIDLastPacket1) AND E.[Description] in (alarmname)) ELSE 0 END 
--FROM #alams a inner join adr_ParamMst b on a.alarmname=b.ParamName   	
END

else If @tiBoxMsgInTypeId1 IN (8)
begin
--print 'Enter3'
 declare @DIP varchar(30)=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'Input=',';')
 delete from #alams
  if (SUBSTRING(@DIP,6,1)=0) 
insert into #alams(alarmname) values ('DigitalIP3')
if (SUBSTRING(@DIP,5,1)=0 and @equipmenttypeid in (3,4))
insert into #alams(alarmname) values ('DigitalIP4')					  
if (SUBSTRING(@DIP,4,1)=0)
insert into #alams(alarmname) values ('DigitalIP5')					  
if (SUBSTRING(@DIP,3,1)=0)
insert into #alams(alarmname) values ('DigitalIP6')	
if (SUBSTRING(@DIP,2,1)=0)
insert into #alams(alarmname) values ('DigitalIP7')					  
if (SUBSTRING(@DIP,1,1)=0)
insert into #alams(alarmname) values ('DigitalIP8')	
if (SUBSTRING(@DIP,16,1)=0)
insert into #alams(alarmname) values ('DigitalIP9')
if (SUBSTRING(@DIP,15,1)=0)
insert into #alams(alarmname) values ('DigitalIP10')	
if (SUBSTRING(@DIP,14,1)=0 and @equipmenttypeid in (2,4))
insert into #alams(alarmname) values ('DigitalIP11')	
if (SUBSTRING(@DIP,13,1)=0 and @equipmenttypeid in (2,4))
insert into #alams(alarmname) values ('DigitalIP12')	
if (SUBSTRING(@DIP,12,1)=0 and @equipmenttypeid in (2,4))
insert into #alams(alarmname) values ('DigitalIP13')	
if (SUBSTRING(@DIP,11,1)=0 and @VFantype >=1)
insert into #alams(alarmname) values ('DigitalIP14')	
if (SUBSTRING(@DIP,10,1)=0 and @VFantype >=1)
insert into #alams(alarmname) values ('DigitalIP15')	
if (SUBSTRING(@DIP,9,1)=0 and @VFantype >1)
insert into #alams(alarmname) values ('DigitalIP16')	
if (SUBSTRING(@DIP,24,1)=0  and @VFantype >1)
insert into #alams(alarmname) values ('DigitalIP17')	
if (SUBSTRING(@DIP,23,1)=0 and @VFantype >2)
insert into #alams(alarmname) values ('DigitalIP18')	
if (SUBSTRING(@DIP,22,1)=0 and @VFantype >2)
insert into #alams(alarmname) values ('DigitalIP19')	
if (SUBSTRING(@DIP,21,1)=0 and @VFantype >3)
insert into #alams(alarmname) values ('DigitalIP20')	
if (SUBSTRING(@DIP,20,1)=0 and @VFantype >3)
insert into #alams(alarmname) values ('DigitalIP21')
print 'Enter4'
	IF not exists(select * FROM #alams)
	BEGIN			
			UPDATE [rvlfAlarm] SET [IsClosed]=1,[ClosedBy]=0,[DateTimeClosed] = @CurDateTimeForAlarm WHERE BoxID=@intBoxID1 
					AND ([IsClosed] IS NULL OR [IsClosed] = 0 OR [IsClosed]='') and AlarmType=@tiBoxMsgInTypeId1				
					--print 'Enter5'	
			--EXEC rvlf_sp_LogNotificaitons_ForAlarms @CurDateTimeForAlarm,NULL,@tiBoxMsgInTypeId1
	END
end

--Update the alarm Reason and corrective action -**************Start************

 declare @tblAlarm table(id int identity(1,1),AlarmName nvarchar(200))

 declare @tblAlarmDesc table(AlarmName nvarchar(200),SubAlarmName nvarchar(200))

 insert into @tblAlarm
 select alarmname from #alams where alarmname is not null

 declare @StartValue int=1, @Totcount int, @alarmname nvarchar(200),@Reason nvarchar(MAX)='',@CorrectiveAction nvarchar(MAX)=''
 
 select @Totcount=COUNT(*) from @tblAlarm

 while(@Totcount>=@StartValue)
	 begin
		delete from @tblAlarmDesc
		select @alarmname=AlarmName from @tblAlarm where id=@StartValue
		insert into @tblAlarmDesc
		select @alarmname,AlarmName from @tblAlarm where AlarmName not in (@alarmname)
		if exists(select b.ParamName from rvlfAlarmconfig a inner join rvlfParamMst b on a.Paramid=b.ParamId inner join @tblAlarmDesc c on b.ParamName=c.AlarmName and a.AlarmParamName=c.SubAlarmName where ParamName=@alarmname)
			begin
				select top 1 @Reason=a.Reason,@CorrectiveAction=a.CorrectiveAction from rvlfAlarmconfig a inner join rvlfParamMst b on a.Paramid=b.ParamId inner join @tblAlarmDesc c on b.ParamName=c.AlarmName and a.AlarmParamName=c.SubAlarmName order by a.Sno
			end
		else
			begin	
				select top 1 @Reason=MReason,@CorrectiveAction=MCorrectiveAction from rvlfParamMst where ParamName=@alarmname
			end
		update #alams set Reason=@Reason,CorrectiveAction=@CorrectiveAction where alarmname=@alarmname
		select @StartValue=@StartValue+1
	 end
------------------------------------------END-----------------------------------


 --print 'Enter23'	
 
INSERT INTO @AlarmTransactionData(MessageInID,AlarmLevelId,DateTimeCreated,BoxId,AlarmType,[Description],StreetAddress,AcceptedBy,DateTimeAccepted,AlarmRepeatFlag,AlarmID,Rootcause,Correctiveaction)
	SELECT distinct @uiMsgInID,3, @dtOriginDateTime1,@intBoxID1, @tiBoxMsgInTypeId1, a.alarmname, 'N/A' ,
NULL,NULL, CASE WHEN a.alarmname IN (Select C.[Description] from rvlfAlarmTransaction C where C.MessageInID = @msgIDLastPacket1) THEN 0 ELSE 1 END,
CASE WHEN a.alarmname IN (Select D.[Description] from rvlfAlarmTransaction D where D.MessageInID = @msgIDLastPacket1) THEN 
(Select E.AlarmID from rvlfAlarmTransaction E where E.MessageInID IN(@msgIDLastPacket1) AND E.[Description] in (a.alarmname)) ELSE 0 END,a.Reason,a.CorrectiveAction 
FROM #alams a inner join rvlfParamMst b on a.alarmname=b.ParamName
inner join rvlfAlarmsDesc c on b.ParamId=c.ParamID where c.EquipmentType=@equipmenttypeid
--print 'Enter6'	

INSERT INTO @AlarmTransactionData (MessageInID,AlarmLevelId,DateTimeCreated,BoxId,AlarmType,[Description],AcceptedBy,DateTimeAccepted,AlarmRepeatFlag,AlarmID)
Select @msgIDLastPacket1,[AlarmLevelId],[DateTimeCreated],BoxId,[AlarmType],[Description],NULL,NULL,2,[AlarmId] from rvlfAlarmTransaction C 
Where C.[Description] Not IN (Select [Description] from @AlarmTransactionData) AND C.MessageInID = @msgIDLastPacket1
--print 'Enter7'	
--To Update the Alarm is Closed I,e..Previous cycle Alarm is Closed
--Select * From rvlfAlarmTransaction WHERE [MessageInID] = @msgIDLastPacket1 AND [Description] IN (Select [Description] from @AlarmTransactionData Where AlarmRepeatFlag = 2)
--Declare @CurDateTimeForAlarm Datetime
-- Select @CurDateTimeForAlarm = GetUTCDate()
IF EXISTS(Select AlarmId From rvlfAlarmTransaction WHERE [MessageInID] = @msgIDLastPacket1 AND [Description] IN (Select [Description] from @AlarmTransactionData Where AlarmRepeatFlag = 2))
BEGIN

		--UPDATE [rvlfAlarm] SET [IsClosed]=1,[ClosedBy]=0,[DateTimeClosed]=GETUTCDATE() WHERE [MessageInID] = @msgIDLastPacket1 AND [Description] Not IN (Select [Description] from @AlarmTransactionData)
		--print 'Enter8'	
			 UPDATE [rvlfAlarm] SET [IsClosed]=1,[ClosedBy]=0,[DateTimeClosed] = @CurDateTimeForAlarm WHERE AlarmId IN 
					(Select AlarmId From rvlfAlarmTransaction WHERE [MessageInID] = @msgIDLastPacket1 AND [Description] IN (Select [Description] from @AlarmTransactionData Where AlarmRepeatFlag = 2))
			--EXEC rvlf_sp_LogNotificaitons_ForAlarms @CurDateTimeForAlarm,NULL,@tiBoxMsgInTypeId1

			--To Update EndDate and Time for Alarms 1.HT_ON_OFF 2.Contractor_Open
			--IF((Select Count(*) FROM @AlarmTransactionData where [Description] in('HT_ON_OFF') AND [AlarmRepeatFlag] = 2 AND ControllerID = @ControllerID1 AND BoxId = @intBoxID1)>1)
			--Begin
			--	-- Log Alarm to Table for KPI Calculation for the Device Type Pricicon-III
			--	EXEC rvlf_sp_TripDetails_adr @intBoxID1,@ControllerID1,@Controller_Name,@tiBoxMsgInTypeId1,'HT_ON_OFF',@CurDateTimeForAlarm,1
			--End
			--Else If((Select Count(*) FROM @AlarmTransactionData where [Description] in('Contactor_Open') AND [AlarmRepeatFlag] = 2 AND ControllerID = @ControllerID1 AND BoxId = @intBoxID1)>1)
			--Begin
			--	-- Log Alarm to Table for KPI Calculation for the Device Type Pricicon-R
			--	EXEC rvlf_sp_TripDetails_adr @intBoxID1,@ControllerID1,@Controller_Name,@tiBoxMsgInTypeId1,'Contactor_Open',@CurDateTimeForAlarm,1
			--End
END
		
--Select * From @AlarmTransactionData 
--print 'Enter9'	
		--IF a Alarm is Already Exists so,Logged in AlarmTransaction Table
	 INSERT INTO [rvlfAlarmTransaction]([AlarmId],[MessageInID],[AlarmLevelId],[DateTimeCreated],[BoxId],[AlarmType],[Description],[AcceptedBy],[DateTimeAccepted],[AlarmRepeatFlag])	
		SELECT AlarmID,@uiMsgInID,AlarmLevelId,DateTimeCreated,BoxId,AlarmType,[Description],AcceptedBy,DateTimeAccepted,AlarmRepeatFlag
			FROM @AlarmTransactionData WHERE [AlarmRepeatFlag] = 0
--print 'Enter10'	
		----New Occurance of Alarm means,Logged into Alarm & AlarmTransaction Table
		IF EXISTS(Select AlarmID FROM @AlarmTransactionData WHERE [AlarmRepeatFlag] = 1)
		BEGIN

		if(SUBSTRING(@DigitalInputs,1,1)=0)
		begin
			delete from @AlarmTransactionData where [Description] in ('P3_Max','P3_Min','P4_Max','P4_Min','DPs_Max','DPs_Min','DPp_Max','DPp_Min','DPp1_Max','DPp1_Min','CR1_Min','CR2_Min')			 
		end
		--print 'Enter11'	
			INSERT INTO [rvlfAlarm](MessageInID,AlarmLevelId,DateTimeCreated,BoxId,AlarmType,[Description],AcceptedBy,DateTimeAccepted,AlarmRepeatFlag,[Lat],[Long],Rootcause,Correctiveaction)
					SELECT @uiMsgInID,AlarmLevelId,DateTimeCreated,BoxId,AlarmType,[Description],AcceptedBy,DateTimeAccepted,AlarmRepeatFlag,0,0,Rootcause,Correctiveaction
					FROM @AlarmTransactionData 
					WHERE [AlarmRepeatFlag] = 1 
--print 'Enter12'	
			--EXEC rvlf_sp_LogNotificaitons_ForAlarms NULL,@uiMsgInID,@tiBoxMsgInTypeId1

			INSERT INTO [rvlfAlarmTransaction]([AlarmId],[MessageInID],[AlarmLevelId],[DateTimeCreated],[BoxId],[AlarmType],[Lat],[Long],[Description],[AcceptedBy],[DateTimeAccepted],[AlarmRepeatFlag])	
				SELECT B.AlarmID,@uiMsgInID AS MessageInID,A.AlarmLevelId,A.DateTimeCreated,A.BoxId,A.AlarmType,0,0,A.[Description],A.AcceptedBy,A.DateTimeAccepted,A.AlarmRepeatFlag
				FROM @AlarmTransactionData A inner JOIN rvlfAlarm B ON A.MessageInID = B.MessageInID 
				WHERE A.[AlarmRepeatFlag] = 1 AND B.[Description] IN (A.[Description])
				
			--Update alarms status 
			Declare @alarmlvlid smallint
			select  @alarmlvlid= max( AlarmLevelId)  from   @AlarmTransactionData 			
			update rvlfBoxId set ControllerID= case when ControllerID is null or ControllerID<@alarmlvlid then @alarmlvlid else ControllerID end where 
			BoxId=@intBoxID1

				--print 'Enter13'	
			----To Update StartDate and Time for Alarms 1.HT_ON_OFF 2.Contractor_Open
			--IF((Select Count(*) FROM @AlarmTransactionData where [Description] in('HT_ON_OFF') AND [AlarmRepeatFlag] = 1 AND ControllerID = @ControllerID1 AND BoxId = @intBoxID1)>1)
			--Begin
			--	-- Log Alarm to Table for KPI Calculation for the Device Type Pricicon-III
			--	EXEC rvlf_sp_TripDetails_adr @intBoxID1,@ControllerID1,@Controller_Name,@tiBoxMsgInTypeId1,'HT_ON_OFF',@dtOriginDateTime1,0
			--End
			--Else If((Select Count(*) FROM @AlarmTransactionData where [Description] in('Contactor_Open') AND [AlarmRepeatFlag] = 1 AND ControllerID = @ControllerID1 AND BoxId = @intBoxID1)>1)
			--Begin
			--	-- Log Alarm to Table for KPI Calculation for the Device Type Pricicon-R
			--	EXEC rvlf_sp_TripDetails_adr @intBoxID1,@ControllerID1,@Controller_Name,@tiBoxMsgInTypeId1,'Contactor_Open',@dtOriginDateTime1,0
			--End
		END
		drop table #alams
END

 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AMScorrectiveAct]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_AMScorrectiveAct]         
(          
@CorrectiveActionId int=null,          
@CorrectiveActionName varchar(25)=null,          
@CorrectiveActionDesc varchar(150)=null,          
@bigOrganizationId bigint = Null,                                    
@bigUserId bigint = Null,          
@OperationType char          
)          
as          
/******************************************************************************/                                                    
-- Name  : rvlf_sp_AMScorrectiveAct null,null,null,6,303,'s'          
-- Description : Get Accident type master details          
-- Author  : Gopal.R            
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--Created Date -08-Oct-2014             
/******************************************************************************/            
begin          
if @OperationType='S'          
select CorrectiveActionId,CorrectiveActionName,CorrectiveActionDesc from rvlfAccidentCorrectiveActions where OrganizationId=@bigOrganizationId and [Status]=1         
and (@CorrectiveActionId is null or @CorrectiveActionId=0 or CorrectiveActionId=@CorrectiveActionId)        
else if @OperationType='U'          
begin          
update rvlfAccidentCorrectiveActions set CorrectiveActionName=@CorrectiveActionName,CorrectiveActionDesc=@CorrectiveActionDesc,          
ModifiedBy=@bigUserId,ModifiedDate=getutcdate(),OrganizationId=@bigOrganizationId          
where CorrectiveActionId=@CorrectiveActionId          
end          
else if @OperationType='I'          
begin          
insert into rvlfAccidentCorrectiveActions values (@CorrectiveActionName,@CorrectiveActionDesc,@bigUserId,GETUTCDATE(),@bigUserId,GETUTCDATE(),@bigOrganizationId,1)          
end          
else if @OperationType='D'          
update rvlfAccidentCorrectiveActions set Status=0,ModifiedBy=@bigUserId,ModifiedDate=getutcdate()where CorrectiveActionId=@CorrectiveActionId          
end             
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AMSReasons]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_AMSReasons]  
(          
@AccidentReasonId   int=null,          
@AccidentReasonName varchar(25)=null,          
@AccidentReasonDesc varchar(150)=null,    
@AccidentReasonGroupID int=null,        
@bigOrganizationId bigint = Null,                                    
@bigUserId bigint = Null,          
@OperationType char          
)          
as          
/******************************************************************************/                                                    
-- Name  : rvlf_sp_AMSReasons null,null,null,null,6,303,'s'          
-- Description : Get Accident type master details          
-- Author  : Gopal.R            
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--Created Date -08-Oct-2014             
/******************************************************************************/            
begin          
if @OperationType='S'          
select AccidentReasonId  ,AccidentReasonName,AccidentReasonDesc,ARG.AccidentReasonGroupName,ARG.AccidentReasonGroupID from rvlfAccidentReasons AR  
inner join rvlfAccidentReasonGroups ARG on AR.AccidentReasonGroupID=ARG.AccidentReasonGroupID  
and AR.OrganizationId=ARG.OrganizationId where AR.OrganizationId=@bigOrganizationId and AR.[Status]=1         
and (@AccidentReasonId is null or @AccidentReasonId=0 or AccidentReasonId=@AccidentReasonId)        
else if @OperationType='U'          
begin          
update rvlfAccidentReasons set AccidentReasonName=@AccidentReasonName,AccidentReasonDesc=@AccidentReasonDesc,AccidentReasonGroupID=@AccidentReasonGroupID,          
ModifiedBy=@bigUserId,ModifiedDate=getutcdate(),OrganizationId=@bigOrganizationId          
where AccidentReasonId  =@AccidentReasonId          
end          
else if @OperationType='I'          
begin          
insert into rvlfAccidentReasons values (@AccidentReasonName,@AccidentReasonDesc,@AccidentReasonGroupID,@bigUserId,GETUTCDATE(),@bigUserId,GETUTCDATE(),@bigOrganizationId,1)          
end          
else if @OperationType='D'          
update rvlfAccidentReasons set Status=0,ModifiedBy=@bigUserId,ModifiedDate=getutcdate()where AccidentReasonId  =@AccidentReasonId          
end             

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AMSTypeMstr]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_AMSTypeMstr]    
(    
@AccidentTypeId int=null,    
@AccidentTypeName varchar(25)=null,    
@AccidentTypeDesc varchar(150)=null,    
@bigOrganizationId bigint = Null,                              
@bigUserId bigint = Null,    
@OperationType char    
)    
as    
/******************************************************************************/                                              
-- Name  : rvlf_sp_AMSTypeMstr null,null,null,6,303,'s'    
-- Description : Get Accident type master details    
-- Author  : Gopal.R      
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--Created Date -08-Oct-2014       
/******************************************************************************/      
begin    
if @OperationType='S'    
select AccidentTypeId,AccidentTypeName,AccidentTypeDesc from rvlfAccidentTypes where OrganizationId=@bigOrganizationId and IsDelete=0   
and (@AccidentTypeId is null or @AccidentTypeId=0 or AccidentTypeId=@AccidentTypeId)  
else if @OperationType='U'    
begin    
update rvlfAccidentTypes set AccidentTypeName=@AccidentTypeName,AccidentTypeDesc=@AccidentTypeDesc,    
ModifiedBy=@bigUserId,ModifiedDate=getutcdate(),OrganizationId=@bigOrganizationId    
where AccidentTypeId=@AccidentTypeId    
end    
else if @OperationType='I'    
begin    
insert into rvlfAccidentTypes values (@AccidentTypeName,@AccidentTypeDesc,@bigUserId,GETUTCDATE(),@bigUserId,GETUTCDATE(),@bigOrganizationId,0)    
end    
else if @OperationType='D'    
update rvlfAccidentTypes set IsDelete=1,ModifiedBy=@bigUserId,ModifiedDate=getutcdate()where AccidentTypeId=@AccidentTypeId    
end       
    
    
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignAndUnAssignDriverGroup]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_AssignAndUnAssignDriverGroup]  
 @bigDriverGroupId bigint = null,  
 @bigAssignedBy bigint = null,  
 @bitIsAssign bit=null,   
 @vcDriverIDs varchar(250) = null,  
 @bigOrganizationID bigint=null  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_AssignAndUnAssignDriverGroup  
-- Description : To assign or unassign drivers to the driver group in bulk manner  
-- Author  : Narayanasamy .V  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 25-Sep-2010 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
 IF(@bitIsAssign =1)  
  BEGIN  
     
    DELETE FROM rvlfDRIVERGroupAssignment WHERE DRIVERID IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcDriverIDs,','))  
  
    INSERT INTO rvlfDRIVERGroupAssignment(DRIVERID, DRIVERGROUPID, AssignedBy, AssignedDate)  
    (SELECT d.DriverId ,@bigDriverGroupId, @bigAssignedBy,GETDATE() FROM rvlfDriverMaster D   
     WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR d.OrganizationId = @bigOrganizationID)  
      AND d.DriverId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcDriverIDs,',')))    
  END  
 ELSE  
  BEGIN  
   DELETE FROM rvlfDRIVERGroupAssignment WHERE DRIVERID IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcDriverIDs,','))  
  END  
   
      
     
   
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignKeys]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_AssignKeys]       
/*************************************************************************************      
Stored Procedure Name : rvlf_sp_AssignKeys      
Purpose               : Select,Insert,Modify and Delete Ibutton Settings  
Created by            : Ranjith     
Created date          : 13-Sep-11      
Updated by            :    
Updated date          :    
**************************************************************************************/      
@BigIntIbuttonId int=null,     
@vcIButtonKey varchar(50)=null,  
@vcIButtonName varchar(50)=null,  
@vcOrgId int=null,  
@IntFlag int=null,
@IntKeyType int=null,
@vcUserName varchar(200)=null
  
AS    
begin  
--Get Unassigned Keys  
if @IntFlag =1
     begin  
      select * from rvlfIButtonMapping   
         where UserName is null and OrganizationId=@vcOrgId and KeyType=@IntKeyType 
     end  
--Get assigned Keys  
else if @IntFlag =2  
    begin  
       select i.IButtonId,i.IButtonKey,i.IButtonKeyName,(case when @IntKeyType =1 then d.DriverName else i.UserName end) as Keyuser from rvlfIButtonMapping i  
         left join rvlfDriverMaster d on d.DriverId=i.DriverId  
          where i.UserName is not null and i.OrganizationId=@vcOrgId and KeyType=@IntKeyType  order by i.IButtonKeyName           
         
    end  
--Checking duplicate Username Entry  
else if @IntFlag =3  
     begin  
     select * from rvlfIButtonMapping   
          where lower(replace(UserName,' ',''))=lower(replace(@vcUserName,' ',''))  
       and (@BigIntIbuttonId IS NULL OR @BigIntIbuttonId='' Or  IButtonId <> @BigIntIbuttonId)   
       --select * from rvlfIButtonMapping   
       --where lower(replace(IButtonKey,' ',''))=lower(replace(@vcIButtonKey,' ',''))  
     end  
--Assign Key
else if @IntFlag =4  
     begin  
     update rvlfIButtonMapping set UserName = @vcUserName
          where  IButtonId=@BigIntIbuttonId               
     end  
end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignMaintenanceService]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_AssignMaintenanceService]
	@bigServiceCategoryId bigint = null,
	@vcServiceIDs varchar(250) = null,
    @bigAssignedBy bigint = null,
	@dtAssignedDate Datetime = null
AS
/******************************************************************************/
--	Name		:	rvlf_sp_AssignMaintenanceService
--	Description	:	To assign maintenance services to the service category in bulk manner
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>>       Initial Reason
--				:	29-Jun-2010	Kumuthini. L	Created Intial Version 
/******************************************************************************/
BEGIN
--SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
	
	BEGIN TRY
		
		DELETE FROM rvlfMaintenanceCategoryService WHERE ServiceCategoryId = @bigServiceCategoryId
		
		INSERT INTO rvlfMaintenanceCategoryService (ServiceCategoryId, ServiceId, AssignedBy, AssignedDate) 
		    (SELECT @bigServiceCategoryId, ms.ServiceId ,@bigAssignedBy, @dtAssignedDate 
		     FROM rvlfMaintenanceService ms
		     WHERE ms.ServiceId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcServiceIDs,',')))
	
	END TRY
	BEGIN CATCH
		SET @ErrorMessage = 'An Error occured during assigning maintenance services to the service category : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignPackages]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_AssignPackages]

@bigPackageOrgId BIGINT = NULL, 
@bigPackageId BIGINT,
@bigOrganizationID BIGINT,
@dtPurchasedOn DateTime,
@dtExpiresOn DateTime,
@bigCreatedBy BIGINT,
@dtCreatedDateTime DateTime

AS

/******************************************************************************/
--	Name		:	rvlf_sp_AssignPackages
--	Description	:	To assign a package to the organization
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	25-Nov-2009		Created Intial Version 
--				:	26-Nov-2009	VN Update the organiztion page set expriry date
--				:	1-Dec-2009	VN delete \ asssign the user priviledges 
--				:	08-Apr-2010 MJJC Retained the rights for the exisiting operation and 
--									 module for the non security admins
--				:	09-Apr-2010 MJJC Based on the new packages messages the severity for the boxes is manipulated
--				:	19-Jun-2010	MJJC Included the organization check in the loop while setting severities.
--				:	19-Jun-2010 VN Insert the default violation rating if the pakage have driver module.
--				:	02-Jul-2010 MJJC Included null checking for the operations while removing the rights
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	
	IF(@bigPackageOrgId > 0)
	BEGIN
	
		DECLARE @OldPackageId BIGINT = 0
		
		SET @OldPackageId = (SELECT PackageId FROM rvlfOrganizationPackage WHERE PackageOrgId = @bigPackageOrgId)
		
		IF(@OldPackageId = @bigPackageId)
		BEGIN		
			UPDATE rvlfOrganizationPackage SET PurchasedOn = @dtPurchasedOn, ExpiresOn = @dtExpiresOn WHERE PackageOrgId = @bigPackageOrgId					
		END
		ELSE
		BEGIN
			IF NOT EXISTS(SELECT PackageOrgId FROM rvlfOrganizationPackage WHERE PackageId = @bigPackageId AND OrganizationID = @bigOrganizationID AND IsActive = 1)
			BEGIN
				
				UPDATE rvlfOrganizationPackage SET IsActive = 0 WHERE PackageOrgId = @bigPackageOrgId 
				
				INSERT INTO rvlfOrganizationPackage (PackageId, OrganizationID, PurchasedOn, ExpiresOn, IsActive, CreatedBy, CreatedDateTime)
				VALUES (@bigPackageId, @bigOrganizationID, @dtPurchasedOn, @dtExpiresOn, 1, @bigCreatedBy, @dtCreatedDateTime)
			
			END
		END
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT PackageOrgId FROM rvlfOrganizationPackage WHERE PackageId = @bigPackageId AND OrganizationID = @bigOrganizationID AND IsActive = 1)
			BEGIN		
				INSERT INTO rvlfOrganizationPackage (PackageId, OrganizationID, PurchasedOn, ExpiresOn, IsActive, CreatedBy, CreatedDateTime)
					VALUES (@bigPackageId, @bigOrganizationID, @dtPurchasedOn, @dtExpiresOn, 1, @bigCreatedBy, @dtCreatedDateTime)													
			END
	END
	
	UPDATE rvlfOrganization SET ExpiresOn=@dtExpiresOn WHERE OrganizationId=@bigOrganizationID 
	
	DECLARE @userGroupId bigint = null

	SET @userGroupId = (SELECT UserGroupId FROM rvlfUserGroup WHERE OrganizationId = @bigOrganizationID AND IsDefaultUserGroup = 1)
		
	IF @userGroupId IS NOT NULL
	BEGIN
		print 1
		DELETE FROM rvlfUserGroupSecurity WHERE UserGroupId in (SELECT UserGroupId FROM rvlfUserGroup WHERE OrganizationId = @bigOrganizationID AND IsDefaultUserGroup =1)
		DELETE FROM rvlfUserGroupSecurity WHERE SecurityId in (select SecurityId from rvlfUserGroupSecurity 
			WHERE UserGroupId IN 
			(SELECT UserGroupId FROM rvlfUserGroup WHERE OrganizationId = @bigOrganizationID 
				AND IsDefaultUserGroup =0) AND OperationTypeId NOT IN
			(SELECT OperationID FROM rvlfPackageOperations WHERE PackageId = @bigPackageId and OperationID IS NOT NULL))
 print 2
		DELETE  FROM rvlfUserGroupSecurity WHERE SecurityId in (select SecurityId  from rvlfUserGroupSecurity 
			WHERE UserGroupId  IN 
			(SELECT UserGroupId FROM rvlfUserGroup WHERE OrganizationId = @bigOrganizationID 
				AND IsDefaultUserGroup =0) AND ModuleId NOT IN
			(SELECT ModuleId FROM rvlfPackageOperations WHERE PackageId = @bigPackageId))
 /***** To assign the rights to the security admin or the group which is default to the organization *****/
		INSERT INTO rvlfUserGroupSecurity 
			(UserGroupId,ModuleID,OperationTypeId, CreatedBy, CreatedDateTime) 
			SELECT @userGroupId, ModuleID,OperationID, @bigCreatedBy, @dtCreatedDateTime
				FROM rvlfPackageOperations WHERE PackageId = @bigPackageId
    END
    
    /***** To delete the message from the message severity for the messages not available in the pacakge *****/
	DECLARE @intBoxID int
	SELECT @intBoxID = MAX(bs.BoxId) FROM rvlfBoxSettings bs 
		INNER JOIN rvlfVehicleAssignment va ON bs.BoxId = va.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId 
		WHERE OrganizationId = @bigOrganizationID
	WHILE @intBoxID IS NOT NULL
		BEGIN
		print @intBoxID
			/***** To insert the new message for the boxes *********/
			INSERT INTO rvlfBoxMsgSeverity 
			SELECT @intBoxID,b.BoxMsgInTypeId, p.DefaultAlarmLevel FROM rvlfBoxMsgInType b 
				INNER JOIN rvlfBoxProtocolMsgInType p ON b.BoxMsgInTypeId = p.BoxMsgInTypeId
				WHERE b.OperationTypeID IN (SELECT OperationID FROM rvlfPackageOperations 
					WHERE PackageId = @bigPackageId)
				AND b.CanSeveritySet = 1 AND b.BoxMsgInTypeId NOT IN 
				 (SELECT BoxMsgInTypeId FROM rvlfBoxMsgSeverity WHERE BoxId = @intBoxID)
			
			/***** To delete the message from boxes *********/
			DELETE FROM rvlfBoxMsgSeverity  WHERE BoxId=@intBoxID AND BoxMsgInTypeId IN
				(SELECT bs.BoxMsgInTypeId FROM rvlfBoxMsgSeverity bs INNER JOIN rvlfBoxMsgInType m
					ON bs.BoxMsgInTypeId= m.BoxMsgInTypeId WHERE bs.BoxId= @intBoxID AND OperationTypeID NOT IN
						(SELECT OperationID FROM rvlfPackageOperations WHERE PackageId = @bigPackageId
						 AND OperationID IS NOT NULL ))
			
			SELECT @intBoxID = MAX(bs.BoxId) FROM rvlfBoxSettings bs
				INNER JOIN rvlfVehicleAssignment va ON bs.BoxId = va.BoxId
				INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId 
			WHERE OrganizationId = @bigOrganizationID
				AND bs.BoxId < @intBoxID
		END
		
	--ASSIGN THE DEFAULT VIOLATION RATING
	IF EXISTS(SELECT * FROM rvlfPackageOperations WHERE PackageId=@bigPackageId AND ModuleID=28) 
		BEGIN
			DELETE rvlfViolationRating WHERE OrganizationID=@bigOrganizationID  
			INSERT INTO rvlfViolationRating(BoxMsgInTypeID,OrganizationID,Rating,VehicleID)
				SELECT BoxMsgInTypeId,@bigOrganizationID,10,0 FROM rvlfBoxMsgInType WHERE Isviolation=1
		END	
	ELSE
		BEGIN
			DELETE rvlfViolationRating WHERE OrganizationID=@bigOrganizationID  
		END		
		
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignRFIDDriversToVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_AssignRFIDDriversToVehicles]      
@bigVehicleID BIGINT = NULL,      
@bigIButtonIDs VARCHAR(max) = NULL,      
@bigOrganizationID INT = NULL,      
@bigQueryingUser INT = NULL,      
@operation TINYINT = NULL ,    
@IsCmdPage bit = 1    
AS      
/******************************************************************************/              
-- Proc. Name : rvlf_sp_AssignRFIDDriversToVehicles      
-- Description : To assign RFID driver to the selected vehicles      
-- Author   : SAKTHI GOPINATH S      
-- Company  : Trinetra Wireless (P) Ltd      
-- History   : <<Date(dd-MON-yyyy)>> Initial Reason      
--      : 12-Sep-2014  Created Intial Version      
/******************************************************************************/           
BEGIN      
SET NOCOUNT ON      
    
if (@IsCmdPage=0) -- done for the RFID assignement screen.    
begin    
set @bigVehicleID = (select VehicleId from rvlfVehicleAssignment where BoxId=@bigVehicleID)    
end    
    
 IF @operation = 1 --Add Operation      
 BEGIN      
  INSERT INTO dbo.rvlfVehicleRFIDs(VehicleId,IButtonID,AssignedBy,AssignedDate)      
  --VALUES(@bigVehicleID,@bigIButtonID,@bigQueryingUser,GETUTCDATE())      
  SELECT @bigVehicleID,FieldValue, @bigQueryingUser,GETUTCDATE() FROM dbo.rvlf_fn_ConvertArrayToTableWithIdentity(@bigIButtonIDs,',')      
 END      
 ELSE IF @operation IN (2,3) --Delete & Delete All Operation      
 BEGIN      
  DELETE dbo.rvlfVehicleRFIDs WHERE VehicleId=@bigVehicleID AND (@bigIButtonIDs IS NULL OR @bigIButtonIDs='' OR IButtonID IN       
  (SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTableWithIdentity(@bigIButtonIDs,',')))      
 END      
SET NOCOUNT OFF      
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignRoute]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_AssignRoute]  
(
@Scheduleid bigint,
@bigQueryingUser bigint,
@Operation bit=1
)
as
--rvlf_sp_AssignRoute 3459,292
--GEt assigned routes and delete 
--Date : 13-Jan-2016
--Pages RouteAssignment page
begin

if(@Operation=1)
begin
 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                         

	select AssignmentId,RouteId,rva.VehicleId,fv.FleetId,
	FORMAT(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,FromDateTime)),'dd MMM yyyy h:mm:ss tt')as FromDateTime1,
	FORMAT(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,ToDateTime)),'dd MMM yyyy h:mm:ss tt')as ToDateTime1,
	--CONVERT(VARCHAR(19),dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,FromDateTime))) as FromDateTime1,
	--CONVERT(VARCHAR(19),dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,ToDateTime))) as ToDateTime1,
	replace(Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,FromDateTime)),@DefaultDateFormat),' ','-') as FromDateTime,
	replace(Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,ToDateTime)),@DefaultDateFormat),' ','-') as ToDateTime,
	ScheduleId,Frequency,WeekDays,[DayOfMonth] from rvlfRouteVehicleAssignment  RVA
	inner join rvlfFleetVehicles fv on rva.VehicleId=fv.VehicleId
	where ScheduleId=@Scheduleid
end
else
	begin
	IF(@scheduleid !='' and @scheduleid!=0 and @scheduleid is not null)
	BEGIN
		UPDATE rvlfRouteVehicleAssignment   set Isdelete=1 
		WHERE ScheduleId =@scheduleid
		UPDATE rvlfScheduleOfCommandsMaster set Isdelete=1  
		where ScheduleId =@scheduleid
		select 0
	END
	end
End

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignTempUserVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_AssignTempUserVehicles]     
 @vcVehicleIDs				varchar(250) = null,
 @Email						varchar(250)=null,
 @MobileNo					varchar(20)=null,
 @dtExpiresFrom  			Datetime = NULL,
 @dtExpiresTo				Datetime = NULL,
 @vcRemarks					varchar(500) = NULL,
 @bigCreatedBy				bigint = NULL,
 @dtCreatedDateTime			Datetime = NULL
AS    
/******************************************************************************/    
-- Name  : [rvlf_sp_AssignTempUserVehicles]    
-- Description : To assign vehicles to the Temp User in bulk manner    
-- Author  : N.Ranjith
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 21-Jul-2016 Created Intial Version     
/******************************************************************************/    
BEGIN    
--SET NOCOUNT ON     
 -- Local variables to hold the intermediate results    
 DECLARE @ErrorMessage varchar(3000)    
     
 BEGIN TRAN MessageOutTransaction    
 BEGIN TRY    
    
  DECLARE @tblVehicleIds TABLE(VehicleID bigint)

  --INSERT INTO @tblVehicleIds
  --SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcVehicleIDs,',')

  --DECLARE @MinVehicleId bigint
  --SELECT @MinVehicleId = MIN(VehicleID) FROM @tblVehicleIds

  --WHILE @MinVehicleId IS NOT NULL
  --BEGIN

  --Added for Lease Management Settings 25-02-2016
  INSERT INTO rvlfVehicleTempUserAssignment(VehicleID,TokenID,Email,MobileNo,ExpiresFrom,ExpiresTo,Remarks,isDelete,isAssign,CreatedBy,CreatedDateTime)
  SELECT @vcVehicleIDs,newid(),@Email,@MobileNo,@dtExpiresFrom,@dtExpiresTo,@vcRemarks,0,0, @bigCreatedBy, @dtCreatedDateTime 
  
  --SELECT @MinVehicleId = MIN(VehicleID) FROM @tblVehicleIds WHERE VehicleID > @MinVehicleId

  --END
           
 COMMIT TRAN    
 END TRY    
 BEGIN CATCH    
  ROLLBACK TRAN     
  SET @ErrorMessage = 'An Error occured during assigning vehicles to the fleet : ' + ERROR_MESSAGE()    
  RAISERROR( @ErrorMessage,16,1)    
 END CATCH    
SET NOCOUNT OFF    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignUnassignStudent]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_AssignUnassignStudent]          
 @intVehicleId int = null,          
 @bigAssignedBy bigint = null,          
 @dtAssignedDate Datetime = null,          
 @bigOrganizationID bigint = null,          
 @vcStudentIDs varchar(250) = null,      
 @IntAssignUnassign int = null,
 @IntMode int = null
AS          
/******************************************************************************/          
-- Name  : rvlf_sp_AssignUnassignStudent          
-- Description : To assign users to the user group in bulk manner          
-- Author  : N. Ranjith          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : 25-Aug-2014  Created Intial Version              
/******************************************************************************/          
BEGIN          
--SET NOCOUNT ON           
 -- Local variables to hold the intermediate results          
 DECLARE @ErrorMessage varchar(3000)          

if @IntMode = 1
begin

SELECT * FROM rvlfStudentVehicleAssignment v           
  WHERE v.StudentmasterId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcStudentIDs,','))

End
Else
Begin      
if @IntAssignUnassign =1      
/****Assign Student***/      
begin      
 BEGIN TRAN MessageOutTransaction          
 BEGIN TRY              
  DELETE FROM rvlfStudentVehicleAssignment WHERE StudentmasterId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcStudentIDs,','))          
          
  INSERT INTO rvlfStudentVehicleAssignment(StudentmasterId, VehicleId, AssignBy, AssignedDate)          
  (SELECT v.StudentmasterId, @intVehicleId, @bigAssignedBy, @dtAssignedDate FROM rvlfStudentMaster v           
  WHERE ((@bigOrganizationID IS NULL OR @bigOrganizationID = '') OR v.OrganizationId = @bigOrganizationID)          
  AND v.StudentmasterId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcStudentIDs,',')))                 
  COMMIT TRAN          
 END TRY          
 BEGIN CATCH          
 ROLLBACK TRAN           
  SET @ErrorMessage = 'An Error occured during assigning student to vehicle : ' +ERROR_MESSAGE()          
 RAISERROR( @ErrorMessage,16,1)          
 END CATCH          
       
 End      
 else      
 /****Unassign Student***/      
 Begin      
 BEGIN TRAN MessageOutTransaction        
 BEGIN TRY        
  DELETE FROM rvlfStudentVehicleAssignment WHERE VehicleId = @intVehicleId and StudentmasterId in         
  (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcStudentIDs,','))         
  COMMIT TRAN        
 END TRY        
 BEGIN CATCH        
 ROLLBACK TRAN         
  SET @ErrorMessage = 'An Error occured during unassigning student to vehicle : ' +ERROR_MESSAGE()        
 RAISERROR( @ErrorMessage,16,1)        
 END CATCH       
 end      
end       
SET NOCOUNT OFF          
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignUserGroup]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_AssignUserGroup]  
 @intUserGroupId int = null,  
 @bigAssignedBy bigint = null,  
 @dtAssignedDate Datetime = null,  
 @bigOrganizationID bigint = null,  
 @vcUserIDs varchar(250) = null  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_AssignUserGroup  
-- Description : To assign users to the user group in bulk manner  
-- Author  : L. Kumuthini  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 11-Sep-2009  Created Intial Version   
--    : 29-Dec-2010 Restricted the deleteted users  
--    : 19-May-2011 Restricted the hidden users  
--    : 17-Feb-2012 Ranjith Hidden user condition removed for assign
/******************************************************************************/  
BEGIN  
--SET NOCOUNT ON   
 -- Local variables to hold the intermediate results  
 DECLARE @ErrorMessage varchar(3000)  
   
 BEGIN TRAN MessageOutTransaction  
 BEGIN TRY  
   
     DELETE FROM rvlfUserGroupAssignment WHERE UserId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcUserIDs,','))  
  
  INSERT INTO rvlfUserGroupAssignment(UserId, UserGroupId, AssignedBy, AssignedDate)  
    (SELECT v.UserId, @intUserGroupId, @bigAssignedBy, @dtAssignedDate FROM rvlfUser v   
    WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)  
     AND v.UserId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcUserIDs,','))  
     AND V.ISDELETE=0 )  --AND V.IsHidden <> 1
     
 COMMIT TRAN  
 END TRY  
 BEGIN CATCH  
  ROLLBACK TRAN   
  SET @ErrorMessage = 'An Error occured during assigning users to User Groups : ' +ERROR_MESSAGE()  
  RAISERROR( @ErrorMessage,16,1)  
 END CATCH  
SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignUserPriviledges]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_AssignUserPriviledges]
	@intUserGroupId int = null,
	@vcOprTypeIds varchar(250) = null
AS
/******************************************************************************/
--	Name		:	rvlf_sp_AssignUserPriviledges
--	Description	:	To assign users privileges to the User Group
--	Author		:	L. Kumuthini
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	22-Sep-2009		Created Intial Version 
/******************************************************************************/
BEGIN
--SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
	
	BEGIN TRAN MessageOutTransaction
	BEGIN TRY
	
	    DELETE FROM rvlfUserPriviledges WHERE OperationTypeId NOT IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcOprTypeIds,','))
	    AND UserGroupId = @intUserGroupId

        INSERT INTO rvlfUserPriviledges(UserGroupId,ModuleID,OperationTypeId) 
             (SELECT @intUserGroupId, OT.ModuleID, OT.OperationTypeId FROM rvlfOperationType OT
              WHERE OT.OperationTypeId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcOprTypeIds,',')) AND 
              OT.OperationTypeId NOT IN (SELECT OperationTypeId FROM rvlfUserPriviledges WHERE UserGroupId = @intUserGroupId)
             )
		 
	COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during assigning priviledges to User Groups : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignUsers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_AssignUsers]  
 @bigFleetID bigint = null,  
 @bigAssignedBy bigint = null,  
 @dtAssignedDate Datetime = null,  
 @bigOrganizationID bigint = null,  
 @vcUserIDs varchar(250) = null  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_AssignUsers  
-- Description : To assign vehicles to the fleet in bulk manner  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 24-Jul-2009 MJJC Created Intial Version   
--    : 19-May-2011 TSK  Blocked the hidden users   
/******************************************************************************/  
BEGIN  
--SET NOCOUNT ON   
 -- Local variables to hold the intermediate results  
 DECLARE @ErrorMessage varchar(3000)  
   
 BEGIN TRAN MessageOutTransaction  
 BEGIN TRY  
  
  INSERT INTO rvlfFleetUsers(FleetId, UserId , AssignedBy, AssignedDate)  
    (SELECT @bigFleetID, v.UserId, @bigAssignedBy, @dtAssignedDate FROM rvlfUser v   
    WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND V.IsHidden <> 1   
     AND v.UserId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcUserIDs,',')))  

 UPDATE rvlfUserPreferences SET DefaultFleetId = @bigFleetID WHERE UserId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcUserIDs,',')) and DefaultFleetId is null
     
 COMMIT TRAN  
 END TRY  
 BEGIN CATCH  
  ROLLBACK TRAN   
  SET @ErrorMessage = 'An Error occured during assigning users to the fleet : ' +ERROR_MESSAGE()  
  RAISERROR( @ErrorMessage,16,1)  
 END CATCH  
SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignVehicleMaintenancePlan]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
      
Create Procedure [dbo].[rvlf_sp_AssignVehicleMaintenancePlan]        
 @bigOrganizationID bigint = null,        
 @bigPlanId bigint = null,        
  @tblVehiclePlanDetails XML = NULL,           
    --@tblVehiclePlanDetails AS MaintenancePlanAssignment READONLY,        
    @bigAssignedBy bigint = null,        
 @dtAssignedDate Datetime = null        
AS        
/******************************************************************************/        
-- Name  : rvlf_sp_AssignVehicleMaintenancePlan         
-- Description : To assign vehicles to the maintenance plan in bulk manner        
-- Author  : Kumuthini. L        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--    : 14-Jul-2010 Kumuthini. L Created Intial Version         
--    :   22-Sep-2010 Kumuthini. L    Getting vehicle assignment details         
--    :  for each vehicle & updating in DB in bulk manner        
/******************************************************************************/        
BEGIN        
--SET NOCOUNT ON         
 -- Local variables to hold the intermediate results        
 DECLARE @ErrorMessage varchar(3000)        
 DECLARE @docHandle int                    
  DECLARE  @tblVehiclePlanDetailsXML TABLE (VehicleId bigint,VehicleDescription Varchar(Max),IsActive Bit,EngineHrsSIValue Bigint, OdometerOpeningValue Bigint,OdometerSIValue Bigint,TimeBasedSIValue DATETIME NULL )      
        
 BEGIN TRAN AssignVehiclePlanTransaction        
 BEGIN TRY        
         
   IF @tblVehiclePlanDetails IS NOT NULL                       
	 BEGIN                                          
		  EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblVehiclePlanDetails                                                   
		  INSERT INTO @tblVehiclePlanDetailsXML                                                                
		  SELECT * FROM OPENXML(@docHandle, '/DocumentElement/VehicleMaintenancePlan')                         
		  WITH                           
		  (                                   
			  VehicleId bigint 'VehicleId'                                    
			  ,VehicleDescription  Varchar(Max)  'VehicleDescription'                                                              
			  ,IsActive bit  'IsActive'                                
			  ,OdometerOpeningValue bigint 'OdometerOpeningValue'                    
			  ,EngineHrsSIValue bigint 'EngineHrsSIValue'          
			  ,OdometerSIValue bigint 'OdometerSIValue'                    
			  ,TimeBasedSIValue DATETIME  'TimeBasedSIValue'                    
		  )                    
                      
		  declare @tblVehiclePlanDetails1 As MaintenancePlanAssignment                    
		  insert into  @tblVehiclePlanDetails1--( VehicleId,VehicleDescription,IsActive,OdometerOpeningValue,EngineHrsSIValue,OdometerSIValue,TimeBasedSIValue)                        
		  select * from @tblVehiclePlanDetailsXML                        
	 END       
         
  -- Get the User Preferences whether miles or kilometer based on the user id        
  DECLARE @ConversionFactor numeric (10,2) = 1.0        
            
  SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END        
  FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz        
  ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigAssignedBy        
          
  DECLARE @IsRecurring BIT = 0        
  SELECT @IsRecurring = RecurringService FROM rvlfMaintenancePlan WHERE PlanId = @bigPlanId        
          
  -- Insert the vehicle plan assignment details into the Vehicle Plan Assignment Table        
  INSERT INTO rvlfVehiclePlanAssignment (VehicleId, PlanId ,IsActive, EngineHrsStartValue, OdometerReadingOpeningValue, OdometerReadingStartValue, TimeBasedStartValue, AssignedStatus, AssignedBy, AssignedDateTime)        
    (SELECT VehicleId, @bigPlanId, IsActive, CASE WHEN @IsRecurring = 1 THEN EngineHrsSIValue ELSE NULL END AS EngineHrsSIValue,         
     ((CASE WHEN (OdometerOpeningValue / @ConversionFactor) > 0 THEN ROUND((OdometerOpeningValue / @ConversionFactor), 0) ELSE (OdometerOpeningValue / @ConversionFactor) END)) AS OdometerOpeningValue,         
     CASE WHEN @IsRecurring = 1 THEN ((CASE WHEN (OdometerSIValue / @ConversionFactor) > 0 THEN ROUND((OdometerSIValue / @ConversionFactor), 0) ELSE (OdometerSIValue / @ConversionFactor) END)) ELSE NULL END AS OdometerSIValue,         
     (CASE WHEN @IsRecurring = 1 THEN (CASE WHEN TimeBasedSIValue = 0 THEN NULL ELSE TimeBasedSIValue END) ELSE NULL END )AS TimeBasedSIValue, 1, @bigAssignedBy, @dtAssignedDate                   
     --CASE WHEN @IsRecurring = 1 THEN TimeBasedSIValue ELSE NULL END AS TimeBasedSIValue, 1, @bigAssignedBy, @dtAssignedDate         
     FROM @tblVehiclePlanDetails1)         
          
     -- Insert the vehicles with the readings in the Current Readings Table if the vehicles are not in the Current Readings Table        
  INSERT INTO rvlfVehicleCurrentReadings (VehicleId, CurrentEngineHours, CurrentOdometerReading)         
   ( SELECT t.VehicleId,0 AS EngineHrsOpeningValue,         
      (CASE WHEN t.OdometerOpeningValue IS NULL THEN 0 ELSE ((CASE WHEN (t.OdometerOpeningValue / @ConversionFactor) > 0 THEN ROUND((t.OdometerOpeningValue / @ConversionFactor), 0) ELSE (t.OdometerOpeningValue / @ConversionFactor) END)) END) AS OdometerOpeningValue        
     FROM @tblVehiclePlanDetails1 t        
     INNER JOIN rvlfVehicle v ON v.VehicleId = t.VehicleId        
     WHERE t.VehicleId NOT IN (SELECT cr.VehicleId FROM rvlfVehicleCurrentReadings cr)        
   )           
          
  -- Calculate the Due On values when assigning the plan to the vehicle        
	--declare @val int=0
 -- 	select @val=isnull(RunningSerial,0) from rvlfVehicleMaintenanceService where ServiceDetailsId in (select Max(ServiceDetailsId) from rvlfVehicleMaintenanceService)
	--if(@val=8888)
	--	begin
	--		set @val=1
	--	end
	--else
	--	begin
	--		set @val= @val + 1
	--	end

  INSERT INTO rvlfVehicleMaintenanceService(VehiclePlanId, PlanDetailsId, ServiceType, Frequency, StartDate, DueOn, DueOnDate, Status, CreatedBy, CreatedDateTime, StatusChangeOn, NearingPercentage, IsNearing, RunningSerial)        
  (SELECT vp.VehiclePlanId, mp.PlanDetailsId, mp.ServiceType, mp.Frequency,         
  CASE WHEN mp.ServiceType = 2 THEN (CASE WHEN vpd.TimeBasedSIValue IS NULL OR @IsRecurring = 0 THEN @dtAssignedDate ELSE vpd.TimeBasedSIValue END) ELSE NULL END AS StartDate,        
  CASE WHEN mp.ServiceType = 0 OR mp.ServiceType =3 THEN (vpd.EngineHrsSIValue + (CASE WHEN @IsRecurring = 1 THEN mp.ServiceInterval ELSE 0 END))        
    WHEN mp.ServiceType = 1 THEN (((CASE WHEN (vpd.OdometerSIValue / @ConversionFactor) > 0 THEN ROUND((vpd.OdometerSIValue / @ConversionFactor), 0) ELSE (vpd.OdometerSIValue / @ConversionFactor) END)) + (CASE WHEN @IsRecurring = 1 THEN mp.ServiceInterval
  
    
      
 ELSE 0 END)) ELSE 0 END AS DueOn,        
  CASE WHEN mp.ServiceType = 2 THEN (CASE WHEN @IsRecurring = 0 THEN vpd.TimeBasedSIValue ELSE        
   (CASE WHEN mp.Frequency = 0 THEN DATEADD(D, mp.ServiceInterval, (CASE WHEN vpd.TimeBasedSIValue IS NULL THEN @dtAssignedDate ELSE vpd.TimeBasedSIValue END))         
     WHEN mp.Frequency = 1 THEN DATEADD(M, mp.ServiceInterval, (CASE WHEN vpd.TimeBasedSIValue IS NULL THEN @dtAssignedDate ELSE vpd.TimeBasedSIValue END))         
     WHEN mp.Frequency = 2 THEN DATEADD(YEAR, mp.ServiceInterval, (CASE WHEN vpd.TimeBasedSIValue IS NULL THEN @dtAssignedDate ELSE vpd.TimeBasedSIValue END)) ELSE NULL END) END)        
   ELSE NULL END AS DueOnDate, 0 AS Status, @bigAssignedBy AS CreatedBy, @dtAssignedDate AS CreatedDateTime,        
  CASE WHEN mp.ServiceType = 0 OR mp.ServiceType =3  THEN vpd.EngineHrsSIValue        
       WHEN mp.ServiceType = 1 THEN (CASE WHEN (vpd.OdometerSIValue / @ConversionFactor) > 0 THEN ROUND((vpd.OdometerSIValue / @ConversionFactor), 0) ELSE (vpd.OdometerSIValue / @ConversionFactor) END) ELSE 0 END AS StatusChangeOn, 0, 0 ,
	   (select isnull(RunningSerial,0) from rvlfVehicleMaintenanceService where ServiceDetailsId in (select Max(ServiceDetailsId) from rvlfVehicleMaintenanceService)) + 1

  FROM rvlfMaintenancePlanDetails mp        
  INNER JOIN rvlfVehiclePlanAssignment vp on vp.PlanId = mp.PlanId        
  INNER JOIN rvlfVehicleCurrentReadings cr on cr.VehicleId = vp.VehicleId        
  INNER JOIN @tblVehiclePlanDetails1 vpd on vpd.VehicleId = vp.VehicleId        
  LEFT OUTER JOIN rvlfVehicleMaintenanceService ms on ms.VehiclePlanId = vp.VehiclePlanId        
  WHERE mp.PlanId = @bigPlanId AND ms.VehiclePlanId IS NULL)        
          
  -- Calculate Nearing Percentage for the plan        
  CREATE TABLE #temp(ServiceDetailsId bigint, Nearing int)         
        
  INSERT INTO #temp(ServiceDetailsId, Nearing)        
  SELECT vm.ServiceDetailsId,         
  ((CASE WHEN vm.ServiceType = 0  OR vm.ServiceType =3 THEN (CASE WHEN mp.RecurringService = 0 THEN ((CAST(CAST(cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0)AS FLOAT) / 3600 as DEcimal(18,2))) * 100)         
     ELSE (CASE WHEN ((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0)) - vm.StatusChangeOn) >= 0 THEN ((CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0)) as Float) / 3600 as Decimal(18,2)) - vm.StatusChangeOn) * 100) ELSE
 0 END) END)         
      WHEN vm.ServiceType = 1 THEN (CASE WHEN mp.RecurringService = 0 THEN (cr.CurrentOdometerReading * 100)        
     ELSE (CASE WHEN (cr.CurrentOdometerReading - vm.StatusChangeOn) >= 0 THEN ((cr.CurrentOdometerReading - vm.StatusChangeOn) * 100) ELSE 0 END) END)         
      WHEN vm.ServiceType = 2 THEN (CASE WHEN (CONVERT(DATE, vm.DueOnDate) = CONVERT(DATE, GETUTCDATE()) AND mp.RecurringService = 0) THEN 100 ELSE (CASE WHEN DATEDIFF(D, vm.StartDate, GETUTCDATE()) > 0 THEN DATEDIFF(D, vm.StartDate, GETUTCDATE()) ELSE 0 
  
    
      
END) * 100 END)        
    END) / (CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 1 OR vm.ServiceType =3 THEN (CASE WHEN mp.RecurringService = 0 THEN vm.DueOn ELSE pd.ServiceInterval END) ELSE (        
       CASE WHEN mp.RecurringService = 1 THEN        
        (CASE WHEN vm.Frequency = 0 THEN pd.ServiceInterval        
          WHEN vm.Frequency = 1 THEN (pd.ServiceInterval * 30)        
          WHEN vm.Frequency = 2 THEN (pd.ServiceInterval * 365) END)        
           ELSE (CASE WHEN CONVERT(DATE, vm.DueOnDate) = CONVERT(DATE, GETUTCDATE()) THEN 1 ELSE DATEDIFF(D, vm.StartDate, vm.DueOnDate) END) END        
         )         
     END)         
  ) AS Nearing        
  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 = cr.VehicleId        
  WHERE mp.OrganizationId = @bigOrganizationID AND vm.Status = 0 AND vp.IsActive = 1         
  AND vp.AssignedStatus = 1 AND vp.PlanId = @bigPlanId        
          
  -- Update the calculated nearing percentage        
  UPDATE ms SET NearingPercentage = t.Nearing, OverdueDate = (CASE WHEN t.Nearing >= 100 THEN GETUTCDATE() ELSE OverdueDate END),        
  EngineHrsOnDue = (CASE WHEN t.Nearing >= 100 THEN (CAST(CAST(cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0)AS FLOAT) / 3600 as DEcimal(18,2))) ELSE EngineHrsOnDue END),        
  OdometerReadingOnDue = (CASE WHEN t.Nearing >= 100 THEN cr.CurrentOdometerReading ELSE OdometerReadingOnDue END)        
  FROM rvlfVehicleMaintenanceService ms        
  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = ms.VehiclePlanId        
  INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId        
  INNER JOIN rvlfVehicle v ON v.VehicleId = cr.VehicleId         
        INNER JOIN #temp t ON t.ServiceDetailsId = ms.ServiceDetailsId        
          
  DROP TABLE #temp        
          
  -- Update IsNearing field for the plan using the calculated nearing (%)        
  CREATE TABLE #temp1(VehiclePlanId bigint, Nearing int)         
        
  INSERT INTO #temp1(VehiclePlanId, Nearing)        
  SELECT vm.VehiclePlanId, MAX(vm.NearingPercentage) AS Nearing FROM rvlfVehicleMaintenanceService vm        
  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId        
  INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId         
  WHERE mp.OrganizationId = @bigOrganizationID AND vm.Status = 0 AND vp.IsActive = 1         
  AND vp.AssignedStatus = 1 AND vp.PlanId = @bigPlanId        
  GROUP BY vm.VehiclePlanId        
        
  UPDATE vm SET vm.IsNearing = (CASE WHEN vm.NearingPercentage = t.Nearing THEN 1 ELSE 0 END) FROM rvlfVehicleMaintenanceService vm        
  INNER JOIN #temp1 t ON t.VehiclePlanId = vm.VehiclePlanId         
  WHERE vm.Status = 0        
        
  DROP TABLE #temp1        
          
 COMMIT TRAN        
 END TRY        
 BEGIN CATCH        
  ROLLBACK TRAN         
  SET @ErrorMessage = 'An Error occured during assigning vehicles to the maintenance plan : ' + ERROR_MESSAGE()        
  RAISERROR( @ErrorMessage,16,1)        
 END CATCH        
SET NOCOUNT OFF        
END   
  
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_AssignVehicles]  
 @bigFleetID bigint = null,  
 @bigAssignedBy bigint = null,  
 @dtAssignedDate Datetime = null,  
 @bigOrganizationID bigint = null,  
 @vcVehicleIDs varchar(250) = null  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_AssignVehicles  
-- Description : To assign vehicles to the fleet in bulk manner  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 24-Jul-2009 MJJC Created Intial Version   
/******************************************************************************/  
BEGIN  
--SET NOCOUNT ON   
 -- Local variables to hold the intermediate results  
 DECLARE @ErrorMessage varchar(3000)  
   
 BEGIN TRAN MessageOutTransaction  
 BEGIN TRY  
  
  INSERT INTO rvlfFleetVehicles (FleetId, VehicleId ,IsActive,AssignedBy, AssignedDate)  
    (SELECT @bigFleetID, v.VehicleId, 1, @bigAssignedBy, @dtAssignedDate FROM rvlfVehicle v   
    WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)  
     AND v.VehicleId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcVehicleIDs,',')))  
     
 COMMIT TRAN  
 END TRY  
 BEGIN CATCH  
  ROLLBACK TRAN   
  SET @ErrorMessage = 'An Error occured during assigning vehicles to the fleet : ' +ERROR_MESSAGE()  
  RAISERROR( @ErrorMessage,16,1)  
 END CATCH  
SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AssignVendorVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_AssignVendorVehicles]      
-- @bigVendorID bigint = null,      
-- @bigAssignedBy bigint = null,      
-- @dtAssignedDate Datetime = null,      
-- @bigOrganizationID bigint = null,      
-- @vcVehicleIDs varchar(250) = null      
--AS      
--/******************************************************************************/      
---- Name  : [rvlf_sp_AssignVendorVehicles]      
---- Description : To assign vehicles to the vendor in bulk manner      
---- Author  : R.Gopal  
---- Company  : Angler Technologies      
---- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
----    : 23-Oct-2013 Created Intial Version       
--/******************************************************************************/      
--BEGIN      
----SET NOCOUNT ON       
-- -- Local variables to hold the intermediate results      
-- DECLARE @ErrorMessage varchar(3000)      
       
-- BEGIN TRAN MessageOutTransaction      
-- BEGIN TRY      
      
--  INSERT INTO rvlfVendorVehicles (VendorId, VehicleId ,IsActive,AssignedBy, AssignedDate)      
--    (SELECT @bigVendorID, v.VehicleId, 1, @bigAssignedBy, @dtAssignedDate FROM rvlfVehicle v       
--    WHERE ((@bigOrganizationID IS NULL OR @bigOrganizationID = '') OR v.OrganizationId = @bigOrganizationID)      
--     AND v.VehicleId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcVehicleIDs,',')))      
         
-- COMMIT TRAN      
-- END TRY      
-- BEGIN CATCH      
--  ROLLBACK TRAN       
--  SET @ErrorMessage = 'An Error occured during assigning vehicles to the fleet : ' +ERROR_MESSAGE()      
--  RAISERROR( @ErrorMessage,16,1)      
-- END CATCH      
--SET NOCOUNT OFF      
--END   

 @bigVendorID				bigint = null,    
 @bigAssignedBy				bigint = null,    
 @dtAssignedDate			Datetime = null,    
 @bigOrganizationID			bigint = null,    
 @vcVehicleIDs				varchar(250) = null,
 @dtContractFrom			Datetime = NULL,
 @dtContractTo				Datetime = NULL,
 @intExpNotificationType	Int = NULL,
 @intExpNotification1		Int = NULL,
 @intExpNotification2		Int = NULL,
 @intMonthlyRunningDist		Int = NULL,
 @bitIsDistanceNotify		bit = NULL,
 @intMonthlyEngineHrs		Int = NULL,
 @bitIsEngineHrsNotify		bit = NULL,
 @bitIsRenew				bit = 0,
 @vcRemarks					varchar(500) = NULL,
 @bigCreatedBy				bigint = NULL,
 @dtCreatedDateTime			Datetime = NULL,
 @Email						varchar(250)=null
AS    
/******************************************************************************/    
-- Name  : [rvlf_sp_AssignVendorVehicles]    
-- Description : To assign vehicles to the vendor in bulk manner    
-- Author  : R.Gopal
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 23-Oct-2013 Created Intial Version     
/******************************************************************************/    
BEGIN    
--SET NOCOUNT ON     
 -- Local variables to hold the intermediate results    
 DECLARE @ErrorMessage varchar(3000)    
     
 BEGIN TRAN MessageOutTransaction    
 BEGIN TRY    
    
  DECLARE @tblVehicleIds TABLE(VehicleID bigint)

  INSERT INTO @tblVehicleIds
  SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcVehicleIDs,',')

  DECLARE @MinVehicleId bigint
  SELECT @MinVehicleId = MIN(VehicleID) FROM @tblVehicleIds

  WHILE @MinVehicleId IS NOT NULL
  BEGIN

  INSERT INTO rvlfVendorVehicles (VendorId, VehicleId ,IsActive,AssignedBy, AssignedDate)    
  SELECT @bigVendorID, v.VehicleId, 1, @bigAssignedBy, @dtAssignedDate 
  FROM	 rvlfVehicle v     
  WHERE  ((@bigOrganizationID IS NULL OR @bigOrganizationID = '') OR v.OrganizationId = @bigOrganizationID)    
  AND	 v.VehicleId = @MinVehicleId


  --Added for Lease Management Settings 25-02-2016
  INSERT INTO rvlfVendorVehicleSettings(VendorVehicleAssignId, ContractFrom, ContractTo, ExpNotificationType, ExpNotification1, ExpNotification2,
										MonthlyRunningDistance, IsDistanceNotify, MonthlyEngineHrs, IsEngineHrsNotify, IsRenew, Remarks, 
										CreatedBy, CreatedDateTime,TokenID,Email)
  SELECT IDENT_CURRENT('rvlfVendorVehicles'), @dtContractFrom, @dtContractTo, @intExpNotificationType, @intExpNotification1, @intExpNotification2,
  @intMonthlyRunningDist, @bitIsDistanceNotify, @intMonthlyEngineHrs, @bitIsEngineHrsNotify, @bitIsRenew, @vcRemarks, @bigCreatedBy, @dtCreatedDateTime,newid(),@Email


  INSERT INTO rvlfVendorVehicleHistory(VendorVehicleAssignId, ContractFrom, ContractTo, ExpNotificationType, ExpNotification1, ExpNotification2,
										MonthlyRunningDistance, IsDistanceNotify, MonthlyEngineHrs, IsEngineHrsNotify, IsRenew, Remarks, 
										CreatedBy, CreatedDateTime) 
  SELECT IDENT_CURRENT('rvlfVendorVehicles'), @dtContractFrom, @dtContractTo, @intExpNotificationType, @intExpNotification1, @intExpNotification2,
  @intMonthlyRunningDist, @bitIsDistanceNotify, @intMonthlyEngineHrs, @bitIsEngineHrsNotify, @bitIsRenew, @vcRemarks, @bigCreatedBy, @dtCreatedDateTime  
  
  SELECT @MinVehicleId = MIN(VehicleID) FROM @tblVehicleIds WHERE VehicleID > @MinVehicleId

  END
           
 COMMIT TRAN    
 END TRY    
 BEGIN CATCH    
  ROLLBACK TRAN     
  SET @ErrorMessage = 'An Error occured during assigning vehicles to the fleet : ' + ERROR_MESSAGE()    
  RAISERROR( @ErrorMessage,16,1)    
 END CATCH    
SET NOCOUNT OFF    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AuthenticateUsers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_AuthenticateUsers]    
 @vcUserName varchar(50),    
 @vcPassword varchar(100),    
 @cOrganizationCode char(3)= null,    
 @vcIPAddress varchar(25) = null,    
 @dtLoginDateTime datetime = null,  
 @GUID uniqueidentifier = null   
AS    
/******************************************************************************/    
-- Name  : rvlf_sp_AuthenticateUsers    
-- Description : To authenticate the users    
--    :   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin    
-- Author  : M. Jebamalai Jaya Chitra.    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 06-Jul-2009 MJJC Created Intial Version     
--    : 26-Nov-2009 MJJC Organization based restriction impl.    
--              :   12-Dec-2009 Kumu    Locking User     
--              :   14-Dec-2009 Kumu    Locking IP Address     
--    : 21-Feb-2010 MJJC Commented the retrieval of last login and instead returned the soltuion details    
--    : 29-Dec-2010 VN Restricted the deleteted users    
--    : 03-Jan-2011 VN update the date if the organization is 30 or 55    
/******************************************************************************/    
BEGIN    
 SET NOCOUNT ON     
  DECLARE @unSuccessfulLogins int    
      
  DECLARE @bigUserID bigint = 0     
  DECLARE @vcEmail varchar(200) = ''    
  DECLARE @vcdisplayName varchar(100) = ''    
  DECLARE @intUserGroupAssigned int = 0    
      
  SELECT @bigUserID = UserID, @vcEmail = Email, @vcdisplayName = DisplayName FROM rvlfUser WHERE UserName = @vcUserName     
  AND ISDELETE=0 AND(@cOrganizationCode is NULL OR @cOrganizationCode='' OR  OrganizationId =     
   (SELECT OrganizationId FROM rvlfOrganization WHERE OrganizationCode = @cOrganizationCode))    
  -- AND [Password] = @vcPassword  COLLATE SQL_Latin1_General_CP1_CS_AS    
      
  DECLARE @bigOrganizationId AS BIGINT    
  DECLARE @dtOrgExpiryDate DateTime    
  DECLARE @dtOrgPurchasedDate DateTime    
  DECLARE @bitLockUser BIT    
  DECLARE @intLockUserTries INT    
  DECLARE @bitLockIP BIT    
  DECLARE @intIPLockDuration INT    
  DECLARE @intIPTries INT    
      
  SELECT @dtOrgExpiryDate = ExpiresOn, @bitLockUser = LockUser, @intLockUserTries = LockUserTries, @bitLockIP = LockIP,             
		 @intIPLockDuration = IPLockDuration, @intIPTries = IPTries, @bigOrganizationId = OrganizationId             
  FROM   rvlfOrganization WHERE OrganizationCode = @cOrganizationCode            
  
  Update rvlfUserLogin SET LogOffDateTime=DATEADD(SECOND,-1,@dtLoginDateTime) WHERE UserId=@bigUserID and LogOffDateTime IS NULL        
  
  IF(@bigOrganizationId <> 1)    
  BEGIN    
      
   SELECT @dtOrgPurchasedDate = PurchasedOn FROM rvlfOrganizationPackage WHERE OrganizationID = @bigOrganizationId AND IsActive = 1    
      
   IF SYSUTCDATETIME() < @dtOrgPurchasedDate    
    BEGIN    
     INSERT INTO rvlfUserLogin     
     (UserID, OrgId, LoginDateTime, IP, LoginStatus ) VALUES (@bigUserID, @bigOrganizationId, @dtLoginDateTime,@vcIPAddress , 1)    
     raiserror('Your license is not yet started',15,0)    
     RETURN    
    END    
       
   IF SYSUTCDATETIME() > @dtOrgExpiryDate    
    BEGIN    
     INSERT INTO rvlfUserLogin     
     (UserID, OrgId, LoginDateTime, IP, LoginStatus ) VALUES (@bigUserID, @bigOrganizationId, @dtLoginDateTime,@vcIPAddress , 1)    
     raiserror('Your account has been expired',15,0)    
     RETURN    
    END    
  END    
      
  SET @intUserGroupAssigned = (SELECT COUNT(*) FROM rvlfUserGroupAssignment WHERE UserId = @bigUserID)    
       
  IF (@bitLockIP = 1)    
  BEGIN    
          
   SELECT @unSuccessfulLogins = COUNT(*) FROM rvlfUserLogin UL    
   WHERE UL.OrgId = @bigOrganizationId AND UL.UserId = 0 AND UL.IP = @vcIPAddress AND   
   UL.LoginDateTime BETWEEN DATEADD(HH,-@intIPLockDuration,@dtLoginDateTime) AND @dtLoginDateTime     
      
  END    
      
  IF (@bitLockIP = 1 AND @vcUserName <> 'Administrator' AND @unSuccessfulLogins >= @intIPTries) -- AND @bigUserID IS NULL    
     BEGIN    
   DECLARE @vcerrorMessage varchar(150)    
   SELECT @vcerrorMessage = dbo.rvlf_fn_GetTimeFromSeconds( (@intIPLockDuration * 3600) - DATEDIFF(ss,     
     (    
      SELECT MAX(UL.LoginDateTime) FROM rvlfUserLogin UL    
      WHERE UL.UserId = 0  AND UL.OrgId = @bigOrganizationId AND UL.IP = @vcIPAddress AND   
      UL.LoginDateTime BETWEEN DATEADD(HH,-@intIPLockDuration,@dtLoginDateTime) AND @dtLoginDateTime    
     ),@dtLoginDateTime) )    
   SET @vcerrorMessage = 'This IP is blocked. Try after '+ @vcerrorMessage    
   raiserror (@vcerrorMessage,16,1)    
   return    
  END    
  ELSE IF EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] = @vcPassword  COLLATE SQL_Latin1_General_CP1_CS_AS and IsLocked = 0 and IsActive = 1 AND ISDELETE=0    
    AND(@cOrganizationCode is NULL OR @cOrganizationCode='' OR  OrganizationId = (SELECT OrganizationId FROM rvlfOrganization WHERE OrganizationCode = @cOrganizationCode)))    
  BEGIN    
   IF (@intUserGroupAssigned > 0 OR @bigUserID = 1)    
   BEGIN    
       DECLARE @IsFirstLogin AS BIT = 0    
           
       SET @IsFirstLogin = (SELECT IsPwdChanged FROM rvlfuser WHERE UserId = @bigUserID)    
           
    INSERT INTO rvlfUserLogin     
    (UserID, OrgId, LoginDateTime, IP, LoginStatus ) VALUES (@bigUserID, @bigOrganizationId, @dtLoginDateTime,@vcIPAddress , 1)    
        
        SELECT *,(case when isnull(up.DefaultDateFormat,0)=0 then Convert(varchar,getdate(),107) else Convert(varchar,getdate(),up.DefaultDateFormat) end) as UserDateFormat, @IsFirstLogin AS 'IsFirstLogin',
        CASE WHEN og.OrgLatitude IS NULL THEN '23.805450,78.486328,4'ELSE CAST(og.OrgLatitude AS VARCHAR(10)) + ','+ CAST(og.OrgLongitude AS VARCHAR(10))+','+ CAST(og.OrgZoomlevel AS VARCHAR(2)) END AS OrgCoords
        FROM rvlfUser t1       
     INNER JOIN rvlfUserLogin t2 ON t1.UserId = t2.UserId       
     INNER JOIN rvlfOrganization og ON t1.OrganizationId = og.OrganizationId  
     INNER JOIN rvlfUserPreferences up on t1.UserId=up.UserId          
    WHERE t1.UserName = @vcUserName AND t1.[Password] = @vcPassword AND t2.LoginId = @@IDENTITY      
         
    -- Commented the retrieval of last login and instead returned the soltuion details    
        
    --SELECT TOP 1 * FROM rvlfUserLogin t2 INNER JOIN rvlfUser t1 ON t2.UserId= t1.UserId     
    --INNER JOIN rvlfOrganization g ON t1.OrganizationId = g.OrganizationId     
    -- WHERE LoginId < @@IDENTITY AND LoginStatus = 1 AND t2.UserId = @bigUserID ORDER BY     
    -- t2.LoginDateTime DESC    
     SELECT g.SolutionId, g.OrganizationId, s.SolutionId, s.ResourceFileName FROM rvlfOrganizationSolution g     
      INNER JOIN rvlfTrinetraSolutions s ON g.SolutionId = s.SolutionId    
      WHERE g.OrganizationId = @bigOrganizationId    
         
     SELECT * FROM rvlfUserGroup g    
     INNER JOIN rvlfUserGroupAssignment ga On g.UserGroupId = ga.UserGroupId    
     WHERE ga.UserId  = @bigUserID    
         
          
     SELECT * FROM rvlfUserGroupSecurity s    
     INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId    
     WHERE ga.UserId = @bigUserID
        
   END    
   ELSE    
   BEGIN    
    raiserror('Your account does not have privilege', 16,1)    
   END    
  END    
  ELSE    
  BEGIN    
      IF EXISTS (SELECT UserID FROM rvlfUser WHERE (UserName = @vcUserName AND [Password] != @vcPassword  COLLATE SQL_Latin1_General_CP1_CS_AS) and IsLocked = 1)    
   BEGIN    
    raiserror('Invalid Credentials', 16,1)    
   END    
   ELSE IF EXISTS (SELECT UserID FROM rvlfUser WHERE (UserName = @vcUserName AND [Password] = @vcPassword  COLLATE SQL_Latin1_General_CP1_CS_AS) and IsLocked = 1)    
   BEGIN    
    raiserror('Your account is locked', 16,1)    
   END    
   ELSE IF EXISTS (SELECT UserID FROM rvlfUser WHERE (UserName = @vcUserName AND [Password] = @vcPassword  COLLATE SQL_Latin1_General_CP1_CS_AS) and IsActive = 0)    
   BEGIN    
    raiserror('Your account is Inactivated', 16,1)    
   END    
   ELSE IF EXISTS (SELECT UserID FROM rvlfUser WHERE (UserName = @vcUserName AND [Password] = @vcPassword  COLLATE SQL_Latin1_General_CP1_CS_AS) and IsActive = 1 AND ISDELETE=1  AND (OrganizationId =     
   (SELECT OrganizationId FROM rvlfOrganization WHERE OrganizationCode = @cOrganizationCode)))    
   BEGIN    
    raiserror('Your account is inaccessible. Kindly contact your administrator.', 16,1)    
   END    
   ELSE IF (@intUserGroupAssigned = 0 AND @bigUserID > 0)    
   BEGIN    
    raiserror('Your account does not have privilege', 16,1)    
   END    
   ELSE    
   BEGIN    
    INSERT INTO rvlfUserLogin (UserID, OrgId, LoginDateTime, IP, LoginStatus )     
    VALUES (ISNULL(@bigUserID,0), ISNULL(@bigOrganizationId,0), @dtLoginDateTime,@vcIPAddress , 0)    
        
    IF @bigUserID IS NOT NULL --AND @vcUserName <> 'Administrator'    
    BEGIN    
            
        DECLARE @dtLockedDateTime AS DATETIME    
            
        SELECT @dtLockedDateTime = LockedDateTime FROM rvlfuser WHERE UserId = @bigUserID    
            
     SELECT @unSuccessfulLogins = COUNT(*) FROM rvlfUserLogin     
      WHERE (@dtLockedDateTime IS NULL OR LoginDateTime > @dtLockedDateTime) AND UserId = @bigUserID    
      AND LoginStatus = 0 AND @bigUserID > 0    
       
	   select @intLockUserTries=isnull(ug.LockUserTries,@intLockUserTries) from rvlfUserGroup ug inner join rvlfUserGroupAssignment uga on ug.UserGroupId=uga.UserGroupId where uga.UserId=@bigUserID

     IF (@bitLockUser = 1 AND @unSuccessfulLogins > @intLockUserTries)    
     BEGIN    
         IF @vcUserName <> 'Administrator'    
         BEGIN    
       UPDATE rvlfUser SET IsLocked = 1, LockedDateTime=@dtLoginDateTime WHERE UserId = @bigUserID    
       raiserror('Your account is locked', 16,1)    
       RETURN     
      END    
      ELSE    
      BEGIN    
          DECLARE @vcMsg AS Varchar(210) = ''    
          SET @vcMsg = 'Invalid Credentials'     
          IF(@vcEmail IS NOT NULL AND @vcEmail <> '')    
          BEGIN    
        SET @vcMsg = @vcMsg + ';'+ @vcEmail + ';' + @vcdisplayName    
          END    
       raiserror(@vcMsg, 16,1)    
      END    
     END    
     ELSE    
      raiserror('Invalid Credentials', 16,1)    
    END    
    ELSE     
    BEGIN    
     raiserror('Invalid Credentials', 16,1)    
    END    
   END    
  END      
      
  ----Included By Jeyanthi on 23-Sep-2010 for updating Demo Organization Data    
  --If(@bigOrganizationId =30 OR @bigOrganizationId =55) --29- Pilot Server & 30-Dedicated Server & defense organization    
  -- BEGIN    
  --  IF(NOT EXISTS (SELECT TOP 10 BoxId  FROM rvlfMsgInHst WHERE BoxId IN(SELECT BoxId FROM rvlfBoxId WHERE OrganizationId =30) AND CONVERT(DATE,OriginDateTime)=CONVERT(DATE,DATEADD(D,-1,GETUTCDATE()))))    
  --   BEGIN    
  --    Exec rvlf_sp_UpdateDateForDemo @bigOrganizationId    
  --   END    
         
  --  IF(NOT EXISTS (SELECT TOP 10 BoxId  FROM rvlfMsgInHst WHERE BoxId IN(SELECT BoxId  FROM rvlfBoxId WHERE OrganizationId =55) AND CONVERT(DATE,OriginDateTime)=CONVERT(DATE,DATEADD(D,-1,GETUTCDATE())) ORDER BY BoxId DESC ))    
  --   BEGIN    
  --    Exec rvlf_sp_UpdateDateForDemo @bigOrganizationId    
  --   END        
  -- END    
  ----End    
      
 SET NOCOUNT OFF    
END    
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AuthenticateUsers_k]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_AuthenticateUsers_k]    
 @vcUserName varchar(50),    
 @vcPassword varchar(100),    
 @cOrganizationCode char(3)= null,    
 @vcIPAddress varchar(25) = null,    
 @dtLoginDateTime datetime = null,  
 @GUID uniqueidentifier = null   
AS    
/******************************************************************************/    
-- Name  : rvlf_sp_AuthenticateUsers    
-- Description : To authenticate the users    
--    :   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin    
-- Author  : M. Jebamalai Jaya Chitra.    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 06-Jul-2009 MJJC Created Intial Version     
--    : 26-Nov-2009 MJJC Organization based restriction impl.    
--              :   12-Dec-2009 Kumu    Locking User     
--              :   14-Dec-2009 Kumu    Locking IP Address     
--    : 21-Feb-2010 MJJC Commented the retrieval of last login and instead returned the soltuion details    
--    : 29-Dec-2010 VN Restricted the deleteted users    
--    : 03-Jan-2011 VN update the date if the organization is 30 or 55    
/******************************************************************************/    
BEGIN    
 SET NOCOUNT ON     
  DECLARE @unSuccessfulLogins int    
      
  DECLARE @bigUserID bigint = 0     
  DECLARE @vcEmail varchar(200) = ''    
  DECLARE @vcdisplayName varchar(100) = ''    
  DECLARE @intUserGroupAssigned int = 0    
      
  SELECT @bigUserID = UserID, @vcEmail = Email, @vcdisplayName = DisplayName FROM rvlfUser WHERE UserName = @vcUserName     
  AND ISDELETE=0 AND(@cOrganizationCode is NULL OR @cOrganizationCode='' OR  OrganizationId =     
   (SELECT OrganizationId FROM rvlfOrganization WHERE OrganizationCode = @cOrganizationCode))    
  -- AND [Password] = @vcPassword  COLLATE SQL_Latin1_General_CP1_CS_AS    
      
  DECLARE @bigOrganizationId AS BIGINT    
  DECLARE @dtOrgExpiryDate DateTime    
  DECLARE @dtOrgPurchasedDate DateTime    
  DECLARE @bitLockUser BIT    
  DECLARE @intLockUserTries INT    
  DECLARE @bitLockIP BIT    
  DECLARE @intIPLockDuration INT    
  DECLARE @intIPTries INT    
      
  SELECT @dtOrgExpiryDate = ExpiresOn, @bitLockUser = LockUser, @intLockUserTries = LockUserTries, @bitLockIP = LockIP,             
		 @intIPLockDuration = IPLockDuration, @intIPTries = IPTries, @bigOrganizationId = OrganizationId             
  FROM   rvlfOrganization WHERE OrganizationCode = @cOrganizationCode            
  
  Update rvlfUserLogin SET LogOffDateTime=DATEADD(SECOND,-1,@dtLoginDateTime) WHERE UserId=@bigUserID and LogOffDateTime IS NULL        
  
  IF(@bigOrganizationId <> 1)    
  BEGIN    
      
   SELECT @dtOrgPurchasedDate = PurchasedOn FROM rvlfOrganizationPackage WHERE OrganizationID = @bigOrganizationId AND IsActive = 1    
      
   IF SYSUTCDATETIME() < @dtOrgPurchasedDate    
    BEGIN    
     INSERT INTO rvlfUserLogin     
     (UserID, OrgId, LoginDateTime, IP, LoginStatus ) VALUES (@bigUserID, @bigOrganizationId, @dtLoginDateTime,@vcIPAddress , 1)    
     raiserror('Your license is not yet started',15,0)    
     RETURN    
    END    
       
   IF SYSUTCDATETIME() > @dtOrgExpiryDate    
    BEGIN    
     INSERT INTO rvlfUserLogin     
     (UserID, OrgId, LoginDateTime, IP, LoginStatus ) VALUES (@bigUserID, @bigOrganizationId, @dtLoginDateTime,@vcIPAddress , 1)    
     raiserror('Your account has been expired',15,0)    
     RETURN    
    END    
  END    
      
  SET @intUserGroupAssigned = (SELECT COUNT(*) FROM rvlfUserGroupAssignment WHERE UserId = @bigUserID)    
       
  IF (@bitLockIP = 1)    
  BEGIN    
          
   SELECT @unSuccessfulLogins = COUNT(*) FROM rvlfUserLogin UL    
   WHERE UL.OrgId = @bigOrganizationId AND UL.UserId = 0 AND UL.IP = @vcIPAddress AND   
   UL.LoginDateTime BETWEEN DATEADD(HH,-@intIPLockDuration,@dtLoginDateTime) AND @dtLoginDateTime     
      
  END    
      
  IF (@bitLockIP = 1 AND @vcUserName <> 'Administrator' AND @unSuccessfulLogins >= @intIPTries) -- AND @bigUserID IS NULL    
     BEGIN    
   DECLARE @vcerrorMessage varchar(150)    
   SELECT @vcerrorMessage = dbo.rvlf_fn_GetTimeFromSeconds( (@intIPLockDuration * 3600) - DATEDIFF(ss,     
     (    
      SELECT MAX(UL.LoginDateTime) FROM rvlfUserLogin UL    
      WHERE UL.UserId = 0  AND UL.OrgId = @bigOrganizationId AND UL.IP = @vcIPAddress AND   
      UL.LoginDateTime BETWEEN DATEADD(HH,-@intIPLockDuration,@dtLoginDateTime) AND @dtLoginDateTime    
     ),@dtLoginDateTime) )    
   SET @vcerrorMessage = 'This IP is blocked. Try after '+ @vcerrorMessage    
   raiserror (@vcerrorMessage,16,1)    
   return    
  END    
  ELSE IF EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] = @vcPassword  COLLATE SQL_Latin1_General_CP1_CS_AS and IsLocked = 0 and IsActive = 1 AND ISDELETE=0    
    AND(@cOrganizationCode is NULL OR @cOrganizationCode='' OR  OrganizationId = (SELECT OrganizationId FROM rvlfOrganization WHERE OrganizationCode = @cOrganizationCode)))    
  BEGIN    
   IF (@intUserGroupAssigned > 0 OR @bigUserID = 1)    
   BEGIN    
       DECLARE @IsFirstLogin AS BIT = 0    
           
       SET @IsFirstLogin = (SELECT IsPwdChanged FROM rvlfuser WHERE UserId = @bigUserID)    
    INSERT INTO rvlfUserLogin     
    (UserID, OrgId, LoginDateTime, IP, LoginStatus ) VALUES (@bigUserID, @bigOrganizationId, @dtLoginDateTime,@vcIPAddress , 1)    
        select @bigUserID, @bigOrganizationId, @dtLoginDateTime,@vcIPAddress , 1
        SELECT *,(case when isnull(up.DefaultDateFormat,0)=0 then Convert(varchar,getdate(),107) else Convert(varchar,getdate(),up.DefaultDateFormat) end) as UserDateFormat, @IsFirstLogin AS 'IsFirstLogin',
        CASE WHEN og.OrgLatitude IS NULL THEN '23.805450,78.486328,4'ELSE CAST(og.OrgLatitude AS VARCHAR(10)) + ','+ CAST(og.OrgLongitude AS VARCHAR(10))+','+ CAST(og.OrgZoomlevel AS VARCHAR(2)) END AS OrgCoords
        FROM rvlfUser t1       
     INNER JOIN rvlfUserLogin t2 ON t1.UserId = t2.UserId       
     INNER JOIN rvlfOrganization og ON t1.OrganizationId = og.OrganizationId  
     INNER JOIN rvlfUserPreferences up on t1.UserId=up.UserId          
    WHERE t1.UserName = @vcUserName AND t1.[Password] = @vcPassword AND t2.LoginId = @@IDENTITY      
         
    -- Commented the retrieval of last login and instead returned the soltuion details    
        
    --SELECT TOP 1 * FROM rvlfUserLogin t2 INNER JOIN rvlfUser t1 ON t2.UserId= t1.UserId     
    --INNER JOIN rvlfOrganization g ON t1.OrganizationId = g.OrganizationId     
    -- WHERE LoginId < @@IDENTITY AND LoginStatus = 1 AND t2.UserId = @bigUserID ORDER BY     
    -- t2.LoginDateTime DESC    
     SELECT g.SolutionId, g.OrganizationId, s.SolutionId, s.ResourceFileName FROM rvlfOrganizationSolution g     
      INNER JOIN rvlfTrinetraSolutions s ON g.SolutionId = s.SolutionId    
      WHERE g.OrganizationId = @bigOrganizationId    
         
     SELECT * FROM rvlfUserGroup g    
     INNER JOIN rvlfUserGroupAssignment ga On g.UserGroupId = ga.UserGroupId    
     WHERE ga.UserId  = @bigUserID    
         
          
     SELECT * FROM rvlfUserGroupSecurity s    
     INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId    
     WHERE ga.UserId = @bigUserID
        
   END    
   ELSE    
   BEGIN    
    raiserror('Your account does not have privilege', 16,1)    
   END    
  END    
  ELSE    
  BEGIN    
      IF EXISTS (SELECT UserID FROM rvlfUser WHERE (UserName = @vcUserName AND [Password] != @vcPassword  COLLATE SQL_Latin1_General_CP1_CS_AS) and IsLocked = 1)    
   BEGIN    
    raiserror('Invalid Credentials', 16,1)    
   END    
   ELSE IF EXISTS (SELECT UserID FROM rvlfUser WHERE (UserName = @vcUserName AND [Password] = @vcPassword  COLLATE SQL_Latin1_General_CP1_CS_AS) and IsLocked = 1)    
   BEGIN    
    raiserror('Your account is locked', 16,1)    
   END    
   ELSE IF EXISTS (SELECT UserID FROM rvlfUser WHERE (UserName = @vcUserName AND [Password] = @vcPassword  COLLATE SQL_Latin1_General_CP1_CS_AS) and IsActive = 0)    
   BEGIN    
    raiserror('Your account is Inactivated', 16,1)    
   END    
   ELSE IF EXISTS (SELECT UserID FROM rvlfUser WHERE (UserName = @vcUserName AND [Password] = @vcPassword  COLLATE SQL_Latin1_General_CP1_CS_AS) and IsActive = 1 AND ISDELETE=1  AND (OrganizationId =     
   (SELECT OrganizationId FROM rvlfOrganization WHERE OrganizationCode = @cOrganizationCode)))    
   BEGIN    
    raiserror('Your account is inaccessible. Kindly contact your administrator.', 16,1)    
   END    
   ELSE IF (@intUserGroupAssigned = 0 AND @bigUserID > 0)    
   BEGIN    
    raiserror('Your account does not have privilege', 16,1)    
   END    
   ELSE    
   BEGIN    
    INSERT INTO rvlfUserLogin (UserID, OrgId, LoginDateTime, IP, LoginStatus )     
    VALUES (ISNULL(@bigUserID,0), ISNULL(@bigOrganizationId,0), @dtLoginDateTime,@vcIPAddress , 0)    
        
    IF @bigUserID IS NOT NULL --AND @vcUserName <> 'Administrator'    
    BEGIN    
            
        DECLARE @dtLockedDateTime AS DATETIME    
            
        SELECT @dtLockedDateTime = LockedDateTime FROM rvlfuser WHERE UserId = @bigUserID    
            
     SELECT @unSuccessfulLogins = COUNT(*) FROM rvlfUserLogin     
      WHERE (@dtLockedDateTime IS NULL OR LoginDateTime > @dtLockedDateTime) AND UserId = @bigUserID    
      AND LoginStatus = 0 AND @bigUserID > 0    
       
	   select @intLockUserTries=isnull(ug.LockUserTries,@intLockUserTries) from rvlfUserGroup ug inner join rvlfUserGroupAssignment uga on ug.UserGroupId=uga.UserGroupId where uga.UserId=@bigUserID

     IF (@bitLockUser = 1 AND @unSuccessfulLogins > @intLockUserTries)    
     BEGIN    
         IF @vcUserName <> 'Administrator'    
         BEGIN    
       UPDATE rvlfUser SET IsLocked = 1, LockedDateTime=@dtLoginDateTime WHERE UserId = @bigUserID    
       raiserror('Your account is locked', 16,1)    
       RETURN     
      END    
      ELSE    
      BEGIN    
          DECLARE @vcMsg AS Varchar(210) = ''    
          SET @vcMsg = 'Invalid Credentials'     
          IF(@vcEmail IS NOT NULL AND @vcEmail <> '')    
          BEGIN    
        SET @vcMsg = @vcMsg + ';'+ @vcEmail + ';' + @vcdisplayName    
          END    
       raiserror(@vcMsg, 16,1)    
      END    
     END    
     ELSE    
      raiserror('Invalid Credentials', 16,1)    
    END    
    ELSE     
    BEGIN    
     raiserror('Invalid Credentials', 16,1)    
    END    
   END    
  END      
      
  ----Included By Jeyanthi on 23-Sep-2010 for updating Demo Organization Data    
  --If(@bigOrganizationId =30 OR @bigOrganizationId =55) --29- Pilot Server & 30-Dedicated Server & defense organization    
  -- BEGIN    
  --  IF(NOT EXISTS (SELECT TOP 10 BoxId  FROM rvlfMsgInHst WHERE BoxId IN(SELECT BoxId FROM rvlfBoxId WHERE OrganizationId =30) AND CONVERT(DATE,OriginDateTime)=CONVERT(DATE,DATEADD(D,-1,GETUTCDATE()))))    
  --   BEGIN    
  --    Exec rvlf_sp_UpdateDateForDemo @bigOrganizationId    
  --   END    
         
  --  IF(NOT EXISTS (SELECT TOP 10 BoxId  FROM rvlfMsgInHst WHERE BoxId IN(SELECT BoxId  FROM rvlfBoxId WHERE OrganizationId =55) AND CONVERT(DATE,OriginDateTime)=CONVERT(DATE,DATEADD(D,-1,GETUTCDATE())) ORDER BY BoxId DESC ))    
  --   BEGIN    
  --    Exec rvlf_sp_UpdateDateForDemo @bigOrganizationId    
  --   END        
  -- END    
  ----End    
      
 SET NOCOUNT OFF    
END    
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AuthneticateUsers_MApp]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_AuthneticateUsers_MApp]
@vcUserName nvarchar(50),            
@vcPassword varchar(100),            
@cOrganizationCode char(3)= null
AS
/*************************************************************************************/            
-- Name  : rvlf_sp_AuthneticateUsers_MApp  'kapil','kEoemxZTaLsMvHpCrD5H4w==','int'
-- Description : To authenticate the users            
-- Author  : S SAKTHI GOPINATH
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
/*************************************************************************************/    
BEGIN
SET NOCOUNT ON
	DECLARE @bigUserID int = 0,@DefaultFleetId int = 0, @OrgId int
	SELECT @bigUserID = u.UserID, @OrgId = u.OrganizationId, @DefaultFleetId = ISNULL(fu.FleetId,0) FROM rvlfUser u 
	INNER JOIN rvlfFleetUsers fu ON fu.UserId=u.UserId INNER JOIN rvlfOrganization o ON o.OrganizationId=u.OrganizationId
	WHERE u.UserName = @vcUserName AND u.IsDelete=0 AND
	((@cOrganizationCode is NULL OR @cOrganizationCode='') OR o.OrganizationCode = @cOrganizationCode)
	
	SELECT CASE WHEN @bigUserID <= 0 THEN '0' ELSE '1' END AS [Status],@bigUserID AS UserId
	
	SELECT f.FleetId,f.FleetName,CASE WHEN (@DefaultFleetId=0 AND f.FleetName='All') OR (@DefaultFleetId = f.FleetId)
	THEN '1' ELSE '0' END AS IsDefaultFleet,(SELECT COUNT(*) FROM rvlfFleetVehicles WHERE FleetId=f.FleetId) AS FleetCount 
	FROM rvlfFleet f INNER JOIN rvlfOrganization o ON o.OrganizationId=f.OrganizationId 
	INNER JOIN rvlfFleetUsers fu ON fu.FleetId=f.FleetId
	INNER JOIN rvlfUser u ON u.UserId = fu.UserId
	WHERE u.UserId=@bigUserID AND o.OrganizationCode=@cOrganizationCode
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AuthneticateUsers_PG]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_AuthneticateUsers_PG]
	@vcUserName VARCHAR(25),
	@vcPassword VARCHAR(250),
	@cOrganizationCode CHAR(3),
	@vcDevRegID varchar(500),
	@IsLogin int = 0,
	@DevOS char(5)
AS
/******************************************************************************/            
-- Name  : rvlf_sp_AuthneticateUsers_PG  'administrator','Vq3GnyTkLB/dEsK4Q3RXpS0caX8bCsPVX0qExZ/i0j8=','GFB','APA91bGj7RvyQ2xpY1jZbkNJ_Enan1yx8w-lUIAbAOaG68b5KHBZrEFZKvCXcDp8_x8uAKDwsRBI705YEpJPQ8aJbpNRzVvfWYkGmc7cN3lllk_warAWek7LSC7poKN40TBhzkH8r6-z',1,'A'
-- Description : To authenticate the users
-- Author  : SAKTHI GOPINATH S
-- Company  : Angler Technologies
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason
/******************************************************************************/      
	BEGIN
		SET NOCOUNT ON
		IF NOT EXISTS (SELECT 1 FROM dbo.rvlfOrganization WHERE OrganizationCode=@cOrganizationCode)
			BEGIN
				RAISERROR('Invalid Credentials!', 16,1); --Invalid Organization Code!
				RETURN; 
			END
		ELSE
			BEGIN
				--IF EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] != @vcPassword and IsLocked = 1)              
				--BEGIN              
				-- RAISERROR('Invalid Credentials', 16,1);  
				-- RETURN;   
				--END      
				--ELSE   
				IF (NOT EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] = @vcPassword)and   
				--NOT EXISTS (SELECT UserID FROM rvlfParentMaster WHERE MobileNo = @vcUserName AND [Password] = @vcPassword)  and  
				NOT EXISTS (SELECT StudentID FROM rvlfStudentMaster s  
				inner join rvlfOrganization o on o.organizationId = s.OrganizationID  
				WHERE s.ContactNo = @vcUserName AND o.OrganizationCode = @cOrganizationCode))  
					BEGIN              
						RAISERROR('Invalid Credentials!', 16,1);  
						RETURN;   
					END  
				else IF EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] = @vcPassword)       
					Begin  
						IF EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] = @vcPassword  and IsLocked = 1)              
							BEGIN              
								RAISERROR('Your account has been locked!', 16,1);  
								RETURN;     
							END              
						ELSE IF EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] = @vcPassword  and IsActive = 0)              
							BEGIN              
								RAISERROR('Your account is Inactive!', 16,1);  
								RETURN;           
							END              
						ELSE IF EXISTS (SELECT OrganizationCode FROM rvlfOrganization o inner join rvlfUser u on u.OrganizationId = o.OrganizationId  
						WHERE UserName = @vcUserName AND [Password] = @vcPassword and  
						OrganizationCode = @cOrganizationCode and isnull(EnableApp,0) = 0 and  IsHidden <> 1 and AppInsDate is not null)              
							BEGIN              
								RAISERROR('You have no access privilege. Contact your Account Manager!', 16,1);  
								RETURN;           
							END       
						ELSE IF EXISTS (SELECT OrganizationCode FROM rvlfOrganization o inner join rvlfUser u on u.OrganizationId = o.OrganizationId  
						WHERE UserName = @vcUserName AND [Password] = @vcPassword and  
						OrganizationCode = @cOrganizationCode and 
						AppInsDate is not null and GETUTCDATE() >= o.ExpiresOn
						--- Modified by Ranjith 18-Sep-2015 -- App expiry set to Organization level expiry
						--AppInsDate is not null and GETUTCDATE() >= dateadd(DD,isnull(AppExpDays,0),isnull(AppInsDate,dateadd(dd,-1,getutcdate()))) 
						and IsHidden <> 1 and o.OrganizationId not in (1,6))              
							BEGIN              
								RAISERROR('Your account has expired. Contact your Account Manager!', 16,1);  
								RETURN;           
							END       
						ELSE  
							BEGIN  
								--Declare @vcMapVal varchar(max),@vcUID bigint    
								Declare @vcMapVal varchar(max),@vcUID bigint,@vcCmdVal varchar(max)      
								IF EXISTS (SELECT OrganizationCode FROM rvlfOrganization o inner join rvlfUser u on u.OrganizationId = o.OrganizationId  
								WHERE OrganizationCode = @cOrganizationCode  and AppInsDate is null    
								and  UserName = @vcUserName AND [Password] = @vcPassword and IsHidden <> 1)  
									Begin  
										update rvlfOrganization set AppInsDate = getutcdate(),EnableApp=1,AppExpDays =15,AppReminder1 =5 where OrganizationCode = @cOrganizationCode  
									End     
								IF EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] = @vcPassword ) --and DevRegID is null      
									BEGIN                  
										update rvlfUser set DevRegID = null where UserId in (  
										select UserId from rvlfUser where DevRegID = @vcDevRegID)       
										update rvlfUser set DevRegID = @vcDevRegID,DevOS = @DevOS where UserName = @vcUserName AND [Password] = @vcPassword and OrganizationId =               
										(SELECT OrganizationId FROM rvlfOrganization WHERE OrganizationCode = @cOrganizationCode)        
									END     
								DECLARE @bigUserID bigint = 0               
								DECLARE @bigOrgID bigint = 0  
								SELECT @bigUserID = UserID, @bigOrgID =  OrganizationId  
								from rvlfUser where UserName = @vcUserName AND [Password] = @vcPassword and OrganizationId =               
								(SELECT OrganizationId FROM rvlfOrganization WHERE OrganizationCode = @cOrganizationCode)   
								SELECT u.UserName,u.UserId,u.DisplayName,o.OrganizationDisplayName,o.OrganizationId, u.UserId,  
								isnull(o.EnableApp,0) as EnableApp,Dateadd(DD,o.AppExpDays,o.AppInsDate) as AppInsDate,AppExpDays,AppReminder1,isnull(DevRegID,0) as DevRegID,DevOS,  
								1 as ParentLogin,u.Email,U.LastName,UP.DefaultFleetId  
								FROM rvlfUser u INNER JOIN dbo.rvlfOrganization o ON u.OrganizationId=o.OrganizationId inner join rvlfUserPreferences UP on UP.UserId=u.UserId 
								WHERE o.OrganizationCode=@cOrganizationCode AND u.UserName=@vcUserName AND u.Password=@vcPassword  
								AND u.IsActive=1 AND u.IsDelete=0      
								DECLARE @tblModuleOperations TABLE(ModuleId VARCHAR(7),OperationId VARCHAR(7),CommandId VARCHAR(7))
								INSERT INTO @tblModuleOperations (ModuleId, OperationId,CommandId)
								select isnull(ug.ModuleId,'2,3,4,') as ModuleId,ug.OperationTypeId,c.BoxCmdOutTypeId from rvlfUserGroupSecurity ug    
								inner join rvlfUserGroupAssignment ua on  ug.UserGroupId = ua.UserGroupId -- and ug.ModuleId in (2,3,4)    
								inner join rvlfUser u  on  ua.UserId = u.UserId   
								Left Join rvlfBoxCmdOutType C ON c.OperationTypeId = ug.OperationTypeId
								where u.UserId = (SELECT u.UserId FROM rvlfUser u INNER JOIN dbo.rvlfOrganization o ON u.OrganizationId=o.OrganizationId    
								WHERE o.OrganizationCode=@cOrganizationCode AND u.UserName=@vcUserName AND u.Password=@vcPassword    
								AND u.IsActive=1 AND u.IsDelete=0)
								SELECT @vcMapVal= coalesce(@vcMapVal,'')+(CAST(ModuleId  AS NVARCHAR(MAX)))+',' FROM (SELECT DISTINCT ModuleId AS ModuleId FROM @tblModuleOperations) M
								SELECT @vcCmdVal = coalesce(@vcCmdVal,'')+(CAST(CommandId  AS NVARCHAR(5)))+',' FROM (SELECT DISTINCT CommandId AS CommandId FROM @tblModuleOperations WHERE ModuleId=22 AND CommandId IS NOT NULL) C
								select SUBSTRING(@vcMapVal,1,LEN(@vcMapVal)-1) as Menu,SUBSTRING(@vcCmdVal,1,LEN(@vcCmdVal)-1) AS Command  
								
								--Select  @vcMapVal= coalesce(@vcMapVal,'')+(CAST(ModuleId  AS NVARCHAR(MAX)))+',' From(    
								-- select distinct isnull(ug.ModuleId,'2,3,4,') as ModuleId  from rvlfUserGroupSecurity ug    
								-- inner join rvlfUserGroupAssignment ua on  ug.UserGroupId = ua.UserGroupId -- and ug.ModuleId in (2,3,4)    
								-- inner join rvlfUser u  on  ua.UserId = u.UserId    
								-- where u.UserId = (SELECT u.UserId FROM rvlfUser u INNER JOIN dbo.rvlfOrganization o ON u.OrganizationId=o.OrganizationId    
								-- WHERE o.OrganizationCode=@cOrganizationCode AND u.UserName=@vcUserName AND u.Password=@vcPassword    
								-- AND u.IsActive=1 AND u.IsDelete=0)) as TBL    
								-- select SUBSTRING(@vcMapVal,1,LEN(@vcMapVal)-1) as Menu  
								--select '2,3,4' as Menu   
								if @IsLogin = 1  
									Begin  
										Insert into rvlfUserLogin_PhoneApp(UserId,OrgId,LoginDateTime) values(@bigUserID,@bigOrgID,GETUTCDATE())  
									end  
							END  
					End  
				else  
					Begin  
						IF NOT EXISTS (SELECT StudentID FROM rvlfStudentMaster s inner join rvlfOrganization o on o.organizationId = s.OrganizationID  
						WHERE s.ContactNo = @vcUserName AND o.OrganizationCode = @cOrganizationCode ) --and  o.organizationId in (1,6)
							Begin  
								RAISERROR('Invalid Credentials of Parent details!', 16,1);  
								RETURN;   
							End  
						else  
							Begin     
								IF NOT EXISTS (SELECT UserID FROM rvlfParentMaster WHERE MobileNo = @vcUserName)  
									Begin  
										Insert into rvlfParentMaster(username,password,MobileNo,OrganizationId,DisplayName,  
										IsActive,CreatedDateTime,IsDelete,DevRegID,DevOS,AllowMobApp)  
										values(@vcUserName,@vcPassword,@vcUserName,(Select organizationid from rvlforganization where organizationcode =@cOrganizationCode),@vcUserName,0,GETUTCDATE(),0,@vcDevRegID,@DevOS,0)       
									End  
								IF NOT EXISTS (SELECT StudentID FROM rvlfStudentMaster s inner join rvlfOrganization o on o.organizationId = s.OrganizationID    
								inner join rvlfParentMaster pm on pm.MobileNo = s.ContactNo
								WHERE s.ContactNo = @vcUserName AND o.OrganizationCode = @cOrganizationCode and pm.AllowMobApp=1 )  --  and o.organizationId in (1,6)
									Begin    
										RAISERROR('Please contact Administrator to activate your account!', 16,1);    
										RETURN;     
									End    
								IF EXISTS (SELECT UserID FROM rvlfParentMaster WHERE UserName = @vcUserName AND [Password] = @vcPassword ) --and DevRegID is null      
									BEGIN                  
										update rvlfParentMaster set DevRegID = null where UserId in (  
										select UserId from rvlfParentMaster where DevRegID = @vcDevRegID)       
										update rvlfParentMaster set DevRegID = @vcDevRegID,DevOS = @DevOS where UserName = @vcUserName AND [Password] = @vcPassword and OrganizationId =               
										(SELECT OrganizationId FROM rvlfOrganization WHERE OrganizationCode = @cOrganizationCode)        
									END     
								SELECT u.UserName,u.UserId,u.DisplayName,o.OrganizationDisplayName,o.OrganizationId, u.UserId,  
								isnull(o.EnableApp,0) as EnableApp,Dateadd(DD,o.AppExpDays,o.AppInsDate) as AppInsDate,AppExpDays,AppReminder1,isnull(DevRegID,0) as DevRegID,DevOS,  
								0 as ParentLogin,U.Email FROM rvlfParentMaster U   
								INNER JOIN dbo.rvlfOrganization o ON u.OrganizationId=o.OrganizationId  
								WHERE o.OrganizationCode=@cOrganizationCode AND U.MobileNo = @vcUserName AND [Password] = @vcPassword  
								select '2,3,4' as Menu   
								DECLARE @bigParentID bigint = 0               
								DECLARE @bigOrgID1 bigint = 0  
								SELECT @bigParentID = UserID, @bigOrgID1 =  OrganizationId  
								from rvlfParentMaster where UserName = @vcUserName AND [Password] = @vcPassword and OrganizationId =               
								(SELECT OrganizationId FROM rvlfOrganization WHERE OrganizationCode = @cOrganizationCode)   
								if @IsLogin = 1  
									Begin  
										Insert into rvlfUserLogin_PhoneApp(UserId,OrgId,LoginDateTime) values(@bigParentID,@bigOrgID1,GETUTCDATE())  
									end  
							End  
					End  
			END  
		SET NOCOUNT OFF  
	END
--		--IF EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] != @vcPassword and IsLocked = 1)            
--		--BEGIN            
--		--	RAISERROR('Invalid Credentials', 16,1);
--		--	RETURN; 
--		--END    
--		--ELSE 
--		IF NOT EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] = @vcPassword)            
--		BEGIN            
--			RAISERROR('Invalid Credentials!', 16,1);
--			RETURN; 
--		END    
--		ELSE IF EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] = @vcPassword  and IsLocked = 1)            
--		BEGIN            
--			RAISERROR('Your account has been locked!', 16,1);
--			RETURN;   
--		END            
--		ELSE IF EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] = @vcPassword  and IsActive = 0)            
--		BEGIN            
--			RAISERROR('Your account is Inactive!', 16,1);
--			RETURN;         
--		END            
--		ELSE IF EXISTS (SELECT OrganizationCode FROM rvlfOrganization o inner join rvlfUser u on u.OrganizationId = o.OrganizationId
--						WHERE UserName = @vcUserName AND [Password] = @vcPassword and
--						OrganizationCode = @cOrganizationCode and isnull(EnableApp,0) = 0 and  IsHidden <> 1 and AppInsDate is not null)            
--		BEGIN            
--			RAISERROR('You have no access privilege. Contact your Account Manager!', 16,1);
--			RETURN;         
--		END   		
--		ELSE IF EXISTS (SELECT OrganizationCode FROM rvlfOrganization o inner join rvlfUser u on u.OrganizationId = o.OrganizationId
--						WHERE UserName = @vcUserName AND [Password] = @vcPassword and
--						OrganizationCode = @cOrganizationCode and AppInsDate is not null and GETUTCDATE() >= dateadd(DD,isnull(AppExpDays,0),isnull(AppInsDate,dateadd(dd,-1,getutcdate()))) and IsHidden <> 1 and o.OrganizationId not in (6))            
--		BEGIN            
--			RAISERROR('Your account has expired. Contact your Account Manager!', 16,1);
--			RETURN;         
--		END     
--		ELSE
--		BEGIN
--			   Declare @vcMapVal varchar(10),@vcUID bigint		
--			   IF EXISTS (SELECT OrganizationCode FROM rvlfOrganization o inner join rvlfUser u on u.OrganizationId = o.OrganizationId
--						WHERE OrganizationCode = @cOrganizationCode  and AppInsDate is null  
--						and  UserName = @vcUserName AND [Password] = @vcPassword and IsHidden <> 1)
--				Begin
--					update rvlfOrganization set AppInsDate = getutcdate(),EnableApp=1,AppExpDays =15,AppReminder1 =5 where OrganizationCode = @cOrganizationCode
--				End			
--				IF EXISTS (SELECT UserID FROM rvlfUser WHERE UserName = @vcUserName AND [Password] = @vcPassword ) --and DevRegID is null    
--				BEGIN            				
--					update rvlfUser set DevRegID = null where UserId in (
--					select UserId from rvlfUser where DevRegID = @vcDevRegID)					
--					 update rvlfUser set DevRegID = @vcDevRegID,DevOS = @DevOS where UserName = @vcUserName AND [Password] = @vcPassword and OrganizationId =             
--					(SELECT OrganizationId FROM rvlfOrganization WHERE OrganizationCode = @cOrganizationCode)      
--				END  	
--				DECLARE @bigUserID bigint = 0             
--				DECLARE @bigOrgID bigint = 0
--				SELECT @bigUserID = UserID, @bigOrgID =	 OrganizationId
--					from rvlfUser where UserName = @vcUserName AND [Password] = @vcPassword and OrganizationId =             
--					(SELECT OrganizationId FROM rvlfOrganization WHERE OrganizationCode = @cOrganizationCode) 
--				SELECT u.UserName,u.UserId,u.DisplayName,o.OrganizationDisplayName,o.OrganizationId, u.UserId,
--				isnull(o.EnableApp,0) as EnableApp,Dateadd(DD,o.AppExpDays,o.AppInsDate) as AppInsDate,AppExpDays,AppReminder1,isnull(DevRegID,0) as DevRegID,DevOS
--				FROM rvlfUser u INNER JOIN dbo.rvlfOrganization o ON u.OrganizationId=o.OrganizationId
--				WHERE o.OrganizationCode=@cOrganizationCode AND u.UserName=@vcUserName AND u.Password=@vcPassword
--				AND u.IsActive=1 AND u.IsDelete=0				
--				Select  @vcMapVal= coalesce(@vcMapVal,'')+(CAST(ModuleId  AS NVARCHAR(MAX)))+',' From(
--				select distinct isnull(ug.ModuleId,'2,3,4,') as ModuleId  from rvlfUserGroupSecurity ug
--				inner join rvlfUserGroupAssignment ua on  ug.UserGroupId = ua.UserGroupId and ug.ModuleId in (2,3,4)
--				inner join rvlfUser u  on  ua.UserId = u.UserId
--				where u.UserId = (SELECT u.UserId FROM rvlfUser u INNER JOIN dbo.rvlfOrganization o ON u.OrganizationId=o.OrganizationId
--				WHERE o.OrganizationCode=@cOrganizationCode AND u.UserName=@vcUserName AND u.Password=@vcPassword
--				AND u.IsActive=1 AND u.IsDelete=0)) as TBL
--				--select SUBSTRING(@vcMapVal,1,LEN(@vcMapVal)-1) as Menu	
--				select '1,2,3,4' as Menu	
--				if @IsLogin = 1
--				Begin
--					Insert into rvlfUserLogin_PhoneApp(UserId,OrgId,LoginDateTime) values(@bigUserID,@bigOrgID,GETUTCDATE())
--				end
--		END
--	END
--SET NOCOUNT OFF
--END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_AutoCompleteSearch]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_AutoCompleteSearch]
	@TableName Varchar(25),
	@ConditionField Varchar(15),
	@CondValue Varchar(15)
AS
/******************************************************************************/
--	Name		:	rvlf_sp_AutoCompleteSearch
--	Description	:	To incorporate AutoComplete Search
--	Author		:	L. Kumuthini
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	25-Jul-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 

DECLARE @SQL AS Varchar(100) = ''

SET @SQL = 'SELECT ' + @ConditionField + ' FROM ' + @TableName + ' WHERE ' + @ConditionField + ' LIKE ''' + @CondValue + '%'''
EXEC(@SQL)
	
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_BulkAssignUser]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_BulkAssignUser]
	@xmlFleetUserList XML
AS
/******************************************************************************/
--	Name		:	rvlf_sp_BulkAssignUser
--	Description	:	To assign users to the fleet in bulk manner
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	24-Jul-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
	
	BEGIN TRAN MessageOutTransaction
	BEGIN TRY
	 DECLARE @index int

		 EXEC sp_xml_preparedocument @index OUTPUT, @xmlFleetUserList

		 INSERT INTO rvlfFleetUsers
		  (
			FleetId,UserId ,AssignedBy, AssignedDate
		  )
		 SELECT fleetid , UserId, AssingedBy, AssignedDate
		 FROM OPENXML (@index, '/FleetUsers/AssignedUserList')
		 WITH (
		  fleetID bigint 'Fleetid',
		  UserId bigint 'UserID',
			AssingedBy bigint 'AssignedBy',
			AssignedDate datetime 'AssignedDate')
		 EXEC sp_xml_removedocument @index
		 
	COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during assigning users to the fleet : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_BulkAssignUserGroup]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_BulkAssignUserGroup]
	@xmlAssignedUserList XML
AS
/******************************************************************************/
--	Name		:	rvlf_sp_BulkAssignUserGroup
--	Description	:	To assign users to the User Groups in bulk manner
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	27-Jul-2009	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
	
	BEGIN TRAN MessageOutTransaction
	BEGIN TRY
	 DECLARE @index int

		 EXEC sp_xml_preparedocument @index OUTPUT, @xmlAssignedUserList

		 INSERT INTO rvlfUserGroupAssignment
		  (
			UserId, UserGroupId ,AssignedBy, AssignedDate
		  )
		 SELECT UserId, UserGroupId , AssingedBy, AssignedDate
		 FROM OPENXML (@index, '/Users/AssignedUserList')
		 WITH (
		    UserId bigint 'UserId',
		    UserGroupId int 'UserGroupId',
			AssingedBy bigint 'AssignedBy',
			AssignedDate datetime 'AssignedDate')
		 EXEC sp_xml_removedocument @index
		 
	COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during assigning user group to the users : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_BulkAssignVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_BulkAssignVehicles]  
 @xmlFleetVehicleList XML = null,  
 @bitIsAll bit = null,  
 @bigFleetID bigint = null,  
 @bigAssignedBy bigint = null,  
 @dtAssignedDate Datetime = null,  
 @bigOrganizationID bigint = null,  
 @siUnassignedMakeID smallint = null,  
 @siUnassignedModelID smallint = null,  
 @intUnassignedVehicleTypeID int = null,  
 @vcUnssignedVehicleDesc varchar = null,  
 @vcVehicleIDs varchar(250) = null  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_BulkAssignVehicles  
-- Description : To assign vehicles to the fleet in bulk manner  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 24-Jul-2009 MJJC Created Intial Version   
--              :   21-Feb-2010 MJJC Included defalut checking instead of name  
/******************************************************************************/  
BEGIN  
--SET NOCOUNT ON   
 -- Local variables to hold the intermediate results  
 DECLARE @ErrorMessage varchar(3000)  
   
 BEGIN TRAN MessageOutTransaction  
 BEGIN TRY  
 IF @bitIsAll IS NULL OR @bitIsAll = 0   
 BEGIN  
   DECLARE @index int  
print 1  
    EXEC sp_xml_preparedocument @index OUTPUT, @xmlFleetVehicleList  
  
    INSERT INTO rvlfFleetVehicles  
     (  
    FleetId, VehicleId ,IsActive,AssignedBy, AssignedDate/*,DeactivatedBy,DeactivatedDate*/  
     )  
    SELECT fleetid , vehicleid, isactive, AssingedBy, AssignedDate  
    FROM OPENXML (@index, '/FleetVehicles/AssingedVehicleList')  
    WITH (  
     fleetID bigint 'Fleetid',  
     VehicleID bigint 'VehicleId',  
    isactive bit 'IsActive',  
    AssingedBy bigint 'AssignedBy',  
    AssignedDate datetime 'AssignedDate')  
    EXEC sp_xml_removedocument @index  
 END  
 ELSE   
 BEGIN  
 print 2  
     
  INSERT INTO rvlfFleetVehicles (FleetId, VehicleId ,IsActive,AssignedBy, AssignedDate)  
    (SELECT @bigFleetID, v.VehicleId, 1, @bigAssignedBy, @dtAssignedDate FROM rvlfVehicle v   
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId   
    INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
    LEFT OUTER JOIN rvlfModel m ON v.ModelId = m.ModelId  
    LEFT OUTER JOIN rvlfMake k ON v.MakeId = k.MakeId  
    INNER JOIN rvlfVehicleType t ON v.VehicleTypeId = t.VehicleTypeId  
    WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)  
     AND v.VehicleId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcVehicleIDs,','))  
     AND ((@vcUnssignedVehicleDesc is null OR @vcUnssignedVehicleDesc='' or  v.VehicleDescription LIKE '%'+@vcUnssignedVehicleDesc+'%' )OR v.VehicleTypeId = @intUnassignedVehicleTypeID OR v.MakeId = @siUnassignedMakeID OR v.ModelId = @siUnassignedModelID)  
     AND f.IsDefault=1 AND v.VehicleId NOT IN  
     ( SELECT rfv.VehicleId FROM rvlfFleetVehicles rfv WHERE FleetId = @bigFleetID))  
 END  
     
 COMMIT TRAN  
 END TRY  
 BEGIN CATCH  
  ROLLBACK TRAN   
  SET @ErrorMessage = 'An Error occured during assigning vehicles to the fleet : ' +ERROR_MESSAGE()  
  RAISERROR( @ErrorMessage,16,1)  
 END CATCH  
SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_BulkVehDetailsUpdate]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sp_helptext rvlf_sp_BulkVehDetailsUpdate

create Procedure [dbo].[rvlf_sp_BulkVehDetailsUpdate]   
 @intBoxId bigint = null,      
 @vcVehicleName nvarchar(20)  = Null,   
 @vcLicensePlate varchar(20)  = Null,  
 @vcVIN varchar(20)  = Null,  
 @vcIntNo varchar(20)  = Null,
 @siYear smallint  = Null,  
 @vcColor varchar(20) = Null,  
 @dtInsuranceExpired datetime=null,  
 @dtPermitExpired datetime=null,  
 @dtFcExpired datetime=null,  
 @dtPurchasedDate datetime=null,  
 @intOpeningEngineHrs int=null,  
 @intFuelTankCapacity int=null,  
 @intLifeSpan int=null,       
 @bigProcessedBy  bigint = Null,   
 @bigOrganizationId bigint,  
 @vcModelName varchar(50)=null  
   
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_BulkVehDetailsUpdate]  
-- Description : Update the vehicle details in bulk  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 19-Jan-2011 VN Created Intial Version  
--    : 18-Nov-2011 Sakthi Update Based on Boxid   
--    : 19-Dec-2011 Sakthi Change datatype of vehicle name  
--    : 23-Jan-2012 Sakthi Update internal vehicle number   
/******************************************************************************/  
BEGIN  
 --IF EXISTS(SELECT * FROM rvlfVehicle WHERE  VehicleDescription=@vcVehicleName AND OrganizationId=@bigOrganizationId )  
 IF EXISTS(SELECT v.VehicleId FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId  
     WHERE va.BoxId=@intBoxId and v.OrganizationId=@bigOrganizationId)  
  BEGIN  
   DECLARE @intMakeId int=null,@intModelId int=null,@intVehicleTypeId int=null  
   IF(@vcModelName IS NOT NULL AND @vcModelName !='')  
    SELECT @intMakeId =ISNULL(MakeId,0),@intModelId=ISNULL(ModelId,0),@intVehicleTypeId=ISNULL(VehicleTypeId,0) FROM rvlfModel WHERE ModelName=@vcModelName   
   --UPDATE rvlfVehicle SET LicensePlate=ISNULL(@vcLicensePlate,LicensePlate),Vin=ISNULL(@vcVIN,Vin),  
   -- ModelYear=ISNULL(@siYear,ModelYear),Color=ISNULL(@vcColor,Color),  
   -- LastInsuranceExpired=ISNULL(@dtInsuranceExpired,LastInsuranceExpired),  
   -- LastPermitExpired =ISNULL(@dtPermitExpired,LastPermitExpired),LastFCDate=ISNULL(@dtFcExpired,LastFCDate),  
   -- PurchasedDate=ISNULL(@dtPurchasedDate,PurchasedDate),OpeningEngineHours=ISNULL(@intOpeningEngineHrs,OpeningEngineHours),  
   -- TankCapacity=ISNULL(@intFuelTankCapacity,TankCapacity),ModelId=ISNULL(@intModelId,ModelId),MakeId=ISNULL(@intMakeId,MakeId),  
   -- VehicleTypeId=ISNULL(@intVehicleTypeId,VehicleTypeId), ModifiedBy=@bigProcessedBy,[Modified DateTime]=GETDATE()  
   --WHERE VehicleDescription=@vcVehicleName AND OrganizationId=@bigOrganizationId     
     
   UPDATE v SET v.LicensePlate=ISNULL(@vcLicensePlate,v.LicensePlate),v.Vin=ISNULL(@vcVIN,v.Vin),  
   v.VehicleDescription=ISNULL(@vcVehicleName,v.VehicleDescription),  
   v.InternalNo = ISNULL(@vcIntNo,v.VehicleDescription),
   v.ModelYear=ISNULL(@siYear,v.ModelYear),Color=ISNULL(@vcColor,v.Color),  
   v.LastInsuranceExpired=ISNULL(@dtInsuranceExpired,v.LastInsuranceExpired),  
   v.LastPermitExpired =ISNULL(@dtPermitExpired,v.LastPermitExpired),LastFCDate=ISNULL(@dtFcExpired,v.LastFCDate),  
   v.PurchasedDate=ISNULL(@dtPurchasedDate,v.PurchasedDate),OpeningEngineHours=ISNULL(@intOpeningEngineHrs,v.OpeningEngineHours),  
   v.TankCapacity=ISNULL(@intFuelTankCapacity,v.TankCapacity),ModelId=ISNULL(@intModelId,v.ModelId),  
   MakeId=ISNULL(@intMakeId,v.MakeId), LifeSpan = @intLifeSpan,     
   v.VehicleTypeId=ISNULL(@intVehicleTypeId,v.VehicleTypeId), ModifiedBy=@bigProcessedBy,[Modified DateTime]=GETDATE()  
   FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId  
   WHERE va.BoxId=@intBoxId AND v.OrganizationId=@bigOrganizationId     
     
  END  
 ELSE IF EXISTS(SELECT * FROM rvlfVehicle WHERE  VehicleDescription=@vcVehicleName AND OrganizationId!=@bigOrganizationId )  
  BEGIN  
   RAISERROR('This Vehicle details are not available in the Organization.',16,1)  
  END  
 ELSE IF EXISTS(SELECT * FROM rvlfVehicle WHERE  VehicleDescription!=@vcVehicleName AND OrganizationId=@bigOrganizationId )  
  BEGIN  
   RAISERROR('This Organization not having this Vehicle details.',16,1)  
  END  
 ELSE   
  BEGIN  
   RAISERROR('Invalid vehicle details update.',16,1)  
  END  
      
END   
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ChangeParentPassword_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
  
CREATE PROCEDURE [dbo].[rvlf_sp_ChangeParentPassword_PhoneGap]       
/******************************************************      
Stored Procedure Name : rvlf_sp_ChangeParentPassword_PhoneGap      
Purpose     : Update password for Parent  
Created by    : Ranjith N     
Created date   : 26-Jun-2015      
Updated by    :       
Updated date   :       
*******************************************************/      
      
@UserID bigint   = Null,      
@OldPwd varchar(100)=null,  
@NewPwd  varchar(100) = null    
AS      
      
BEGIN       
      
 IF (@UserID > 0)      
 BEGIN      
    if Exists(Select * from rvlfParentMaster where UserId = @UserID and Password =@OldPwd)  
    Begin      
   UPDATE rvlfParentMaster SET Password = @NewPwd, IsPwdChanged = 1 WHERE UserId = @UserID   
 End  
 Else  
 Begin  
  RAISERROR('Invalid Old password!', 16,1)  
 End    
 END      
      
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ChangePassword]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_ChangePassword]
(
   @UserId bigint, 
   @OldPassword varchar(100), 
   @NewPassword varchar(100)
)
AS
/****************************************************************************************/
--	Name		  : rvlf_sp_ChangePassword
--	Description	  :	To change the password for a particular user 
--	Author		  :	Kumuthini. L
--	Created Date  : 14-July-09
--  Modified Date :
/***************************************************************************************/
BEGIN
	SET NOCOUNT ON 
	
	DECLARE @isSimilar AS INT
	
	-- Check the Old Password is similar to the password in the Database by passing the User Id
	SET @isSimilar = (SELECT COUNT(*) FROM rvlfUser WHERE UserId = @UserId AND Password = @OldPassword)   

	IF(@isSimilar > 0)
		BEGIN
		    -- If the Old Password is Correct, then replace the Old Password with the new one
			UPDATE rvlfUser SET Password = @NewPassword WHERE UserId = @UserId 
			
			SELECT 1 AS "Flag"
		END
	ELSE
		BEGIN
			SELECT 0 AS "Flag"  
		END
		
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ChangePassword_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_ChangePassword_PhoneGap]       
	@UserID bigint   = Null,      
	@OldPwd varchar(100)=null,  
	@NewPwd  varchar(100) = null    
AS      
	BEGIN       
		IF (@UserID > 0)      
			BEGIN      
				if Exists(Select * from rvlfUser where UserId = @UserID and Password =@OldPwd)  
					Begin      
						UPDATE rvlfUser SET Password = @NewPwd, IsPwdChanged = 1 WHERE UserId = @UserID   
					End  
				Else  
					Begin  
						RAISERROR('Invalid Old password!', 16,1)  
					End    
			END      
	END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ChangeVehicleToAntherOrg]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_ChangeVehicleToAntherOrg]    
(  
@boxid bigint,  
@NewOrgId Bigint  
)  
as  
/*****************************************************************************
Procedure Created By Gopalakrishnan
Updated By Sakthi
*****************************************************************************/
begin  
Declare @VehicleID bigint = (select VehicleId from rvlfVehicleAssignment where boxid=@boxid)  
Declare @NewFleetID Bigint = (select FleetId from rvlfFleet where OrganizationId=@NewOrgId and IsDefault=1)  
Declare @PrevOrgID bigint = (select OrganizationId from rvlfVehicle where VehicleId=@VehicleID)  
select o.OrganizationName,COUNT(*) as rvlfvehicle  from rvlfvehicle v inner join rvlfOrganization o on v.OrganizationId=o.OrganizationId  
 where v.OrganizationId in (@NewOrgId,@PrevOrgID) group by o.OrganizationName  
select COUNT(*) as rvlfFleetVehicles from rvlfFleetVehicles fv inner join rvlfFleet f on fv.FleetId=f.FleetId where OrganizationId in (@NewOrgId,@PrevOrgID)  
select count(*) as rvlfBoxId from rvlfBoxId where OrganizationId in (@NewOrgId,@PrevOrgID)  
  
update rvlfBoxId set OrganizationId=@NewOrgId where BoxId=@boxid  
update rvlfVehicle set OrganizationId=@NewOrgId where VehicleId=@VehicleID  
update rvlfFleetVehicles set FleetId=@NewFleetID  where VehicleId=@VehicleID AND
FleetId  = (SELECT TOP 1 FleetId FROM rvlfFleetVehicles WHERE VehicleId=@VehicleID)
  
select o.OrganizationName,COUNT(*) as rvlfvehicle  from rvlfvehicle v inner join rvlfOrganization o on v.OrganizationId=o.OrganizationId  
 where v.OrganizationId in (@NewOrgId,@PrevOrgID) group by o.OrganizationName  
select COUNT(*) as rvlfFleetVehicles from rvlfFleetVehicles fv inner join rvlfFleet f on fv.FleetId=f.FleetId where OrganizationId in (@NewOrgId,@PrevOrgID)  
select count(*) as rvlfBoxId from rvlfBoxId where OrganizationId in (@NewOrgId,@PrevOrgID)  
  
end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckCarMakeInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_CheckCarMakeInfo]  
 @CarId int=Null,  
 @CarName varchar(50) = Null  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_CheckCarMakeInfo]null  
-- Description : To check the duplicates in the Car Make and Model details.  
-- Author  : V.Muthukumaravadivel  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 24-Feb-2011 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
    
    IF @CarName IS NOT NULL  
    BEGIN  
  SELECT MakeName FROM rvlfMake   
  WHERE   
  (@CarId IS NULL OR @CarId='' OR MakeId <> @CarId)   
  AND MakeName=@CarName   
    
  SELECT ModelName FROM rvlfModel   
  WHERE   
  (@CarId IS NULL OR @CarId='' OR ModelId <> @CarId)   
   AND ModelName=@CarName  
      
 END   
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDeviceAvailability]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E	
-- Create date: 11-06-2015
-- Description:	Checks whether the Logged in user has registered with any Mobile device.
--				rvlf_sp_CheckDeviceAvailability 219
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDeviceAvailability]
	-- Add the parameters for the stored procedure here
	@bigUserID					bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
    Declare @return bit
    Set @return =	(SELECT	COUNT(UserId) 
					FROM	rvlfUser 
					WHERE	DevRegID IS NOT NULL 
					and		DevOS IS NOT NULL
					and		UserId = @bigUserID)
	Select @return 
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDeviceInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_CheckDeviceInfo]        
 @Sno bigint=null,  
 @bigboxid varchar(15) = Null,        
 @vcEquipDescription varchar(50) = null,    
 @bigOrganizationID bigint = null    
AS        
/******************************************************************************/        
-- Name  : rvlf_sp_CheckDeviceInfo 575757,null,86       
-- Description : To check the Device information        
-- Author  : R.Gopal    
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--    : 11-jun-2009 MJJC Created Intial Version         
/******************************************************************************/        
BEGIN        
         
 IF @vcEquipDescription IS NOT NULL        
 BEGIN        
  SELECT COUNT(*) as 'Result' FROM rvlfMakdevices        
   WHERE         
    ((@bigboxid IS NULL OR @bigboxid='') OR BoxId <> @bigboxid)         
    AND((@Sno IS NULL OR @Sno='') OR Sno <> @Sno)         
    AND EquipmentName = @vcEquipDescription        
    AND OrganizationId = @bigOrganizationID and IsDelete=0       
 END         
 IF @vcEquipDescription IS NULL        
 BEGIN        
  SELECT COUNT(*) as 'Result' FROM rvlfMakdevices        
   WHERE         
      
    ((@Sno IS NULL OR @Sno='') OR Sno <> @Sno)         
    And BoxId = @bigboxid        
    AND OrganizationId = @bigOrganizationID and IsDelete=0     
 END      
END   
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDriverInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_CheckDriverInfo]      
 @bigDriverId bigint = Null,      
 @vcLicenseNo varchar(20)  = Null,      
 @bigOrganizationID bigint = null,      
 @vcDriverDisplayName varchar(10)=null      
AS      
/******************************************************************************/      
-- Name  : [rvlf_sp_CheckDriverInfo]      
-- Description : To check the duplicates in the driver details.      
-- Author  : V.Narayanasamy      
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--    : 10-Jun-2010 VN Created Intial Version       
/******************************************************************************/      
BEGIN      
        
    IF @vcLicenseNo IS NOT NULL      
    BEGIN      
  SELECT COUNT(*) as 'Result' FROM rvlfDriverMaster       
  WHERE      
   (@bigDriverId IS NULL OR @bigDriverId='' OR DriverId <> @bigDriverId)       
   AND LicenseNo  = @vcLicenseNo      
   AND OrganizationId = @bigOrganizationID AND  IsDelete <> 1     
 END      
 IF @vcDriverDisplayName IS NOT NULL      
    BEGIN      
  SELECT COUNT(*) as 'Result' FROM rvlfDriverMaster       
  WHERE      
   (@bigDriverId IS NULL OR @bigDriverId='' OR DriverId <> @bigDriverId)       
   AND DisplayName = @vcDriverDisplayName      
   AND OrganizationId = @bigOrganizationID  AND IsDelete <> 1   
 END      
END   
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateDriverGroupName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateDriverGroupName]  
@bigDriverGroupId BIGINT = NULL,  
@vcDriverGroupName VARCHAR(20),  
@bigOrganizationId BIGINT  
  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_CheckDuplicateDriverGroupName  
-- Description : To Check the duplication of the driver Group Name  
-- Author  : Narayanasamy .V  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 25-Sep-2010 VN  
/******************************************************************************/  
BEGIN  
   
 SELECT ISNULL(COUNT(*),0) FROM rvlfdrivergroupmaster WHERE driverGroupName = @vcDriverGroupName   
  AND (@bigDriverGroupId IS NULL OR @bigDriverGroupId='' OR DriverGroupId <> @bigDriverGroupId) AND OrganizationId = @bigOrganizationId  
    
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateFleetName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateFleetName]  
@bigFleetID bigint = null,  
@vcFleetName varchar(100),  
@bigOrganizationId bigint  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_CheckDuplicateFleetName]  
-- Description : To Check the duplication of the fleet name  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 17-Sep-2009 MJJC Created Intial Version   
/******************************************************************************/  
BEGIN  
 SELECT ISNULL(COUNT(*),0) from rvlfFleet where FleetName = @vcFleetName  
  and (@bigFleetID IS NULL OR @bigFleetID='' Or  FleetId <> @bigFleetID) AND OrganizationId = @bigOrganizationId  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateGeoName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateGeoName]  
 @bigGeozoneNo bigint = null,  
 @vcGeozoneName varchar(50),  
 @bigOrganizationID bigint  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_CheckDuplicateGeoName  
-- Description : To Check the duplication of the geozone name  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 07-Nov-2009 MJJC Created Intial Version   
/******************************************************************************/  
BEGIN  
 SELECT ISNULL(COUNT(*),0) as Result from rvlfOrganizationGeozone where GeozoneName= @vcGeozoneName  
  and OrganizationId = @bigOrganizationID AND (@bigGeozoneNo IS NULL OR @bigGeozoneNo='' Or  GeozoneNo <> @bigGeozoneNo)   
END   
--exec rvlf_sp_CheckDuplicateGeoName 1,'Angler sw',1  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateGeoZoneCategory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateGeoZoneCategory]  
 @CategoryID bigint = null,  
 @categoryName nvarchar(50),  
 @organizationId bigint  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_CheckDuplicateGeoZoneCategory  
-- Description : To Check the duplication of the geozone category name  
-- Author  : Ramya  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 03-Oct-2009  
/******************************************************************************/  
BEGIN  
 SELECT ISNULL(COUNT(*),0) from rvlfCategory where CategoryName = @categoryName  
  and (@CategoryID IS NULL OR @CategoryID='' Or  CategoryId <> @CategoryID) AND OrganizationId = @organizationId  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateLandmarkCategory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateLandmarkCategory]  
 @bigCategoryID bigint = null,  
 @vcCategoryName nvarchar(50),  
 @bigOrganizationID bigint  
AS  
  
/******************************************************************************/  
-- Name  : rvlf_sp_CheckDuplicateLandmarkCategory  
-- Description : To Check the duplication of the landmark category name  
-- Author  : Kumuthini  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 13-Feb-2010 Kumuthini  
/******************************************************************************/  
BEGIN  
  
 SELECT ISNULL(COUNT(*),0) AS Result FROM rvlfLandmarkCategory WHERE CategoryName = @vcCategoryName  
  AND (@bigCategoryID IS NULL OR @bigCategoryID='' OR LandmarkCategoryID <> @bigCategoryID) AND OrganizationId = @bigOrganizationID  
  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateLandmarkName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateLandmarkName]  
 @bigLandmarkID bigint = null,  
 @vcLandmarkName varchar(50),  
 @bigOrganizationID bigint  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_CheckDuplicateLandmarkName  
-- Description : To Check the duplication of the landmark name  
-- Author  : Kumuthini. L  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 03-Feb-2010 Kumuthini Created Intial Version   
/******************************************************************************/  
BEGIN  
  
 SELECT ISNULL(COUNT(*),0) AS Result FROM rvlfLandmark WHERE LandmarkName = @vcLandmarkName  
  AND OrganizationId = @bigOrganizationID AND (@bigLandmarkID IS NULL OR @bigLandmarkID='' OR LandmarkID <> @bigLandmarkID)   
    
END   
-- exec rvlf_sp_CheckDuplicateLandmarkName null,'Landmark 2',1  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateNewsName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateNewsName]  
@bigNewsId BIGINT = NULL,  
@vcNewsName VARCHAR(20),  
@bigOrganizationId BIGINT  
  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_CheckDuplicateNewsName  
-- Description : To Check the duplication of the News Name  
-- Author  : Jeyanthi .S  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 19-Oct-2010 SJ  
/******************************************************************************/  
BEGIN  
   
 SELECT ISNULL(COUNT(*),0) FROM rvlfNews WHERE NewsName = @vcNewsName    
  AND (@bigNewsId IS NULL OR @bigNewsId='' OR NewsId <> @bigNewsId) --AND OrganizationId = @bigOrganizationId  
  AND [Type] <> 'Tips'  
    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateOutput]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateOutput]
	@intBoxID int,
	@vcOutputName varchar(15),
	@tiOutputID tinyint
AS
/******************************************************************************/
--	Name		:	rvlf_sp_CheckDuplicateOutput
--	Description	:	To Check the duplication of the output name
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	30-Nov-2010	LK	Created Intial Version 
/******************************************************************************/
BEGIN

	SELECT ISNULL(COUNT(*),0) AS Result FROM rvlfBoxOutputsCfg WHERE OutputName = @vcOutputName
	 AND BoxId = @intBoxID AND OutputId <> @tiOutputID

END 



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicatePackageName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicatePackageName]  
  
@bigPackageID bigint = null,  
@vcPackageName varchar(100)  
  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_CheckDuplicatePackageName]  
-- Description : To Check the duplication of the package name  
-- Author  : L. Kumuthini  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 30-Nov-2009 Kumuthini Created Intial Version   
/******************************************************************************/  
BEGIN  
 SELECT ISNULL(COUNT(*),0) FROM rvlfPackage WHERE PackageName = @vcPackageName  
  and (@bigPackageID IS NULL OR @bigPackageID='' OR PackageId <> @bigPackageID)  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateROICostName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateROICostName]  
@CostId bigint = null,  
@CostName varchar(100),  
@bigOrganizationId bigint  
AS  
/******************************************************************************/  
-- Name  : [[rvlf_sp_CheckDuplicateROICostName]]  
-- Description : To Check the duplication of the ROI Cost name  
-- Author  : S SAKTHI GOPINATH
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 17-Sep-2009 SAKTHI Created Intial Version   
/******************************************************************************/  
BEGIN  
 SELECT ISNULL(COUNT(*),0) from rvlfROICost where 
 CostName = @CostName  AND (@bigOrganizationId IS NULL OR @bigOrganizationId = 0 OR OrgId=@bigOrganizationId)
  and ((@CostId IS NULL Or @CostId='') OR  Id <> @CostId) AND ISNULL(IsDelete,0)=0
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateRouteName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateRouteName]  
@bigRouteId BIGINT = NULL,  
@vcRouteName VARCHAR(20),  
@bigOrganizationId BIGINT  
  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_CheckDuplicateRouteName]  
-- Description : To Check the duplication of the route name  
-- Author  : Narayanasamy .V  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 26-Sep-2010 VN  
/******************************************************************************/  
BEGIN  
   
 SELECT ISNULL(COUNT(*),0) FROM rvlfRouteMaster WHERE RouteName = @vcRouteName   
  AND (@bigRouteId IS NULL OR @bigRouteId='' OR RouteID <> @bigRouteId) AND OrgID = @bigOrganizationId  
    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateSensor]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateSensor]
	@intBoxID int,
	@vcSensorName varchar(15),
	@tiSensorID tinyint
AS
/******************************************************************************/
--	Name		:	rvlf_sp_CheckDuplicateSensor
--	Description	:	To Check the duplication of the sensor name
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	01-Oct-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
	SELECT ISNULL(COUNT(*),0) as Result from rvlfBoxSensorsCfg  where SensorName = @vcSensorName
	 and BoxId = @intBoxID AND SensorId  <> @tiSensorID
END 


--exec rvlf_sp_CheckDuplicateSensor 999222, 'Door',2


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicatesFleetMaintenance]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicatesFleetMaintenance]  
@bigAutoID bigint = null,  
@vcName varchar(100),  
@ModuleName varchar(25),  
@bigOrganizationId bigint  
  
AS  
/********************************************************************************************/  
-- Name  : [rvlf_sp_CheckDuplicatesFleetMaintenance]  
-- Description : To Check the duplication of the names in the Fleet Maintenance Module  
-- Author  : L. Kumuthini  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
/********************************************************************************************/  
BEGIN  
   
 IF(@ModuleName = 'MainService') -- If Maintenance Service  
 BEGIN  
   
  SELECT ISNULL(COUNT(*),0) FROM rvlfMaintenanceService WHERE ServiceName = @vcName  
   AND (@bigAutoID IS NULL OR @bigAutoID='' OR ServiceId <> @bigAutoID) AND OrganizationId = @bigOrganizationId  
    
 END  
 ELSE IF(@ModuleName = 'ServiceCategory') -- If Maintenance Service Category  
 BEGIN  
   
  SELECT ISNULL(COUNT(*),0) FROM rvlfMaintenanceServiceCategory WHERE ServiceCategoryName = @vcName  
   AND (@bigAutoID IS NULL OR @bigAutoID='' OR ServiceCategoryId <> @bigAutoID) AND OrganizationId = @bigOrganizationId  
    
 END  
 ELSE IF(@ModuleName = 'MaintenancePlan') -- If Maintenance Plan   
 BEGIN  
   
  SELECT ISNULL(COUNT(*),0) FROM rvlfMaintenancePlan WHERE PlanName = @vcName  
   AND (@bigAutoID IS NULL OR @bigAutoID='' OR PlanId <> @bigAutoID) AND OrganizationId = @bigOrganizationId  
    
 END  
    
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateTempName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateTempName]  
@intSeverityTempId int = NULL,  
@vcSeverityTempName nvarchar(50)  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_CheckDuplicateTempName  
-- Description : To Check the duplication of the Template Name  
-- Author  : Jeyanthi .S  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 29-Oct-2010 SJ  
/******************************************************************************/  
BEGIN  
   
 SELECT ISNULL(COUNT(*),0) FROM rvlfSeverityTemplate WHERE SeverityTempName = @vcSeverityTempName    
  AND (@intSeverityTempId IS NULL OR @intSeverityTempId='' OR SeverityTempId <> @intSeverityTempId)   
END  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateTipsName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateTipsName]  
@bigTipsId BIGINT = NULL,  
@vcTipsName VARCHAR(50),  
@bigOrganizationId BIGINT  
  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_CheckDuplicateTipsName  
-- Description : To Check the duplication of the News Name  
-- Author  : Jeyanthi .S  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 21-Oct-2010 SJ  
/******************************************************************************/  
BEGIN  
   
 SELECT ISNULL(COUNT(*),0) FROM rvlfNews WHERE NewsName = @vcTipsName    
  AND (@bigTipsId IS NULL OR @bigTipsId='' OR NewsId <> @bigTipsId) --AND OrganizationId = @bigOrganizationId  
  AND [Type] = 'Tips'  
    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckDuplicateUserGroupName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckDuplicateUserGroupName]  
@bigUserGroupId BIGINT = NULL,  
@vcUserGroupName VARCHAR(30),  
@bigOrganizationId BIGINT  
  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_CheckDuplicateUserGroupName]  
-- Description : To Check the duplication of the User Group Name  
-- Author  : L. Kumuthini  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 01-Dec-2009 Kumuthini.L Created Intial Version   
/******************************************************************************/  
BEGIN  
   
 SELECT ISNULL(COUNT(*),0) FROM rvlfUserGroup WHERE UserGroupName = @vcUserGroupName  
  AND (@bigUserGroupId IS NULL OR @bigUserGroupId='' OR UserGroupId <> @bigUserGroupId) AND OrganizationId = @bigOrganizationId  
    
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_checkEnggedVehicle]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_checkEnggedVehicle]  
(  
@bigRouteId Bigint = NULL,                          
 @dtFromDateTime DateTime = NULL,                          
 @dtToDateTime DateTime = NULL,                          
 @vcVehicleIDs Varchar(500) = NULL,  
 @bigAssignedBy Bigint = NULL,
 @Frequency	tinyint,
 @WeekDays	varchar(15),
 @DayOfMonth	tinyint 
 )
 as  
 /******************************************************************************/                          
-- Name  : rvlf_sp_checkEnggedVehicle 38,'16-feb-16 8:00:00 AM','25-feb-16 8:00:00 PM','5',94,1,null,null
-- Description : To check the vehicle is engaged in the time                     
-- Author  :Gopal  
-- Company  : Angler Technologies                          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                          
--    : 15-jun-2015 Gopal Created Intial Version                          
--                 
/******************************************************************************/    
 begin  
   
 DECLARE @ErrorMessage varchar(3000)                                                  
 DECLARE @Scheduleid bigint=null                           
 DECLARE @HoursToBeAdded INT = 0                          
 DECLARE @MinsToBeAdded INT = 0                          
 DECLARE @RefIds TABLE (RouteId BIGINT,DriverId BIGINT);                
 DECLARE @dtFromDate DATETIME = @dtFromDateTime                          
 DECLARE @dtToDate DATETIME = @dtToDateTime 

  SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded                          
  FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz                          
  ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigAssignedBy                                                    
                           
 SET @dtFromDate = DATEADD(MINUTE,1,DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtFromDate)))     
 SET @dtToDate = DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtToDate))   
    
SELECT * from rvlfRouteVehicleAssignment RVA   
inner join rvlfScheduleOfCommandsMaster SM on RVA.ScheduleId=SM.ScheduleId  
where ((RVA.FromDateTime BETWEEN @dtFromDate AND @dtToDate OR RVA.ToDateTime BETWEEN @dtFromDate AND @dtToDate 
or
 (@dtFromDate BETWEEN RVA.FromDateTime AND RVA.ToDateTime OR @dtToDate BETWEEN RVA.FromDateTime AND RVA.ToDateTime)
) or  
    (SM.EffectiveFrom BETWEEN @dtFromDate AND @dtToDate OR SM.EffectiveTo BETWEEN @dtFromDate AND @dtToDate))
	 and ((cast(RVA.FromDateTime as time) BETWEEN cast(@dtFromDate as time) AND cast(@dtToDate as time) 
	OR cast(RVA.ToDateTime as time) BETWEEN cast(@dtFromDate as time) AND cast(@dtToDate as time)))
    and VehicleId=@vcVehicleIDs and SM.BoxCmdOutTypeId=94 and RVA.Isdelete is null and SM.Isdelete is null 
	--Daily filter
	AND (@Frequency=0 and (rva.Frequency=0 or([DayOfMonth] between datepart(DAY,@dtFromDate) and DATEPART(day,@dtToDate)) or 
	 1<=(select COUNT(*) from  dbo.rvlf_fn_ConvertArrayToTable(rva.WeekDays,',') where FieldValue in (select WeekDays from dbo.rvlf_fn_getWeekday(@dtFromDate,@dtToDate,null)))) 
	 or 
	 --Weekly filter
	   (@Frequency=1 AND (rva.Frequency=0 or 1<=(select COUNT(*) from  dbo.rvlf_fn_ConvertArrayToTable(rva.WeekDays,',') where FieldValue in 
	   (select FieldValue from  dbo.rvlf_fn_ConvertArrayToTable(@WeekDays,','))) or [DayOfMonth] in 
	   (select datepart(day,FieldValue) from dbo.rvlf_fn_getWeekday(@dtFromDate,@dtToDate,@WeekDays)))) OR
	  --Monthly filter
	  (@Frequency=2 AND ([DayOfMonth]=@DayOfMonth or (RVA.Frequency=0 and @DayOfMonth between datepart(DAY,RVA.FromDateTime) and DATEPART(day,RVA.ToDateTime))
	  or (RVA.Frequency=1 and @DayOfMonth in (select Daydate from dbo.rvlf_fn_getWeekday(rva.FromDateTime,rva.ToDateTime,WeekDays)))
	  )))

   
End 


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckFleetName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckFleetName]     
/******************************************************    
Stored Procedure Name : rvlf_sp_CheckFleetName
Purpose     : Check existing fleet name
Created by    : N.Uma Maheswari    
Created date   : 10-Jul-09    
Updated by    :    
Updated date   :    
*******************************************************/    
 
	
@FleetName			varchar(50)		
       
AS  
   
BEGIN     

Select COUNT(*) as FleetCount from  rvlfFleet where FleetName=@FleetName
    
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckIncentiveInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE Procedure [dbo].[rvlf_sp_CheckIncentiveInfo]  
 @bigIncentiveId bigint = Null,  
 @vcVehicletype varchar(5)  = Null,  
 @bigOrganizationID bigint = null,  
 @vcIncentiveName varchar(50)=null  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_CheckIncentiveInfo]null,'HMV',6,'Incentive A'  
-- Description : To check the duplicates in the incentive details.  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 19-Oct-2010 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
    
    IF @vcIncentiveName IS NOT NULL  
    BEGIN  
  SELECT COUNT(*) as 'Result' FROM rvlfDriverBattaDetails   
  WHERE  
   (@bigIncentiveId IS NULL OR @bigIncentiveId='' OR BattaId <> @bigIncentiveId)   
   AND (@vcVehicletype IS NULL OR @vcVehicletype='' OR VehicleType = @vcVehicletype)  
   AND (Description= @vcIncentiveName)  
   AND OrganizationId = @bigOrganizationID  
 END   
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckMDTUserId]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_CheckMDTUserId]      
 @bigUserId bigint = Null,       
 @vcMDTUserId varchar(5)=null,    
 @vcMsg nvarchar(50)=null,    
 @bigMsgId bigint=null,    
 @bitMsgType bit=null,    
 @bigOrganizationId bigint=null,
@IsGarmin bit = 1
AS      
/******************************************************************************/      
-- Name   : [rvlf_sp_CheckMDTUserId]    
-- Description : To check the duplicates in the MDT User Details    
-- Author  : V.Narayanasamy      
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--    : 13-Sep-2011 VN Created Intial Version       
/******************************************************************************/      
BEGIN         
 --check the MDTUserId duplication         
  IF @vcMDTUserId IS NOT NULL      
  BEGIN      
   SELECT COUNT(*) as 'Result' FROM rvlfMDTUserTable        
     WHERE      
      ((@bigUserId IS NULL OR @bigUserId='') OR UserId <> @bigUserId)       
      AND MDTUserId = @vcMDTUserId           
  END      
      
 --check the Precanned message name    
 IF @vcMsg IS NOT NULL      
  BEGIN      
   SELECT COUNT(*) as 'Result' FROM rvlfPrecannedMessages         
     WHERE      
      ((@bigMsgId IS NULL OR @bigMsgId='') OR CannedMsgId <> @bigMsgId)       
      AND MsgName = @vcMsg      
      AND IsServerMsg=@bitMsgType     
      AND OrganizationId=@bigOrganizationId          
  END      
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckMobileNo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckMobileNo]
	(@bigUserid bigint)
AS
/******************************************************************************/
--	Name		:	rvlf_sp_Checkmobileno
--	Description	:	To check the user for getting SMS notificaiton
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	04-Nov-2009	VN	Created Intial Version 
/****************************************************************************/
BEGIN
SET NOCOUNT ON
	IF EXISTS(SELECT SMS FROM rvlfNotificationList WHERE UserID=@bigUserid AND SMS=1)
		BEGIN
			SELECT 1;
		END
	ELSE
		BEGIN
			SELECT 0;
		END
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckOrgRestrictions]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckOrgRestrictions]
	@bigOrganizationID bigint=null,
	@vcType varchar(5)=null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_CheckOrgRestrictions]6,'u' 
--	Description	:	To check the organization restrictions
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	25-Nov-2009	VN	Created Intial Version 
--				:	04-Dec-2009 MJJC Changed the checking by including null for max limit
--				:	01-Feb-2014 Kapil Changed the checking by including Isdelete for users and Limitation >= for max limit
/******************************************************************************/
BEGIN
	DECLARE @intLimitation int 
	DECLARE @intCounter int
	IF(@vcType='F')
		BEGIN
			SELECT @intLimitation = NoOfFleet  FROM rvlfOrganization WHERE OrganizationId=@bigOrganizationID
			SELECT @intCounter = COUNT(*) FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID
		END
	
	IF(@vcType='U')
		BEGIN
			SELECT @intLimitation = NoOfUsers  FROM rvlfOrganization WHERE OrganizationId=@bigOrganizationID
			SELECT @intCounter = COUNT(*) FROM rvlfUser WHERE OrganizationId=@bigOrganizationID and IsDelete =0 and TitleId is not null
		END
	
	IF(@vcType='V')
		BEGIN
			SELECT @intLimitation = NoOfVehicles FROM rvlfOrganization WHERE OrganizationId=@bigOrganizationID
			SELECT @intCounter = COUNT(*) FROM rvlfMAKDevices WHERE OrganizationId=@bigOrganizationID and isdelete=0
		END			
		
			IF(@vcType='L')
		BEGIN
			SELECT @intLimitation = NoOfLandmarks FROM rvlfOrganization WHERE OrganizationId=@bigOrganizationID
			SELECT @intCounter = COUNT(*) FROM rvlfLandmark WHERE OrganizationId=@bigOrganizationID
		END		
			
		IF(@vcType='G')
		BEGIN
			SELECT @intLimitation = NoOfGeozones FROM rvlfOrganization WHERE OrganizationId=@bigOrganizationID
			SELECT @intCounter = COUNT(*) FROM rvlfOrganizationGeozone WHERE OrganizationId=@bigOrganizationID
		END		
	IF((@intLimitation IS NULL) OR (@intLimitation > @intCounter ))
		SELECT 'TRUE' AS RESULT
	ELSE
		SELECT 'FALSE' AS RESULT
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckRefNameDuplicates]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckRefNameDuplicates]          
        
@RefName VARCHAR(30) = NULL ,        
@RefId bigint,    
@bigOrganizationId bigint      
        
          
AS          
/******************************************************************************/          
-- Name  :[rvlf_sp_CheckRefNameDuplicates]         
-- Description : To Check the duplication of the User Group Name          
-- Author  : Kapil          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : 07-May-2014 Kapil Created Intial Version           
/******************************************************************************/          
BEGIN          
           
 SELECT ISNULL(COUNT(*),0)as Result FROM rvlfRefrigeration  WHERE RefgName  = @RefName          
  AND (@RefId IS NULL OR @RefId='' OR RefgId <> @RefId) AND IsDelete=0 and OrganizationId=@bigOrganizationId       
             
            
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckScheduledVehicleReq]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create Procedure [dbo].[rvlf_sp_CheckScheduledVehicleReq]
	@bigEmployeeId bigint = Null,
	@vcRequisitionService varchar(7)=null,
	@dtRequisitionFromDate datetime=null,
	@dtRequisitionToDate datetime=null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_CheckScheduledVehicleReq]415,'both','2010-03-20','2010-03-25'
--	Description	:	To check the requisitions already exists
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	01-Mar-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN
	
	IF @bigEmployeeId IS NOT NULL
		BEGIN
			IF EXISTS(SELECT * FROM rvlfScheduledVehicleRequisition 
								WHERE EmployeeId=@bigEmployeeId 
									AND Closed=0 
									--AND RequisitionService=@vcRequisitionService
									AND(RequisitionFromDate BETWEEN @dtRequisitionFromDate AND @dtRequisitionToDate))									
					BEGIN
						SELECT COUNT(*) as 'Result' FROM rvlfScheduledVehicleRequisition
							WHERE EmployeeId=@bigEmployeeId 
								AND Closed=0 
								--AND RequisitionService=@vcRequisitionService
								AND(RequisitionFromDate BETWEEN @dtRequisitionFromDate AND @dtRequisitionToDate)
					END
				ELSE IF EXISTS(SELECT * FROM rvlfScheduledVehicleRequisition 
								WHERE EmployeeId=@bigEmployeeId 
									AND Closed=0 
									--AND RequisitionService=@vcRequisitionService
									AND(RequisitionToDate BETWEEN @dtRequisitionFromDate AND @dtRequisitionToDate))							
					BEGIN
						SELECT COUNT(*) as 'Result' FROM rvlfScheduledVehicleRequisition
							WHERE EmployeeId=@bigEmployeeId 
								AND Closed=0 
								--AND RequisitionService=@vcRequisitionService
								AND(RequisitionToDate BETWEEN @dtRequisitionFromDate AND @dtRequisitionToDate)	
					END
				ELSE IF EXISTS(SELECT * FROM rvlfScheduledVehicleRequisition 
								WHERE EmployeeId=@bigEmployeeId 
									AND Closed=0 
									--AND RequisitionService=@vcRequisitionService
									AND(RequisitionFromDate >@dtRequisitionFromDate AND RequisitionToDate<@dtRequisitionToDate))
					BEGIN
						SELECT COUNT(*) as 'Result' FROM rvlfScheduledVehicleRequisition
							WHERE EmployeeId=@bigEmployeeId 
								AND Closed=0 
								--AND RequisitionService=@vcRequisitionService
								AND(RequisitionFromDate =@dtRequisitionFromDate AND RequisitionToDate=@dtRequisitionToDate)
					END
				ELSE
					BEGIN
						SELECT 0 as 'Result'
					END
		END
	
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckStudentAvailability]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckStudentAvailability]     
      @StudentId VARCHAR(50)    
AS    
BEGIN    
      SET NOCOUNT ON;        
      IF NOT EXISTS(SELECT * FROM rvlfStudentMaster WHERE StudentID = @StudentId and Active = 1 )    
            SELECT 'true'    
      ELSE    
            SELECT 'false'    
END  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckStudentDataduplicate]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CheckStudentDataduplicate]  
(     @StudentId VARCHAR(300)=null,  
      @organizationid bigint=null,  
      @RFID varchar(300)=null,  
      @Mode int=null  
      )  
AS      
BEGIN      
      SET NOCOUNT ON;          
     if(@Mode =1)  
     Begin  
     Select * from rvlfStudentMaster where OrganizationID =@organizationid and StudentID =@StudentId  
     End  
     else if(@Mode =2)  
     Begin  
     Select * from rvlfStudentMaster where OrganizationID =@organizationid and RFID=@RFID  
     End  
     
      SET NOCOUNT OFF;          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckTyreMakeInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_CheckTyreMakeInfo]  
 @Id int=Null,
 @Name varchar(50) = Null,
 @bigOrganizationId bigint = Null 
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_CheckTyreMakeInfo]null,'MRF'  
-- Description : To check the duplicates in the Car Make and Model details.  
-- Author  : V.Muthukumaravadivel  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 24-Feb-2011 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
    
    IF @Id IS NOT NULL  
    BEGIN  
		 SELECT BrandName FROM rvlfTyreMake   
	  WHERE   
	  ((@Id IS NULL OR @Id = '') OR BrandID <> @Id)   
	  AND BrandName=@Name   
	  and OrganizationId =@bigOrganizationId	  
    
	 SELECT ModelName FROM rvlfTyreModel  TM left JOIN 
	 rvlfTyreMake M on M.BrandID = TM.BrandID	  	 
	 WHERE   
	 ((@Id IS NULL OR @Id = '') OR ModelID <> @Id)   
	  AND ModelName=@Name  	  
	  AND M.organizationId = @bigOrganizationId
	  
      
 END   
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckVehicleCount]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_CheckVehicleCount]   
 @bigOrganizationID bigint = null,  
 @intVehicleCount int =Null   
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_CheckVehicleCount   
-- Description : To check/ modify the vehicle count of the Oganization information  
-- Author  : S. Jeyanthi.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 29-Oct-2010 SJ Created Intial Version   
/******************************************************************************/  
BEGIN  
   
 DECLARE @intVehicleAvailable int=0  
   
 IF @bigOrganizationID IS NOT NULL  
 BEGIN  
  SET @intVehicleAvailable = (SELECT COUNT(VehicleId) FROM rvlfVehicle    
  WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId = @bigOrganizationID))   
    
  IF @intVehicleAvailable <= @intVehicleCount  
   BEGIN  
    SELECT 0 As Result  
   END  
  ELSE  
   BEGIN  
    SELECT 1 As Result  
   END     
 END  
   
END  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CheckVehicleInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_CheckVehicleInfo]  
 @bigVehicleId bigint = Null,  
 @vcVehicleDescription varchar(50) = null,  
 @vcVIN varchar(20)  = Null,  
 @vcLicensePlate varchar(20)  = Null,  
 @bigOrganizationID bigint = null,  
 @vehicleDisplayName varchar(10)=null  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_CheckVehicleInfo  
-- Description : To check the vehicle information  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 28-Sep-2009 MJJC Created Intial Version   
-- Updated by : V.Narayanasamy on 19-nov-2009 adding displayname checking  
/******************************************************************************/  
BEGIN  
   
 IF @vcVehicleDescription IS NOT NULL  
 BEGIN  
  SELECT COUNT(*) as 'Result' FROM rvlfVehicle  
   WHERE   
    (@bigVehicleId IS NULL OR @bigVehicleId='' OR VehicleId <> @bigVehicleId)   
    AND VehicleDescription = @vcVehicleDescription  
    AND OrganizationId = @bigOrganizationID  
 END  
 IF @vcVIN IS NOT NULL  
 BEGIN  
  SELECT COUNT(*) as 'Result' FROM rvlfVehicle  
   WHERE  
    (@bigVehicleId IS NULL OR @bigVehicleId='' OR VehicleId <> @bigVehicleId)   
    AND Vin = @vcVIN  
    AND OrganizationId = @bigOrganizationID  
 END  
    IF @vcLicensePlate IS NOT NULL  
    BEGIN  
  SELECT COUNT(*) as 'Result' FROM rvlfVehicle   
  WHERE  
   (@bigVehicleId IS NULL OR @bigVehicleId='' OR VehicleId <> @bigVehicleId)   
   AND LicensePlate = @vcLicensePlate  
   AND OrganizationId = @bigOrganizationID  
 END  
 IF @vehicleDisplayName IS NOT NULL  
    BEGIN  
  SELECT COUNT(*) as 'Result' FROM rvlfVehicle   
  WHERE  
   (@bigVehicleId IS NULL OR @bigVehicleId='' OR VehicleId <> @bigVehicleId)   
   AND DisplayName = @vehicleDisplayName  
   AND OrganizationId = @bigOrganizationID  
 END  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CustomerAssignment]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_CustomerAssignment]
@AssignmentId BIGINT = NULL,
@AssignmentDate DATETIME = NULL,
@FromDate DATETIME = NULL,
@ToDate DATETIME = NULL,
@CustomerId INT = NULL,
@VehicleId BIGINT = NULL,
@DriverId BIGINT = NULL,
@BoxId VARCHAR(15) = NULL,
@Location VARCHAR(100) = NULL,
@nOrganizationId INT = NULL,
@nUserId INT = NULL,
@Operation TINYINT = NULL


AS
/******************************************************************************/  
-- Procedure 	: rvlf_sp_CustomerAssignment
-- Description	: To save, Update & Delete the Customer Assignment 
-- Author		: T Kanimozhi
-- Company		: Trinetra wireless (P) Ltd.
-- History		: <<Date(dd-MON-yyyy)>> Initial Reason  
--				: 07-June-2018 TK Created Intial Version   
/******************************************************************************/  
BEGIN
SET NOCOUNT ON
	IF @Operation = 1
	BEGIN
	INSERT INTO dbo.rvlfCustomerAssignment(CustomerId, VehicleId, FromDate, ToDate, Location, OrgId, ModifiedBy, CreatedDate, IsDelete)
		VALUES( @CustomerId, @VehicleId, @FromDate, @ToDate, @Location, @nOrganizationId,@nUserId,GETUTCDATE(),0)
	END
	ELSE IF @Operation = 2
	BEGIN
		UPDATE dbo.rvlfCustomerAssignment SET  CustomerId=@CustomerId, VehicleId= @VehicleId, FromDate=@FromDate, ToDate=@ToDate, Location=@Location,  
		OrgId = @nOrganizationId,ModifiedBy = @nUserId,ModifiedDate = GETUTCDATE(),IsDelete=0
		WHERE AssignmentId = @AssignmentId
	END
	ELSE IF @Operation = 3
	BEGIN
		Update dbo.rvlfCustomerAssignment SET IsDelete=1 WHERE AssignmentId = @AssignmentId
	END	
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CustomerFilterddl]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- rvlf_sp_CustomerFilterddl 87,247,86,458,176,'Customer'
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_CustomerFilterddl]
	-- Add the parameters for the stored procedure here
	@CustomerID BIGINT =null,
	@SiteID bigint =null,
	@OrgId BIGINT =null,
	@UserID BIGINT =null,
	@defaultFleet int=null,
	@FlagType varchar(20)=null,
	@EnableAlloption bit=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Customer Details

	DECLARE @varUserName AS Varchar(30)
		DECLARE @bigOrganizationId AS BIGINT
		if(@EnableAlloption is null)
		begin
			set @EnableAlloption=0
		end
		declare @DefaultFleetID bigint
		declare @AllFleet int=null
		SELECT @bigOrganizationId = u.OrganizationId, @varUserName = u.UserName FROM rvlfUser u
		WHERE u.UserId = @UserId
		select @DefaultFleetID=isnull(DefaultFleetId,0) from rvlfUserPreferences where UserId=@UserID
		declare @table table (ID int identity(1,1),FleetId nvarchar(100),FleetName nvarchar(100),IsDefault bit,DefaultFleetID bigint)
	
	IF(@varUserName = 'Administrator')
    BEGIN
	 SELECT f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleet f
	 WHERE f.OrganizationId = @bigOrganizationId	 
	END
	ELSE
	BEGIN
	  SELECT f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleetUsers fu
	  INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
	  WHERE UserId = @UserId
	END


		--DECLARE @varUserName AS Varchar(30)
		--DECLARE @bigOrganizationId AS BIGINT
		--if(@EnableAlloption is null)
		--begin
		--	set @EnableAlloption=0
		--end
		--declare @DefaultFleetID bigint
		--declare @AllFleet int=null
		--SELECT @bigOrganizationId = u.OrganizationId, @varUserName = u.UserName FROM rvlfUser u
		--WHERE u.UserId = @UserId
		--select @DefaultFleetID=isnull(DefaultFleetId,0) from rvlfUserPreferences where UserId=@UserID
		--declare @table table (ID int identity(1,1),FleetId nvarchar(100),FleetName nvarchar(100),IsDefault bit,DefaultFleetID bigint)
		--IF(@varUserName = 'Administrator')
		--	BEGIN
		--		SELECT distinct f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleet f inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
		--			inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
		--		WHERE f.OrganizationId = @bigOrganizationId
		--			and  (@CustomerID IS NULL OR @CustomerID = 0 OR @CustomerID = '' OR  (md.CustomerId = @CustomerID and f.FleetName !='All')) 

		--	END
		--ELSE
		--	BEGIN
		--		if(@FlagType='Customer')
		--		begin
		--			if((select FleetId from rvlfFleet f where f.OrganizationId=@OrgId and f.FleetName ='All')=@defaultFleet)
		--			begin
		--				set @AllFleet=1
		--			end
		--			if(@SiteID is not null)
		--				begin
		--					set @defaultFleet=@SiteID
		--				end
		--			if(@CustomerID is null)
		--				begin
		--					SELECT @CustomerID=md.CustomerId FROM rvlfFleetUsers fu
		--					INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
		--					inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
		--					inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
		--					WHERE UserId = @UserId and (@AllFleet IS not NULL OR f.FleetName !='All')  and f.FleetId=@defaultFleet and MD.OrganizationId =@OrgId
		--				end
		--			if(@CustomerID=0)
		--				begin
		--					set @CustomerID=0
		--				end
		--			if(@EnableAlloption=1)
		--				begin
		--					select 0 as CustomerId, 'All' as CustomerName, '' as CustomerDesc ,'' as  CustomerCode , '' as MobileNo , '' as Email , '' as CustomerLocation ,'' as phNo,@CustomerID  as defaultCus 
		--					union all
		--					SELECT CustomerId, CustomerName, CustomerDesc ,  CustomerCode , MobileNo ,Email ,CustomerLocation ,phNo,@CustomerID  as defaultCus FROM rvlfCustomers WHERE (OrgId = @OrgId) and IsDelete=0 and CustomerId in (SELECT md.CustomerId FROM rvlfFleetUsers fu
		--						INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
		--						inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
		--						inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
		--						WHERE UserId = @UserId and f.FleetId<>176) ORDER BY CustomerName
		--				end
		--			else
		--				begin
		--					SELECT CustomerId, CustomerName, CustomerDesc ,  CustomerCode , MobileNo ,Email ,CustomerLocation ,phNo,@CustomerID  as defaultCus FROM rvlfCustomers WHERE (OrgId = @OrgId) and IsDelete=0 and CustomerId in (SELECT md.CustomerId FROM rvlfFleetUsers fu
		--						INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
		--						inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
		--						inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
		--						WHERE UserId = @UserId and f.FleetId<>176) ORDER BY CustomerName
		--				end
		--			if(@EnableAlloption=1 and @CustomerID=0)
		--				begin
		--					select 1 as ID,0 as FleetId,'All' as FleetName,'1' as IsDefault,'0' as DefaultFleetID

		--					SELECT 0 as VehicleId,'' as Vin, '' as LicensePlate, '' as MakeId, '' as ModelId, '' as MakeName, '' as ModelName,'' as VehicleTypeId, '' as VehicleTypeName, '' as StateProvince, '' as ModelYear, '' as Color,'All' as VehicleDescription,'' as IconTypeId, '' as VehicleTimeZone,'' as VehicleDayLightSaving, '' as VehicleEmail,'' as VehicleSMS, '' as VehicleNotify, '' as VehicleCritical,'' as VehicleWarning , '' as VehicleAutoAdjust,'' as FleetId, '' as FleetName, '' as OrganizationId, '' as FleetDesc,'' as FleetEmail, '' as FleetSMS, '' as FleetTimezone,'' as FleetDayLightSaving, '' as FleetNotify,'' as FleetWarning , '' as FleetCritical ,'' as FleetAutoAdjust, '' as  OrganizationName,'' as BoxId, '' as VehicleName,'' as CustomerId,'' as EConsumptionType
							
		--				end
		--			else
		--				begin
		--					insert into @table
		--					select FleetId,FleetName,IsDefault,@DefaultFleetID from (
		--						SELECT distinct f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleetUsers fu
		--						INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
		--						inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
		--						inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
		--						WHERE UserId = @UserId and  
		--						(@CustomerID IS NULL OR @CustomerID = 0 OR @CustomerID = '' OR  (md.CustomerId = @CustomerID and (@AllFleet IS not NULL OR f.FleetName !='All')) ) and f.FleetId=@defaultFleet
		--						union all
		--						SELECT distinct f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleetUsers fu
		--						INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
		--						inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
		--						inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
		--						WHERE UserId = @UserId  and  
		--						(@CustomerID IS NULL OR @CustomerID = 0 OR @CustomerID = '' OR  (md.CustomerId = @CustomerID and (@AllFleet IS not NULL OR f.FleetName !='All')) ) and f.FleetId not in (@defaultFleet)
		--					) as a 

		--					select * from @table

		--					SELECT distinct  
		--					v.VehicleId, v.Vin, v.LicensePlate, v.MakeId, v.ModelId, '' as MakeName, '' as ModelName,  
		--					v.VehicleTypeId, t.VehicleTypeName, v.StateProvince, v.ModelYear, v.Color,  
		--					v.VehicleDescription, v.IconTypeId, v.TimeZone as VehicleTimeZone,  
		--					v.DayLightSaving as VehicleDayLightSaving, v.Email as VehicleEmail,  
		--					v.SMS as VehicleSMS, v.Notify as VehicleNotify, v.Critical as VehicleCritical,  
		--					v.Warning as VehicleWarning , v.AutoAdjustDayLightSaving as VehicleAutoAdjust,  
		--					f.FleetId, f.FleetName, f.OrganizationId, f.[Description] as FleetDesc,  
		--					f.Email as FleetEmail, f.SMS as FleetSMS, f.TimeZone as FleetTimezone,  
		--					f.DayLightSaving as FleetDayLightSaving, f.Notify as FleetNotify,  
		--					f.Warning as FleetWarning , f.Critical as FleetCritical ,   
		--					f.AutoAdjustDayLightSaving as FleetAutoAdjust, g.OrganizationName,  
		--					MD.BoxId, v.VehicleDescription as VehicleName,MD.CustomerId,md.EConsumptionType,BI.LastCommunicatedDateTime,isnull(MD.VFantype,0) as VFantype
		--					FROM rvlfVehicle v  
		--					Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
		--					inner join rvlfBoxId BI on BI.BoxId=MD.BoxId
		--					--INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId   
		--					INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
		--					INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
		--					INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
		--					inner join @table FLT on FLT.FleetId=f.FleetId
		--					-- LEFT OUTER JOIN rvlfMake m ON v.MakeId = m.MakeId  
		--					-- LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId  
		--					INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
		--					WHERE  
		--					--va.IsDeleted = 0 AND   
		--					(@CustomerID IS NULL OR @CustomerID='' OR MD.CustomerId =@CustomerID) AND  
		--					(@SiteID IS NULL OR @SiteID='' OR f.FleetId =@SiteID) AND  
		--					f.FleetId =(case when (@SiteID is null) then (select top 1 FleetId from @table) else f.FleetId end) and
		--					(@OrgId IS NULL OR @OrgId='' OR g.OrganizationId= @OrgId) and (@AllFleet IS not NULL OR f.FleetName !='All') 
		--					ORDER BY BI.LastCommunicatedDateTime desc
		--				end
					
		--		end
		--		else
		--		begin
					
		--			if((select FleetId from rvlfFleet f where f.OrganizationId=@OrgId and  f.FleetName ='All')=@defaultFleet)
		--			begin
		--				set @AllFleet=1
		--			end

		--			if(@SiteID is not null)
		--				begin
		--					set @defaultFleet=@SiteID
		--				end
					
		--			SELECT CustomerId, CustomerName, CustomerDesc ,  CustomerCode , MobileNo ,Email ,CustomerLocation ,phNo,@CustomerID  as defaultCus FROM rvlfCustomers WHERE (OrgId = @OrgId) and IsDelete=0  ORDER BY CustomerName
		--			insert into @table
		--			select FleetId,FleetName,IsDefault,@DefaultFleetID from (
		--			SELECT distinct f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleetUsers fu
		--			INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
		--			inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
		--			inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
		--			WHERE UserId = @UserId 
		--			and  (@AllFleet IS not NULL OR f.FleetName !='All') and f.FleetId=@defaultFleet
		--			union all
		--			SELECT distinct f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleetUsers fu
		--			INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
		--			inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
		--			inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
		--			WHERE UserId = @UserId and (@AllFleet IS not NULL OR f.FleetName !='All') and f.FleetId not in (@defaultFleet)) as a

		--			select * from @table

		--			declare @lastname nvarchar(100)
		--			select @lastname=LastName from rvlfUser where UserId=@UserID
					
		--			SELECT distinct  
		--					v.VehicleId, v.Vin, v.LicensePlate, v.MakeId, v.ModelId, '' as MakeName, '' as ModelName,  
		--					v.VehicleTypeId, t.VehicleTypeName, v.StateProvince, v.ModelYear, v.Color,  
		--					v.VehicleDescription, v.IconTypeId, v.TimeZone as VehicleTimeZone,  
		--					v.DayLightSaving as VehicleDayLightSaving, v.Email as VehicleEmail,  
		--					v.SMS as VehicleSMS, v.Notify as VehicleNotify, v.Critical as VehicleCritical,  
		--					v.Warning as VehicleWarning , v.AutoAdjustDayLightSaving as VehicleAutoAdjust,  
		--					f.FleetId, f.FleetName, f.OrganizationId, f.[Description] as FleetDesc,  
		--					f.Email as FleetEmail, f.SMS as FleetSMS, f.TimeZone as FleetTimezone,  
		--					f.DayLightSaving as FleetDayLightSaving, f.Notify as FleetNotify,  
		--					f.Warning as FleetWarning , f.Critical as FleetCritical ,   
		--					f.AutoAdjustDayLightSaving as FleetAutoAdjust, g.OrganizationName,  
		--					MD.BoxId, v.VehicleDescription as VehicleName,MD.CustomerId,md.EConsumptionType,BI.LastCommunicatedDateTime,isnull(MD.VFantype,0) as VFantype
		--			FROM rvlfVehicle v  
		--			Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
		--			inner join rvlfBoxId BI on BI.BoxId=MD.BoxId
		--			INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
		--			INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
		--			INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
		--			INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
		--			WHERE  
		--			(@SiteID IS NULL OR @SiteID='' OR f.FleetId =@SiteID) AND  
		--			f.FleetId =(case when (@SiteID is null) then (select top 1 FleetId from @table) else f.FleetId end) and
		--			(@OrgId IS NULL OR @OrgId='' OR g.OrganizationId= @OrgId)  and md.CustomerName=@lastname
		--			ORDER BY BI.LastCommunicatedDateTime desc
		--			--SELECT distinct  
		--			--v.VehicleId, v.Vin, v.LicensePlate, v.MakeId, v.ModelId, '' as MakeName, '' as ModelName,  
		--			--v.VehicleTypeId, t.VehicleTypeName, v.StateProvince, v.ModelYear, v.Color,  
		--			--v.VehicleDescription, v.IconTypeId, v.TimeZone as VehicleTimeZone,  
		--			--v.DayLightSaving as VehicleDayLightSaving, v.Email as VehicleEmail,  
		--			--v.SMS as VehicleSMS, v.Notify as VehicleNotify, v.Critical as VehicleCritical,  
		--			--v.Warning as VehicleWarning , v.AutoAdjustDayLightSaving as VehicleAutoAdjust,  
		--			--f.FleetId, f.FleetName, f.OrganizationId, f.[Description] as FleetDesc,  
		--			--f.Email as FleetEmail, f.SMS as FleetSMS, f.TimeZone as FleetTimezone,  
		--			--f.DayLightSaving as FleetDayLightSaving, f.Notify as FleetNotify,  
		--			--f.Warning as FleetWarning , f.Critical as FleetCritical ,   
		--			--f.AutoAdjustDayLightSaving as FleetAutoAdjust, g.OrganizationName,  
		--			--MD.BoxId, v.VehicleDescription as VehicleName,MD.CustomerId
		--			--FROM rvlfVehicle v  
		--			--Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
		--			----INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId   
		--			--INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
		--			--INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
		--			--INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
		--			---- LEFT OUTER JOIN rvlfMake m ON v.MakeId = m.MakeId  
		--			---- LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId  
		--			--INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
		--			--WHERE  
		--			----va.IsDeleted = 0 AND   
		--			--(@defaultFleet IS NULL OR @defaultFleet='' OR f.FleetId =@defaultFleet) AND  
		--			--(@OrgId IS NULL OR @OrgId='' OR g.OrganizationId= @OrgId)  
		--			--ORDER BY v.VehicleDescription ASC
		--		end
		--	END
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CustomerFilterddl_karthick]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- rvlf_sp_CustomerFilterddl 87,247,86,458,176,'Customer'
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_CustomerFilterddl_karthick]
	-- Add the parameters for the stored procedure here
	@CustomerID BIGINT =null,
	@SiteID bigint =null,
	@OrgId BIGINT =null,
	@UserID BIGINT =null,
	@defaultFleet int=null,
	@FlagType varchar(20)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Customer Details
	select 'IN'
		DECLARE @varUserName AS Varchar(30)
		DECLARE @bigOrganizationId AS BIGINT
		declare @AllFleet int=null
		SELECT @bigOrganizationId = u.OrganizationId, @varUserName = u.UserName FROM rvlfUser u
		WHERE u.UserId = @UserId
		declare @table table (ID int identity(1,1),FleetId nvarchar(100),FleetName nvarchar(100),IsDefault bit)
		
		IF(@varUserName = 'Administrator')
			BEGIN
				SELECT distinct f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleet f inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
					inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
				WHERE f.OrganizationId = @bigOrganizationId
					and  (@CustomerID IS NULL OR @CustomerID = 0 OR @CustomerID = '' OR  (md.CustomerId = @CustomerID and f.FleetName !='All')) 
			END
		ELSE
			BEGIN
			select 'IN'
				if(@FlagType='Customer')
				begin
					if((select FleetId from rvlfFleet f where f.OrganizationId=@OrgId and f.FleetName ='All')=@defaultFleet)
					begin
						set @AllFleet=1
					end
					if(@SiteID is not null)
						begin
							set @defaultFleet=@SiteID
						end
					if(@CustomerID is null)
						begin
							SELECT @CustomerID=md.CustomerId FROM rvlfFleetUsers fu
							INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
							inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
							inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
							WHERE UserId = @UserId and (@AllFleet IS not NULL OR f.FleetName !='All')  and f.FleetId=@defaultFleet
						end
					SELECT CustomerId, CustomerName, CustomerDesc ,  CustomerCode , MobileNo ,Email ,CustomerLocation ,phNo,@CustomerID  as defaultCus FROM rvlfCustomers WHERE (OrgId = @OrgId) and IsDelete=0 and CustomerId in (SELECT md.CustomerId FROM rvlfFleetUsers fu
						INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
						inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
						inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
						WHERE UserId = @UserId and f.FleetId<>176) ORDER BY CustomerName
					
					insert into @table
					select FleetId,FleetName,IsDefault from (
						SELECT distinct f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleetUsers fu
						INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
						inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
						inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
						WHERE UserId = @UserId and  
						(@CustomerID IS NULL OR @CustomerID = 0 OR @CustomerID = '' OR  (md.CustomerId = @CustomerID and (@AllFleet IS not NULL OR f.FleetName !='All')) ) and f.FleetId=@defaultFleet
						union all
						SELECT distinct f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleetUsers fu
						INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
						inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
						inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
						WHERE UserId = @UserId  and  
						(@CustomerID IS NULL OR @CustomerID = 0 OR @CustomerID = '' OR  (md.CustomerId = @CustomerID and (@AllFleet IS not NULL OR f.FleetName !='All')) ) and f.FleetId not in (@defaultFleet)
					) as a 

					select * from @table

					SELECT distinct  
					v.VehicleId, v.Vin, v.LicensePlate, v.MakeId, v.ModelId, '' as MakeName, '' as ModelName,  
					v.VehicleTypeId, t.VehicleTypeName, v.StateProvince, v.ModelYear, v.Color,  
					v.VehicleDescription, v.IconTypeId, v.TimeZone as VehicleTimeZone,  
					v.DayLightSaving as VehicleDayLightSaving, v.Email as VehicleEmail,  
					v.SMS as VehicleSMS, v.Notify as VehicleNotify, v.Critical as VehicleCritical,  
					v.Warning as VehicleWarning , v.AutoAdjustDayLightSaving as VehicleAutoAdjust,  
					f.FleetId, f.FleetName, f.OrganizationId, f.[Description] as FleetDesc,  
					f.Email as FleetEmail, f.SMS as FleetSMS, f.TimeZone as FleetTimezone,  
					f.DayLightSaving as FleetDayLightSaving, f.Notify as FleetNotify,  
					f.Warning as FleetWarning , f.Critical as FleetCritical ,   
					f.AutoAdjustDayLightSaving as FleetAutoAdjust, g.OrganizationName,  
					MD.BoxId, v.VehicleDescription as VehicleName,MD.CustomerId,md.EConsumptionType
					FROM rvlfVehicle v  
					Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
					--INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId   
					INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
					INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
					INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
					inner join @table FLT on FLT.FleetId=f.FleetId
					-- LEFT OUTER JOIN rvlfMake m ON v.MakeId = m.MakeId  
					-- LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId  
					INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
					WHERE  
					--va.IsDeleted = 0 AND   
					(@CustomerID IS NULL OR @CustomerID='' OR MD.CustomerId =@CustomerID) AND  
					(@SiteID IS NULL OR @SiteID='' OR f.FleetId =@SiteID) AND  
					f.FleetId =(case when (@SiteID is null) then (select top 1 FleetId from @table) else f.FleetId end) and
					(@OrgId IS NULL OR @OrgId='' OR g.OrganizationId= @OrgId) and (@AllFleet IS not NULL OR f.FleetName !='All') 
					ORDER BY v.VehicleDescription ASC
				end
				else
				begin
					
					if((select FleetId from rvlfFleet f where f.OrganizationId=@OrgId and  f.FleetName ='All')=@defaultFleet)
					begin
						set @AllFleet=1
					end

					if(@SiteID is not null)
						begin
							set @defaultFleet=@SiteID
						end
					
					SELECT CustomerId, CustomerName, CustomerDesc ,  CustomerCode , MobileNo ,Email ,CustomerLocation ,phNo,@CustomerID  as defaultCus FROM rvlfCustomers WHERE (OrgId = @OrgId) and IsDelete=0  ORDER BY CustomerName
					insert into @table
					select FleetId,FleetName,IsDefault from (
					SELECT distinct f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleetUsers fu
					INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
					inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
					inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
					WHERE UserId = @UserId 
					and  (@AllFleet IS not NULL OR f.FleetName !='All') and f.FleetId=@defaultFleet
					union all
					SELECT distinct f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleetUsers fu
					INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
					inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
					inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
					WHERE UserId = @UserId and (@AllFleet IS not NULL OR f.FleetName !='All') and f.FleetId not in (@defaultFleet)) as a

					select * from @table

					declare @lastname nvarchar(100)
					select @lastname=LastName from rvlfUser where UserId=@UserID
					
					SELECT distinct  
					v.VehicleId, 
					v.VehicleTypeId, t.VehicleTypeName,
					v.VehicleDescription, 
					MD.BoxId, v.VehicleDescription as VehicleName,md.EConsumptionType
					FROM rvlfVehicle v  
					Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
					INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
					INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
					INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
					INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
					WHERE  
					(@SiteID IS NULL OR @SiteID='' OR f.FleetId =@SiteID) AND  
					f.FleetId =(case when (@SiteID is null) then (select top 1 FleetId from @table) else f.FleetId end) and
					(@OrgId IS NULL OR @OrgId='' OR g.OrganizationId= @OrgId)  and md.CustomerName=@lastname
					ORDER BY v.VehicleDescription ASC
					--SELECT distinct  
					--v.VehicleId, v.Vin, v.LicensePlate, v.MakeId, v.ModelId, '' as MakeName, '' as ModelName,  
					--v.VehicleTypeId, t.VehicleTypeName, v.StateProvince, v.ModelYear, v.Color,  
					--v.VehicleDescription, v.IconTypeId, v.TimeZone as VehicleTimeZone,  
					--v.DayLightSaving as VehicleDayLightSaving, v.Email as VehicleEmail,  
					--v.SMS as VehicleSMS, v.Notify as VehicleNotify, v.Critical as VehicleCritical,  
					--v.Warning as VehicleWarning , v.AutoAdjustDayLightSaving as VehicleAutoAdjust,  
					--f.FleetId, f.FleetName, f.OrganizationId, f.[Description] as FleetDesc,  
					--f.Email as FleetEmail, f.SMS as FleetSMS, f.TimeZone as FleetTimezone,  
					--f.DayLightSaving as FleetDayLightSaving, f.Notify as FleetNotify,  
					--f.Warning as FleetWarning , f.Critical as FleetCritical ,   
					--f.AutoAdjustDayLightSaving as FleetAutoAdjust, g.OrganizationName,  
					--MD.BoxId, v.VehicleDescription as VehicleName,MD.CustomerId
					--FROM rvlfVehicle v  
					--Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
					----INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId   
					--INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
					--INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
					--INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
					---- LEFT OUTER JOIN rvlfMake m ON v.MakeId = m.MakeId  
					---- LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId  
					--INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
					--WHERE  
					----va.IsDeleted = 0 AND   
					--(@defaultFleet IS NULL OR @defaultFleet='' OR f.FleetId =@defaultFleet) AND  
					--(@OrgId IS NULL OR @OrgId='' OR g.OrganizationId= @OrgId)  
					--ORDER BY v.VehicleDescription ASC
				end
			END
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_CustomerInfoOpr]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_CustomerInfoOpr]   
(  
	@CustomerId		BIGINT		 =	null,	                        
	@OrgId			BIGINT		 =	null,                        
	@UserID			BIGINT		 =	null,  
	@CustomerName	VARCHAR(50)	 =	null, 
	@CustomerDesc   VARCHAR(300) =	null, 
	@CustomerCode   VARCHAR(30)  =	null, 
	@Email          VARCHAR(50)  =	null, 
	@MobileNo       VARCHAR(15)  =	null, 
	@phNo       VARCHAR(15)  =	null, 
	@Location		VARCHAR(300) =	null,   
	@Operation		VARCHAR(20)  = null 
)  
AS  
BEGIN  
	IF(@Operation = 'Insert')
	BEGIN	  
		INSERT INTO rvlfCustomers (CustomerName, CustomerDesc, CustomerCode, MobileNo, Email, CustomerLocation, OrgId, CreatedBy, CreatedDate, IsDelete,phNo)
		VALUES (@CustomerName, @CustomerDesc,@CustomerCode,@MobileNo,@Email,@Location,@OrgId,@UserID,GETDATE(),0,@phNo) 
		SELECT 'Customer details saved successfully'
	END 
	ELSE if(@Operation = 'Update')
	BEGIN
		update rvlfUser set LastName=@CustomerName where LastName=(select CustomerName from rvlfCustomers where CustomerId=@CustomerId)
		UPDATE rvlfCustomers Set CustomerName = @CustomerName, CustomerDesc = @CustomerDesc, CustomerCode = @CustomerCode, MobileNo = @MobileNo, Email = @Email, CustomerLocation = @Location, ModifiedBy = @UserID, ModifiedDate = GETDATE(),phNo=@phNo
		WHERE CustomerId = @CustomerId
		update rvlfMAKDevices set CustomerName=@CustomerName where CustomerId=@CustomerId
		SELECT 'Customer details updated successfully'
	END
	ELSE if(@Operation = 'Delete')
	BEGIN
		IF(EXISTS(Select BoxId From rvlfMAKDevices Where CustomerId = @CustomerId and IsDelete = 0))
			SELECT 'Customer cannot be deleted as it is already assigned to an Equipment'
		ELSE if(EXISTS(Select UserId From rvlfUser Where CustomerId = @CustomerId and IsDelete = 0))
			begin
				SELECT 'Customer cannot be deleted as it is already assigned to an user'
			end
		else
		BEGIN
			UPDATE rvlfCustomers Set IsDelete = 1, ModifiedBy = @UserID, ModifiedDate = GETDATE()
			WHERE CustomerId = @CustomerId  
			SELECT 'Customer details deleted successfully'
		END
	END
	ELSE 
	BEGIN 	    
		if(@Operation='Customer')
			begin
				SELECT CustomerId, CustomerName, CustomerDesc ,  CustomerCode , MobileNo ,Email ,CustomerLocation ,phNo
	FROM rvlfCustomers
			WHERE	(@CustomerName is null or @CustomerName ='' or  CustomerName = @CustomerName) and ( @CustomerId is null or @CustomerId ='' or CustomerId = @CustomerId) 
			AND     (OrgId = @OrgId) and IsDelete=0 and CustomerId in (SELECT md.CustomerId FROM rvlfFleetUsers fu
							INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
							inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
							inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
							WHERE UserId = @UserID and f.FleetId<>176)
			ORDER BY CustomerName
			end
		else
			begin
				SELECT CustomerId, CustomerName, CustomerDesc ,  CustomerCode , MobileNo ,Email ,CustomerLocation ,phNo
	FROM rvlfCustomers
			WHERE	(@CustomerName is null or @CustomerName ='' or  CustomerName = @CustomerName) and ( @CustomerId is null or @CustomerId ='' or CustomerId = @CustomerId) 
			AND     (OrgId = @OrgId) and IsDelete=0 
			ORDER BY CustomerName
			end
		
	END
END 

 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DelayNotificationForGeozone]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================                  
-- Author:  Vijay.N                  
-- Create date: <Create Date,,>                  
-- Description: Get the delay notification details for the organizations.                
-- =============================================                  
CREATE PROCEDURE [dbo].[rvlf_sp_DelayNotificationForGeozone]                  
 -- Add the parameters for the stored procedure here                   
AS                  
BEGIN                  
-- SET NOCOUNT ON added to prevent extra result sets from                  
-- interfering with SELECT statements.                  
 SET NOCOUNT ON;                  
                  
-- Insert statements for procedure here                  
DECLARE @TBLGeo AS TABLE                  
(                   
[INDEX] INT IDENTITY PRIMARY KEY,                  
Boxid INT,                  
GeozoneID INT,                  
GeozoneNo INT,                  
Vehiclename VARCHAR(500),                  
SchoolName_EN VARCHAR(500),                  
DriverName VARCHAR(250),                  
SchoolArrivalTime TIME,                  
RecurrenceDays VARCHAR(15),                
TripNo TinyInt,                
IsBusReached BIT                
)                  
                  
                  
INSERT INTO @TBLGeo (Boxid,GeozoneID,GeozoneNo,Vehiclename,SchoolName_EN,DriverName,SchoolArrivalTime,RecurrenceDays,TripNo)                  
SELECT Boxids,GeoId,OG.GeozoneNo,v.VehicleDescription,OG.geozoneName,'Driver',TripTime,Recurrence,TripNo FROM                
(SELECT Boxids,GeoId,DATEADD(MINUTE,TripTimeGrace,TripTime) AS TripTime,MailStatus,Recurrence,TripNo FROM rvlfDelayNotify CROSS APPLY(VALUES(boxid,GeozoneId,Trip1time,Trip1Gracetime,Trip1MailStatus,RecurrenceDays,1),                   
(boxid,GeozoneId,Trip2time,Trip2Gracetime,Trip2MailStatus,RecurrenceDays,2),(boxid,GeozoneId,Trip3time,Trip3Gracetime,Trip3MailStatus,RecurrenceDays,3)) x (Boxids,GeoId,TripTime,TripTimeGrace,MailStatus,Recurrence,TripNo)) AS DN                    
INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId = DN.Boxids                  
INNER JOIN rvlfVehicleGeozone VG ON VG.VehicleId = VA.VehicleId AND VG.GeozoneNo = DN.GeoId                
INNER JOIN rvlfVehicle V ON V.VehicleId = VA.VehicleId                  
INNER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId = DN.GeoId AND OG.OrganizationId = V.OrganizationId               
WHERE               
TripTime <> '00:00:00.0000000'              
AND (CAST(MailStatus AS DATE) <> CAST(GETUTCDATE() AS DATE) OR MailStatus IS NULL)                
AND Recurrence LIKE '%' + CAST(DATEPART(WEEKDAY, DATEADD(MINUTE,DATEDIFF(MINUTE,0,DATEADD(MINUTE,0,DATEADD(HOUR,4,GETUTCDATE()))),0)) AS VARCHAR(2)) + '%'                
AND TripTime = CAST(DATEADD(MINUTE,DATEDIFF(MINUTE,0,GETUTCDATE()),0) AS TIME(7))                  
                  
UPDATE TL SET TL.IsBusReached = 1 FROM (SELECT T.* FROM @TBLGeo T INNER JOIN rvlfMsgInHst MG ON MG.BoxId = T.Boxid WHERE            
CAST(DATEADD(MINUTE,0,DATEADD(HOUR,4,OriginDateTime)) AS TIME(7))            
BETWEEN DATEADD(MINUTE,-20,T.SchoolArrivalTime)AND T.SchoolArrivalTime                   
AND MG.BoxId = T.Boxid AND BoxMsgInTypeId = 5 AND CAST(origindatetime AS DATE) = CAST(getutcdate() AS DATE)                  
AND CAST(SUBSTRING(CustomProp,11,CHARINDEX(';',CustomProp) - 11) AS INT) = T.GeozoneID) AS TBL                  
INNER JOIN @TBLGeo TL ON TL.Boxid = TBL.Boxid                
                
                
SELECT G.Boxid,GeozoneID,GeozoneNo,Vehiclename,SchoolName_EN AS SchoolName,                  
G.DriverName,SchoolArrivalTime,ISNULL(IsBusReached,0) AS IsBusReached,U.UserName,                  
ISNULL(NL.SMS,0) AS IsSMS, ISNULL(NL.Email,0) AS IsEmail,        
CASE WHEN ISNULL(NL.SMS,0) = 1 THEN U.MobileNo END AS SMS,                
CASE WHEN ISNULL(NL.Email,0) = 1 THEN U.Email END AS Email,                
CASE WHEN ISNULL(UP.Lang,'LanguageEn') = 'LanguageArNew' THEN 'DelayMailTemplate_AR.txt' ELSE 'DelayMailTemplate.txt' END AS Template,            
'Vehicle '+''''+Vehiclename+''''+' has not reached the Geozone '+''''+SchoolName_EN+''''+' on time('+CAST(DATEADD(MINUTE,TZ.MinToBeAdded,DATEADD(HOUR,TZ.HoursToBeAdded,SchoolArrivalTime)) AS VARCHAR(20))+')' AS "Message",                
TripNo,DATEADD(MINUTE,TZ.MinToBeAdded,DATEADD(HOUR,TZ.HoursToBeAdded,SchoolArrivalTime)) AS PlannedTime,            
DM.DisplayName,DM.MobileNo,            
(SELECT TOP 1 ISNULL(CASE WHEN ISNULL(UP.Lang,'LanguageEn') = 'LanguageArNew' THEN StreetAddress_AR ELSE StreetAddress END            
,'Address not resolved') AS StreetAddress FROM rvlfMsgInHst WHERE Boxid = G.Boxid             
ORDER BY OriginDateTime DESC) AS StreetAddress            
FROM @TBLGeo G INNER JOIN rvlfNotificationList NL ON NL.TypeID = G.GeozoneNo            
INNER JOIN rvlfUser U ON U.UserId = NL.UserId            
INNER JOIN rvlfUserPreferences UP ON UP.UserId = U.UserId            
INNER JOIN rvlfTimeZones TZ ON TZ.TimeZoneID = UP.TimezoneId            
LEFT OUTER JOIN rvlfDriverAssignment DA ON DA.BoxId = G.Boxid            
LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId = DA.DriverId            
WHERE NL.NotificationType = 1 AND            
ISNULL(IsBusReached,0) = 0            
            
SET NOCOUNT OFF;                  
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DelayNotificationReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================                    
-- EXEC [rvlf_sp_DelayNotificationReport] NULL,181,107, '2012-12-13 01:00:00 AM', '2012-12-13 08:00:00.00 PM',498          
-- Author:  Vijay.N                    
-- Create date: <Create Date,,>                    
-- Description: Get the delay notification details for the organizations.                  
-- =============================================                    
CREATE PROCEDURE [dbo].[rvlf_sp_DelayNotificationReport]          
 -- Add the parameters for the stored procedure here                     
 @intBoxID VARCHAR(MAX) = NULL,
 @bigFleetID BIGINT,
 @bigOrganizationID INT,
 @dtStartDate DATETIME,
 @dtEndDate DATETIME,
 @bigQueryingUser BIGINT = NULL
           
AS                    
BEGIN                    
-- SET NOCOUNT ON added to prevent extra result sets from          
-- interfering with SELECT statements.        
 SET NOCOUNT ON;          
           
           
DECLARE @Lang varchar(50)                                                          
SELECT @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser          
DECLARE @HoursToBeAdded INT = 0, @MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,          
@ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit           
           
  SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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)                                                         
  FROM rvlfUserPreferences up                                                   
   INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                            
   INNER JOIN rvlfUser U on U.UserId = up.UserId                                       
  WHERE up.UserId = @bigQueryingUser           
                    
 DECLARE @tblFleets TABLE              
 (              
	FleetId BIGINT PRIMARY KEY              
 )              
               
 INSERT INTO @tblFleets (FleetId)              
 SELECT ParentChildId FROM [DBO].[rvlf_fn_GetParentChild](@bigFleetID)
                    
IF(@intBoxID IS NULL OR @intBoxID = '')
BEGIN
	SET @intBoxID = ''
	SELECT @intBoxID +=CAST(BoxId AS VARCHAR(MAX)) + ','  FROM @tblFleets F INNER JOIN rvlfFleetVehicles FV ON FV.FleetId = F.FleetId
	INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId = FV.VehicleId WHERE F.FleetId = @bigFleetID
END
                    
-- Insert statements for procedure here          
DECLARE @TBLGeo AS TABLE          
(                     
[INDEX] INT IDENTITY PRIMARY KEY,                    
Boxid INT,                    
GeozoneID INT,                    
GeozoneNo INT,                    
Vehiclename VARCHAR(500),                    
Vehiclename_AR NVARCHAR(500),           
SchoolName_EN VARCHAR(500),          
SchoolName_AR NVARCHAR(500),          
DriverName VARCHAR(250),                    
SchoolArrivalTime TIME,                    
RecurrenceDays VARCHAR(15),                  
TripNo TinyInt,                  
IsBusReached BIT,        
PlannedTime TIME,        
GraceTime INT        
)                    
                    
                    
INSERT INTO @TBLGeo (Boxid,GeozoneID,GeozoneNo,Vehiclename,Vehiclename_AR,SchoolName_EN,SchoolName_AR,DriverName,SchoolArrivalTime,RecurrenceDays,TripNo,PlannedTime,GraceTime)        
SELECT Boxids,GeoId,OG.GeozoneNo,v.VehicleDescription,V.VehicleDescription,OG.geozoneName,OG.geozoneName,'Driver',TripTime,Recurrence,TripNo,PlannedTime,TripTimeGrace FROM                  
(SELECT Boxids,GeoId,DATEADD(MINUTE,TripTimeGrace,TripTime) AS TripTime,MailStatus,Recurrence,TripNo,TripTime AS PlannedTime,TripTimeGrace        
 FROM rvlfDelayNotify CROSS APPLY(VALUES(boxid,GeozoneId,Trip1time,Trip1Gracetime,Trip1MailStatus,RecurrenceDays,1),                     
(boxid,GeozoneId,Trip2time,Trip2Gracetime,Trip2MailStatus,RecurrenceDays,2),(boxid,GeozoneId,Trip3time,Trip3Gracetime,Trip3MailStatus,RecurrenceDays,3)) x (Boxids,GeoId,TripTime,TripTimeGrace,MailStatus,Recurrence,TripNo)) AS DN                      
INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId = DN.Boxids                    
INNER JOIN rvlfVehicleGeozone VG ON VG.VehicleId = VA.VehicleId AND VG.GeozoneNo = DN.GeoId                  
INNER JOIN rvlfVehicle V ON V.VehicleId = VA.VehicleId AND OrganizationId = @bigOrganizationID                          
INNER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId = DN.GeoId   AND OG.OrganizationId = @bigOrganizationID               
WHERE         
--VA.BoxId IN  (SELECT * FROM rvlf_fn_ConvertArrayToTable(@intBoxID,','))        
(@intBoxID IS NULL OR @intBoxID = '' OR VA.BoxId IN  (SELECT * FROM rvlf_fn_ConvertArrayToTable(@intBoxID,',')))--@intBoxID           
AND OG.organizationid = @bigOrganizationID AND TripTime <> '00:00:00.0000000'                
--AND (CAST(MailStatus AS DATE) <> CAST(GETUTCDATE() AS DATE) OR MailStatus IS NULL)                  
AND Recurrence LIKE '%' + CAST(DATEPART(WEEKDAY, DATEADD(MINUTE,DATEDIFF(MINUTE,0,DATEADD(MINUTE,0,DATEADD(HOUR,4,GETUTCDATE()))),0)) AS VARCHAR(2)) + '%'                  
AND     
CAST(DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,TripTime)) AS TIME)    
BETWEEN           
--CAST(DATEADD(MINUTE,-@MinsToBeAdded,DATEADD(HOUR,-@HoursToBeAdded,@dtStartDate)) AS TIME)           
--AND CAST(DATEADD(MINUTE,-@MinsToBeAdded,DATEADD(HOUR,-@HoursToBeAdded,@dtEndDate)) AS TIME)         
    
CAST(@dtStartDate AS TIME)           
AND CAST(@dtEndDate AS TIME)             
    
                    
                   
                    
UPDATE TL SET TL.IsBusReached = 1 FROM (SELECT T.* FROM @TBLGeo T INNER JOIN rvlfMsgInHst MG ON MG.BoxId = T.Boxid WHERE              
CAST(OriginDateTime AS TIME(7))          
--CAST(DATEADD(MINUTE,0,DATEADD(HOUR,4,OriginDateTime)) AS TIME(7))              
BETWEEN DATEADD(MINUTE,-20,T.SchoolArrivalTime)AND T.SchoolArrivalTime                     
AND MG.BoxId = T.Boxid AND BoxMsgInTypeId = 5 AND CAST(origindatetime AS DATE) = CAST(getutcdate() AS DATE)                    
AND CAST(SUBSTRING(CustomProp,11,CHARINDEX(';',CustomProp) - 11) AS INT) = T.GeozoneID) AS TBL                    
INNER JOIN @TBLGeo TL ON TL.Boxid = TBL.Boxid         
  
  
--select * from @TBLGeo    
           
                  
SELECT G.Boxid,GeozoneID,GeozoneNo,          
(CASE WHEN ISNULL(@Lang,'LanguageEn') = 'LanguageArNew'THEN ISNULL(Vehiclename_AR,Vehiclename) ELSE Vehiclename END) AS Vehiclename,          
(CASE WHEN ISNULL(@Lang,'LanguageEn') = 'LanguageArNew'THEN ISNULL(SchoolName_AR,SchoolName_EN) ELSE SchoolName_EN END )AS SchoolName,          
(CASE WHEN ISNULL(@Lang,'LanguageEn') = 'LanguageArNew'THEN ISNULL(DM.DisplayName,DM.DisplayName) ELSE DM.DisplayName END) AS DriverName,           
SchoolArrivalTime,(CASE WHEN ISNULL(IsBusReached,0) = 0 THEN 'Not reached On time' ELSE 'Reached On time' END)          
 AS IsBusReached,U.UserName,          
ISNULL(NL.SMS,0) AS IsSMS, ISNULL(NL.Email,0) AS IsEmail,          
CASE WHEN ISNULL(NL.SMS,0) = 1 THEN U.MobileNo END AS SMS,                  
CASE WHEN ISNULL(NL.Email,0) = 1 THEN U.Email END AS Email,          
('Trip ' + CAST(TripNo AS VARCHAR(1)) ) AS TripNo,        
DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SchoolArrivalTime)) AS PlannedTime,              
(CASE WHEN ISNULL(@Lang,'LanguageEn') = 'LanguageArNew'THEN ISNULL(DM.DisplayName,DM.DisplayName) ELSE DM.DisplayName END) AS DisplayName,           
ISNULL(DM.MobileNo,'-') AS MobileNo,          
(SELECT TOP 1 ISNULL(CASE WHEN ISNULL(@Lang,'LanguageEn') = 'LanguageArNew'THEN ISNULL(StreetAddress_AR,StreetAddress) ELSE StreetAddress END              
,'Address not resolved') AS StreetAddress FROM rvlfMsgInHst WHERE Boxid = G.Boxid AND CAST(OriginDateTime AS DATE) <= CAST(GETUTCDATE() AS DATE)        
 AND CAST (OriginDateTime AS TIME) <= SchoolArrivalTime ORDER BY OriginDateTime DESC) AS StreetAddress,          
DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,GETUTCDATE())) AS GenerateDate,          
 CAST(CONVERT(VARCHAR(20), DATEADD(DAY,1,@dtStartDate),100) AS TIME) AS StartTime,    
 CAST(CONVERT(VARCHAR(20),@dtEndDate,100) AS TIME) AS EndTime,        
(SELECT FleetName FROM rvlfFleetVehicles FV           
INNER JOIN rvlfFleet F ON FV.FleetId = F.FleetId          
INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId = FV.VehicleId          
WHERE VA.BoxId = G.Boxid AND F.FleetId <> 164 AND FleetName NOT LIKE '%Lot%') AS FleetName,        
DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,PlannedTime)) AS PlannedReachTime,        
GraceTime        
FROM @TBLGeo G INNER JOIN rvlfNotificationList NL ON NL.TypeID = G.GeozoneNo          
INNER JOIN rvlfUser U ON U.UserId = NL.UserId          
INNER JOIN rvlfUserPreferences UP ON UP.UserId = U.UserId          
INNER JOIN rvlfTimeZones TZ ON TZ.TimeZoneID = UP.TimezoneId          
LEFT OUTER JOIN rvlfDriverAssignment DA ON DA.BoxId = G.Boxid          
LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId = DA.DriverId          
WHERE ISNULL(IsBusReached,0) = 0          
              
SET NOCOUNT OFF;        
END   
  
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteAssignment]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_DeleteAssignment]
	@bigAssignmentId bigint = Null,
	@bitType bit=null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_DeleteAssignment]
--	Description	:	To delete the driver assignment details.
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	16-Jun-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN
	IF(@bitType=1)
		DELETE rvlfDriverAssignment WHERE AssignmentId=@bigAssignmentId 
	ELSE
		DELETE rvlfDriverAssignment WHERE TRIPID=@bigAssignmentId 
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteCategory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Ramya
-- Create date: 10 Oct 2009
-- Description:	To delete the geozone category
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_DeleteCategory]
	@CategoryId int, 
	@OrganizationId bigint 
as
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	--Delete the category
    Delete from rvlfCategory where CategoryId = @CategoryId;
		
	--Select the set of geozone category
	SELECT CategoryId, CategoryName, CategoryDescription,
	CASE WHEN EXISTS(SELECT OG.CategoryId FROM rvlfOrganizationGeozone OG WHERE OG.CategoryId = rvlfCategory.CategoryId) 
		THEN 1 ELSE 0 END AS AssignedStatus  
	FROM rvlfCategory where OrganizationId = @OrganizationId
	
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteData]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_DeleteData]
AS
/************************************************************
Procedure Name	: rvlf_sp_DeleteData
Created By		: Sakthi Gopinath S
Created Date	: 15-Feb-2013
Description		: Data remove from ET database
*************************************************************/
BEGIN
SET NOCOUNT ON
	--Maintain two month data from the current utc.
	--Delete the records except boxmsginid reference
	BEGIN TRAN DeleteTransaction_FMS
	BEGIN TRY
		
		DELETE dbo.rvlfMsgInHst WHERE OriginDateTime < CAST(CONVERT(VARCHAR(10), DATEADD(DD,-7,DATEADD(MONTH,-2,GETUTCDATE())), 110) AS DATETIME)
		AND IsArchived=1 AND MessageInID NOT IN (SELECT MessageInID FROM dbo.rvlfBoxId)
		
		--Frame mail template for deleted records
		DECLARE @rowCount varchar(25)
		SELECT @rowCount = CAST(@@ROWCOUNT AS VARCHAR(25))
		DECLARE @bodytag varchar(max) = '<div style="font-family: Verdana; font-size: 12px;">
		<p><span style="color: rgb(0, 102, 153);"><strong>Dear All,</strong></span></p>
		<p><span style="color: rgb(0, 102, 153);"><u><em><strong>Old data''s are removed successfully from ''FMS'' database. 
		Only 2 month data available from this date ('+ CAST(CAST(CONVERT(VARCHAR(10), DATEADD(DD,-7,DATEADD(MONTH,-2,GETUTCDATE())), 110) AS DATETIME) 
		AS VARCHAR) +')'+'.</strong></em></u></span></p>
		<table border="0" cellpadding="1" cellspacing="1" style="width: 439px; color: rgb(0, 102, 153);font-family: Verdana;">
		<tbody>
		<tr>
		<td align="left" nowrap="nowrap" style="font-family: Verdana; font-size: 12px;" valign="top"><strong>Details</strong></td>
		<td>&nbsp;</td>
		<td>&nbsp;</td>
		</tr>
		<tr style="font-family: Verdana; font-size: 12px;">
		<td align="left" valign="top">
		<strong>Source Database Name</strong>
		</td>
		<td align="left" valign="top">
		:
		</td>
		<td>
		TRINETRA_Pilot
		</td>
		</tr>
		<tr style="font-family: Verdana; font-size: 12px;">
		<td align="left" valign="top">
		<strong>No of deleted records</strong>
		</td>
		<td align="left" valign="top">
		:
		</td>
		<td>
		'+@rowCount+' 
		</td>
		</tr>
		</tbody>
		</table>
		<hr />
		<p>
		<span style="color: rgb(0, 102, 153);"><b>Best Regards,<br />
		</b></span><a href="http://www.trinetrawireless.com">
		<img alt="trinetrawireless" src="http://www.trinetrawireless.com/images/logo.png"
		style="border: 0px none; width: 94px; height: 34px;" /></a></p>
		<p>
		<span style="font-size: 10px;"><span style="color: rgb(0, 102, 153);">This is a system generated mail</span><br />
		</span>
		</p>
		<p>
		<b><b>&nbsp;</b></b></p>
		</div>'
		
		--Triggering mail once the delete process completed
	--	EXEC msdb.dbo.sp_send_dbmail @profile_name='TRINETRA',
	--	@recipients='gopalakrishnan@angleritech.com;anbarasu.e@angleritech.com',
	--	@copy_recipients = 'sakthigopinath@angleritech.com;ranjith.n@angleritech.com',
	--	@subject='TRINETRA | Reg : Data removed - FMS',@body= @bodytag,@body_format = 'HTML'
		
		COMMIT TRAN
	END TRY
	BEGIN CATCH
		
		ROLLBACK TRAN
		DECLARE @ErrMsg varchar(500)
		SET @ErrMsg = 'An Error occured during delete of the packet message : ' + ERROR_MESSAGE() 
	--	EXEC msdb.dbo.sp_send_dbmail @profile_name='TRINETRA',
	--	@recipients='gopalakrishnan@angleritech.com;anbarasu.e@angleritech.com',
	--	@copy_recipients = 'sakthigopinath@angleritech.com;ranjith.n@angleritech.com',
	--	@subject='TRINETRA | Reg : Data removed - FMS | ERROR',@body= @ErrMsg,@body_format = 'HTML'
		
	END CATCH
	
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteDriverInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_DeleteDriverInfo]  
	@bigDriverId			bigint = Null,   
	@bigOrganizationID		bigint = null,
	@vcDriverName			varchar(50)=null     
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_DeleteDriverInfo]  
-- Description : To delete the driver details  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 10-Jun-2010 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
	--DELETE rvlfDriverMaster   
	--WHERE DriverId=@bigDriverId  
	--AND(@bigOrganizationID IS NULL OR OrganizationID=@bigOrganizationID)   

	IF @bigDriverId IS NOT NULL
	BEGIN
		UPDATE	rvlfDriverMaster SET ISDELETE=1
		WHERE	DriverId=@bigDriverId
		AND		((@bigOrganizationID IS NULL OR @bigOrganizationID='') OR OrganizationID=@bigOrganizationID)
	END
	ELSE
	BEGIN
		DELETE	FROM rvlfDriverMaster
		WHERE	DriverName IN (select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@vcDriverName,','))
		AND		OrganizationID = @bigOrganizationID
	END
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteEmployee]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_DeleteEmployee]
	@bigEmployeeId BIGINT
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_DeleteEmployee]
--	Description	:	To delete the employee details
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	19-Feb-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN
			
 --   DELETE FROM rvlfEmployee WHERE EmployeeID = @bigEmployeeId 
    	
	--DELETE FROM rvlfUserGroupAssignment WHERE UserId=@bigEmployeeId 
IF EXISTS(SELECT * FROM rvlfEmployee WHERE EmployeeID =@bigEmployeeId AND UserGroup=3)
	BEGIN
		RAISERROR('You cannot delete the administrator user group employee.',15,0)
		RETURN
	END
ELSE
	BEGIN
		UPDATE rvlfEmployee SET isdeleted=1 WHERE EmployeeID=@bigEmployeeId 
	END
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteFleetNotification]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_DeleteFleetNotification]   
/*************************************************************************************  
Stored Procedure Name : rvlf_sp_DeleteFleetNotification 
Purpose     : Delete the notification details of a fleet 
Created by    : Uma  
Created date   : 15-Jul-09  
Updated by    :   
Updated date   :   
**************************************************************************************/  
  
@FleetId  bigint  = Null  
  
  
AS  
  
BEGIN   
  
 UPDATE rvlfFleet SET  
 Email=Null,  
 SMS=Null,  
 Notify=Null,  
 Warning=Null,  
 Critical=Null  
 WHERE FleetId=@FleetId    
  
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteFleets]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_DeleteFleets]     
/*************************************************************************************    
Stored Procedure Name : rvlf_sp_DeleteFleets    
Purpose     : Delete selected fleets  
Created by    : Uma    
Created date   : 13-Jul-09    
Updated by    :     
Updated date   :  
[rvlf_sp_DeleteFleets] 82   
**************************************************************************************/    
    
@FleetID  bigint  = Null 
AS  
BEGIN
  DELETE from rvlfFleet WHERE FleetId=@FleetID
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteFuelDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[rvlf_sp_DeleteFuelDetails]    
@Sno BIGINT = NULL,    
@Mode BIGINT =nULL    
    
AS    
/******************************************************************************/    
-- Name  : [rvlf_sp_DeleteFuelDetails]1,4    
-- Description : To delete the fuel details    
--    :      
-- Author  : Kapil.    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 07-May-2014 Created Intial Version     
/******************************************************************************/    
BEGIN      
  update rvlfFuelContainer set IsDelete =1    
  where Sno = @Sno         
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteLandmarkCategory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_DeleteLandmarkCategory]
	@bigLandmarkCategoryID bigint,
	@bigOrganizationID bigint
AS
/******************************************************************************/
--	Name		:	rvlf_sp_DeleteLandmarkCategory
--	Description	:	To delete the landmark category
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	08-Feb-2010	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
	
	BEGIN TRY
		IF EXISTS (SELECT * FROM rvlfLandmarkCategory WHERE LandmarkCategoryID = @bigLandmarkCategoryID 
			AND OrganizationId = @bigOrganizationID)
		BEGIN
		print 'exists'
			DELETE FROM rvlfLandmarkCategory WHERE LandmarkCategoryID = @bigLandmarkCategoryID
				AND OrganizationId = @bigOrganizationID
			select 1
		END
		ELSE
		BEGIN
		print 'notexists'
			SET @ErrorMessage = 'No such category exists !';
			select 0
		END
	END TRY
	BEGIN CATCH
		select 2
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteManualFuelEntry]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[rvlf_sp_DeleteManualFuelEntry] 

	@FuelId bigint=NULL
/*************************************************************************************
Stored Procedure Name	: rvlf_sp_DeleteManualFuelEntry
Purpose					: Delete assigned vehicles of a fleet, to store new vehicles
Created by				: U
Created date			: 10-Jul-09
Updated by				: 
Updated date			: 
**************************************************************************************/



AS

BEGIN	

		DELETE from rvlfFuelEntry WHERE FuelEntryID=@FuelId 

END




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteModelDetails_App]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_DeleteModelDetails_App]
@ModelId int,
@IsUnassigned bit = 0
AS
/*********************************************************************************************
Procedure Name	: rvlf_sp_DeleteModelDetails_App 2
Description		: Delete the model details and mapped details also
Created By		: Sakthi Gopinath S
Created Date	: 16-Mar-2013
*********************************************************************************************/
BEGIN
SET NOCOUNT ON
	BEGIN TRAN DeleteModel
	BEGIN TRY	 
		IF @IsUnassigned = 1
		BEGIN 
			DELETE rvlfModelBoxSettings_App WHERE ModelId=@ModelId
		END
		ELSE
		BEGIN
			DELETE rvlfModelBoxSettings_App WHERE ModelId=@ModelId
			DELETE rvlfModel_App WHERE ModelId=@ModelId
		END
		COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN
	END CATCH
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteOrgorVehicle]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_DeleteOrgorVehicle]  
 @bigOrganizationId bigint=null,  
 @bigVehicleId bigint=null, 
 @EquipId Varchar(max) = null  
AS  
/**********************************************************************************/  
-- Name  : rvlf_sp_DeleteOrgorVehicle   
-- Description : To delete the organization or vehicle details.  
-- Author  : V. Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 01-July-2010 VN Created Intial Version   
--    : 01-July-2010 TSK Delete BoxID from Boxsettings to recreate missing BoxID  
--    : 02-jUN-2011  VN To resrict the deletion of boxid from rvlfboxsetting.  
--	  :	03-Nov-2011	 Sakthi Delete Notification list of vehicle for organization
/***********************************************************************************/  
BEGIN  
IF(@bigOrganizationId IS NOT NULL AND @bigOrganizationId = '')
SET @bigOrganizationId = NULL

 IF(@bigOrganizationId IS NOT NULL AND @bigOrganizationId <> 0)  
  BEGIN     
   DELETE VA FROM rvlfVehicleAssignment  VA   
     INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId   
    WHERE V.OrganizationId = @bigOrganizationId   
      
   DELETE FV FROM rvlfFleetVehicles FV   
     INNER JOIN rvlfVehicle V ON V.VehicleId = FV.VehicleId   
    WHERE V.OrganizationId = @bigOrganizationId   
  
   DELETE VG FROM rvlfVehicleGeozone VG  
     INNER JOIN rvlfVehicle V ON V.VehicleId=VG.VehicleId   
     WHERE V.OrganizationId = @bigOrganizationId   
  
   DELETE VP FROM rvlfVehiclePlanAssignment VP   
     INNER JOIN rvlfVehicle V ON V.VehicleId=VP.VehicleId   
    WHERE V.OrganizationId = @bigOrganizationId  
      
   DELETE VCR FROM rvlfVehicleCurrentReadings VCR  
     INNER JOIN rvlfVehicle V ON V.VehicleId=VCR.VehicleId   
    WHERE OrganizationId=@bigOrganizationId  
      
   DELETE rvlfVehicle WHERE OrganizationId=@bigOrganizationId  
  
   DELETE MPD FROM rvlfMaintenancePlanDetails MPD  
     INNER JOIN rvlfMaintenancePlan MP ON MP.PlanId=MPD.PlanId   
    WHERE MP.OrganizationId = @bigOrganizationId  
  
   DELETE rvlfMaintenancePlan WHERE OrganizationId=@bigOrganizationId  
  
   DELETE UP FROM rvlfUserPreferences UP   
     INNER JOIN rvlfFleet F ON F.FleetId=UP.DefaultFleetId   
    WHERE F.OrganizationId = @bigOrganizationId  
  
   DELETE FU FROM rvlfFleetUsers FU   
     INNER JOIN rvlfFleet F ON F.FleetId=FU.FleetId   
    WHERE F.OrganizationId = @bigOrganizationId  
       
   DELETE rvlfFleet WHERE OrganizationId=@bigOrganizationId  
  
   DELETE rvlfOrganizationPackage WHERE OrganizationID = @bigOrganizationId  
  
   DELETE UGS FROM rvlfUserGroupSecurity UGS   
     INNER JOIN rvlfUserGroup UG ON UG.UserGroupId = UGS.UserGroupId   
    WHERE UG.OrganizationId = @bigOrganizationId  
      
   DELETE rvlfUserGroup WHERE OrganizationId = @bigOrganizationId  
   
   DELETE NL FROM rvlfNotificationList NL 
   INNER JOIN rvlfVehicle v ON v.VehicleId=NL.TypeID and NL.NotificationType=4
   WHERE v.OrganizationId = @bigOrganizationId 
  
   DELETE NL FROM rvlfNotificationList NL   
     INNER JOIN rvlfUser U ON U.UserId = NL.UserID   
    WHERE U.OrganizationId = @bigOrganizationId  
      
   DELETE rvlfMaintenanceServiceCategory WHERE OrganizationId = @bigOrganizationId  
  
   DELETE rvlfOrganizationGeozone WHERE OrganizationId = @bigOrganizationId  
  
   DELETE rvlfUser WHERE OrganizationId = @bigOrganizationId  
  
   DELETE rvlfOrganizationSolution WHERE OrganizationId = @bigOrganizationId  
  
   DELETE rvlfOrganization WHERE OrganizationId = @bigOrganizationId     
  END  
 ELSE  
  BEGIN  
    DELETE FV FROM rvlfFleetVehicles FV          
     INNER JOIN rvlfVehicle V ON V.VehicleId = FV.VehicleId           
    WHERE V.VehicleId = @bigVehicleId          
              
   DELETE BMS FROM rvlfBoxMsgSeverity BMS          
     INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId = BMS.BoxId           
    WHERE VA.VehicleId = @bigVehicleId          
           
   DELETE B FROM rvlfBoxId B          
     INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId = B.BoxId           
    WHERE VA.VehicleId = @bigVehicleId             
           
   DELETE VA FROM rvlfVehicleAssignment VA          
     INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId           
    WHERE V.VehicleId =@bigVehicleId            
              
          
   DELETE VG FROM rvlfVehicleGeozone VG          
     INNER JOIN rvlfVehicle V ON V.VehicleId=VG.VehicleId           
    WHERE V.VehicleId =@bigVehicleId          
              
   DELETE VPA FROM rvlfVehiclePlanAssignment VPA          
     INNER JOIN rvlfVehicle V ON V.VehicleId=VPA.VehicleId           
    WHERE V.VehicleId =@bigVehicleId          
              
   DELETE VCR FROM rvlfVehicleCurrentReadings  VCR          
     INNER JOIN rvlfVehicle V ON V.VehicleId=VCR.VehicleId           
    WHERE V.VehicleId =@bigVehicleId          
             
   DELETE DA FROM rvlfDriverAssignment DA          
     INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=DA.BOXID           
     INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId           
     WHERE V.VehicleId =@bigVehicleId           
               
 --Delete the Box from Boxsettings          
    DELETE BS FROM rvlfBoxSettings BS          
     INNER JOIN rvlfMAKDevices V ON V.BoxId =BS.BoxId           
    WHERE V.VehicleId =@bigVehicleId     
               
   DELETE rvlfVehicle WHERE VehicleId =@bigVehicleId     
               
   update rvlfMAKDevices set IsDelete=1 where VehicleId =@bigVehicleId 

   DELETE FROM rvlf_EnergyConsumption WHERE EquipmentId =@EquipId

   DELETE FROM rvlf_CompactorDetails WHERE DeviceId = @EquipId

   DELETE FROM rvlfParamRange WHERE Boxid = @EquipId

  END  
END  
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeletePackage]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_DeletePackage]
	@bigPackageId BIGINT
AS
/**************************************************************************************/
--	Name		:	rvlf_sp_DeletePackage
--	Description	:	To delete the package details
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	27-Nov-2009		Created Intial Version 
--				:	14-Jun-2010		MJJC	Changed to delete the package if not active currently 
--												In future a track history needs to be maintained.
/**************************************************************************************/
BEGIN
SET NOCOUNT ON 
			
    DECLARE @Count AS INT = 0			
   
    -- Check whether the package is mapped to the Organization
    SET @Count = (SELECT COUNT(*) FROM rvlfOrganizationPackage WHERE PackageId = @bigPackageId AND IsActive=1)

    IF(@Count > 0)
    BEGIN
    
		SELECT 'True' AS IsMapped
    
    END
    ELSE
	BEGIN
	
		DELETE FROM rvlfOrganizationPackage WHERE PackageId = @bigPackageId
	    DELETE FROM rvlfPackageOperations WHERE PackageId = @bigPackageId
	    
	    DELETE FROM rvlfPackage WHERE PackageId = @bigPackageId
	
		SELECT 'False' AS IsMapped
	
	END

SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteRefrigeration]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  CREATE Procedure [dbo].[rvlf_sp_DeleteRefrigeration]         
 @bigRefrigerationId BIGINT  ,    
 @bigOrganizationId bigint      
AS        
/******************************************************************************/        
-- Name  : [rvlf_sp_DeleteRefrigeration]         
-- Description : To delete the Refrigeration details        
-- Author  : Kapil        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--    : 07-May-2014 Created Intial Version         
/******************************************************************************/        
BEGIN        
           
   IF NOT EXISTS (SELECT * FROM rvlfRefrigeratorAssignmt WHERE  RefgId=@bigRefrigerationId and UnAssignDate is null )        
           
  BEGIN             
  UPDATE rvlfRefrigeration SET IsDelete=1 WHERE RefgId=@bigRefrigerationId and OrganizationId = @bigOrganizationId            
  update rvlfRefrigeratorAssignmt set UnAssignDate=GETUTCDATE() where RefgId=@bigRefrigerationId and UnAssignDate is null  
   END            
   ELSE            
    raiserror('Refrigeration Cannot be deleted! Refrigeration Assigned to vehicle.', 16,1)              
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteScheduleReportsSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_DeleteScheduleReportsSettings]
	@bigReportScheduleId bigint
AS

/******************************************************************************/
--	Name		:	rvlf_sp_DeleteScheduleReportsSettings
--	Description	:	To mark the Schedule Reports Settings as delete
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>>   Initial Reason
--				:	03-Mar-2010	Kumuthini	Created Intial Version 
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 
			
		UPDATE rvlfSchedulingReport SET IsDeleted = 1, CanGenerate = 0 WHERE ReportScheduleId = @bigReportScheduleId
	
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteSeverityTemplate]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_DeleteSeverityTemplate]	
	@intSeverityTempID int=null	
AS
/****************************************************************************************/
--	Name		  : rvlf_sp_DeleteSeverityTemplate 
--	Description	  :	To delete the Severity Template details
--	Author		  :	Jeyanthi.S
--	Created Date  : 29-Oct-2010
--  Modified Date :
/***************************************************************************************/
BEGIN
	SET NOCOUNT ON 	
			DELETE FROM rvlfSeverityTemplate WHERE SeverityTempId=@intSeverityTempID 				
	
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteTyreDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_DeleteTyreDetails]       
@TyreID int,          
@bigOrganizationId bigint = Null    
AS      
-- =============================================      
-- Name   : rvlf_sp_DeleteTyreVendorDetails      
-- Author  : kapil      
-- Create date : 19-Feb-2014
-- Description : Delete Tyre Details      
-- Company  : Trinetra      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
-- =============================================      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
IF NOT EXISTS (select * from rvlfTyreStock where TyreID = @TyreID AND UsedQuantity >0)
	BEGIN
	
	Update rvlfTyreMaster set IsDelete=1 where TyreId =@TyreID	
	--update rvlfTyreStock set TotalQuantity = (TotalQuantity - @Qty) 
	update rvlfTyreStock set TotalQuantity = (TotalQuantity - (select Quantity from rvlfTyreMaster where TyreId = @TyreID))
	--Available = (TotalQuantity-ISNULL(UsedQuantity,0)),UsedQuantity = ISNULL(UsedQuantity,0)
	where vendorId = (select vendorid from rvlfTyreMaster where TyreId = @TyreID)
	and ModelID = (select modelid from rvlfTyreMaster where TyreId = @TyreID)	
	update rvlfTyreStock set Available = (TotalQuantity-ISNULL(UsedQuantity,0)),UsedQuantity = ISNULL(UsedQuantity,0)
	select 1	
	
	END	
	
	else	
	
	select 0	
 Set Nocount Off; 
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteTyreMappingDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
      
CREATE PROCEDURE [dbo].[rvlf_sp_DeleteTyreMappingDetails]       
@TyreMapId int,
@bigOrganizationId bigint = Null    
AS      
-- =============================================      
-- Name   : rvlf_sp_DeleteTyreMappingDetails  257,'35'    
-- Author  : kapil      
-- Create date : 24-Feb-2014
-- Description : Delete Tyre Mapping Details      
-- Company  : Trinetra      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
-- =============================================      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;		 	   
 
				--Update rvlfTyreVehicleMapping set IsDelete=1 where TyreMappingId =@TyreMapId		
		
		
		       if EXISTS(select * from rvlfTyreHistory where TyreMappingID = @TyreMapId)		
		       
				BEGIN
					declare @Category int 	
					Declare @MaxType int
						IF EXISTS(select * from rvlfTyreVehicleMapping where TyreMappingId = @TyreMapId and Category = 2)			
						BEGIN					
						--Set @Category = (select Category from rvlfTyreHistory where Id = (select MAX(id) from rvlfTyreHistory where TyreMappingID = @TyreMapId))					
						Update rvlfTyreVehicleMapping set IsDelete= 0, Category = 2,IsActive=1 where TyreMappingId =@TyreMapId
						
						END
						
						ELSE												
						set @MaxType = (select MAX(id) from rvlfTyreHistory where TyreMappingID = @TyreMapId)
						Set @Category = (select Category from rvlfTyreHistory where Id = (select MAX(id) from rvlfTyreHistory where TyreMappingID = @TyreMapId and Id < ISNULL(@MaxType,0)))					
						
						Update rvlfTyreVehicleMapping set IsDelete= 0, Category = @Category, IsActive=1 where TyreMappingId =@TyreMapId
						
				END		
				
				
				ELSE
				
					BEGIN
				
					Update rvlfTyreVehicleMapping set IsDelete=1 where TyreMappingId =@TyreMapId		
					END
		
		
 Set Nocount Off; 

END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteTyreVendorDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_DeleteTyreVendorDetails]     
@VendorID int ,                    
@bigOrganizationId bigint = Null      
AS      
-- =============================================      
-- Name   : rvlf_sp_DeleteTyreVendorDetails      
-- Author  : kapil      
-- Create date : 18-Feb-2014
-- Description : Delete Vendor Details      
-- Company  : Trinetra      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
-- =============================================      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;      
     
      IF NOT EXISTS (select * from rvlfTyreMaster where VendorId  = @VendorID  ANd IsDelete =0)    
      	
		BEGIN
		
		Update rvlfTyreVendorMaster set IsDelete=1 where VendorId=@VendorID  
		
		SELECT 1
		
		end
		
		else
		
		SELECT 0
 
 Set Nocount Off; 
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteUser]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_DeleteUser]
	@bigUserId bigint=null,
	@bigOrganizationId bigint=null,
	@Modifyby bigint=null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_DeleteUser]
--	Description	:	To delete the user details
--	Author		:	V.Narayanasamy.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	29-Dec-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	UPDATE rvlfUser SET ISDELETE=1,ModifiedBy=@Modifyby,ModifiedDateTime=GETUTCDATE() WHERE UserId =@bigUserId and OrganizationId=@bigOrganizationId
	DELETE FROM rvlfNotificationList WHERE UserID =@bigUserId 
	DELETE FROM rvlfUserGroupAssignment WHERE UserId =@bigUserId   
	
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteUserGroup]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_DeleteUserGroup]
	@bigUserGroupId BIGINT
AS
/**************************************************************************************/
--	Name		:	rvlf_sp_DeleteUserGroup
--	Description	:	To delete the UserGroup details
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	01-Dec-2009		Created Intial Version 
/**************************************************************************************/
BEGIN
SET NOCOUNT ON 
			
    DELETE FROM rvlfUserGroupSecurity WHERE UserGroupId = @bigUserGroupId
    
    DELETE FROM rvlfUserGroup WHERE UserGroupId = @bigUserGroupId

SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteUsers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_DeleteUsers]     
/*************************************************************************************    
Stored Procedure Name : rvlf_sp_DeleteUsers    
Purpose     : Delete assigned users of a fleet, to store new users    
Created by    : Uma    
Created date   : 11-Jul-09    
Updated by    :     
Updated date   :     
**************************************************************************************/    
    
@FleetId  bigint  = Null    
    
    
AS    
    
BEGIN     
    
  DELETE from rvlfFleetUsers WHERE FleetId =  @FleetId   
    
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_DeleteVehicles] 
/*************************************************************************************
Stored Procedure Name	: rvlf_sp_DeleteVehicles
Purpose					: Delete assigned vehicles of a fleet, to store new vehicles
Created by				: Uma
Created date			: 10-Jul-09
Updated by				: 
Updated date			: 
**************************************************************************************/

@FleetId		bigint		= Null


AS

BEGIN	

		DELETE from rvlfFleetVehicles WHERE FleetId=@FleetId 

END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DeleteVendorDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
        
CREATE PROCEDURE [dbo].[rvlf_sp_DeleteVendorDetails]         
@VendorID int ,                      
@bigOrganizationId bigint = Null        
AS        
-- =============================================        
-- Name   : rvlf_sp_DeleteVendorDetails        
-- Author  : Gopal.R        
-- Create date : 22-Oct-2013        
-- Description : Delete Vendor Details        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
-- =============================================        
BEGIN        
 -- SET NOCOUNT ON added to prevent extra result sets from        
 -- interfering with SELECT statements.        
 SET NOCOUNT ON;        
        
 Update rvlfVendors set IsDelete=1 where VendorId=@VendorID    
   
 Set Nocount Off;   
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_DelteRouteDriverorVehicleInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_DelteRouteDriverorVehicleInfo]  
 @bigAssignementId bigint = Null,    
 @bitIsDriverInfo bit=nulL ,  
  @bigDriverId bigint = null  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_DelteRouteDriverorVehicleInfo]  
-- Description : To delete the route wise driver/vehicle schedule details  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 27-Sep-2010 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
  
 IF(@bitIsDriverInfo =1)  
  BEGIN  
   DELETE FROM rvlfRouteDriverAssignment WHERE ASSIGNMENTID=@bigAssignementId AND DriverId= @bigDriverId   
  END  
 ELSE  
  BEGIN  
   DELETE FROM rvlfRouteVehicleAssignment WHERE ASSIGNMENTID=@bigAssignementId   
  END   
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_SP_DeviceRemapping]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Proc [dbo].[rvlf_SP_DeviceRemapping]
(
 @boxid varchar(max)=null,
 @Fromboxid varchar(max)=null,
 @ToBoxid varchar(max)=null,
 @OrgId bigint=6
)
as
 --rvlf_SP_DeviceRemapping null,1032,1036,86
begin
 declare @FleetId bigint

 update rvlfBoxId set OrganizationId=@OrgId where ((@boxid is null or BoxId in(@boxid)) and (@Fromboxid is null or boxid between @fromboxid and @Toboxid))
 
 update rvlfVehicle set OrganizationId=86 where VehicleId in (select v.VehicleId from rvlfVehicleAssignment va inner join rvlfVehicle V on va.VehicleId=v.VehicleId 
 where ((@boxid is null or BoxId in(@boxid)) and (@Fromboxid is null or boxid between @fromboxid and @Toboxid)))
 --select v.VehicleId,OrganizationId from rvlfVehicleAssignment va inner join rvlfVehicle V on va.VehicleId=v.VehicleId 
 --where ((@boxid is null or BoxId in(@boxid)) and (@Fromboxid is null or boxid between @fromboxid and @Toboxid))
 
 select @FleetId=fleetid from rvlfFleet where organizationid=@orgID and IsDefault=1
 
 delete rvlffleetvehicles where VehicleId in (select v.VehicleId from rvlfVehicleAssignment va inner join rvlfVehicle V on va.VehicleId=v.VehicleId 
 where ((@boxid is null or BoxId in(@boxid)) and (@Fromboxid is null or boxid between @fromboxid and @Toboxid)))
 


 insert into rvlffleetvehicles 
 select @FleetId,v.VehicleId,1,1,GETDATE(),null,null from rvlfVehicleAssignment va inner join rvlfVehicle V on va.VehicleId=v.VehicleId 
 where ((@boxid is null or BoxId in(@boxid)) and (@Fromboxid is null or boxid between @fromboxid and @Toboxid))

  declare @count int=0
 select @count=count(*) from rvlfVehicleAssignment va inner join rvlfVehicle V on va.VehicleId=v.VehicleId 
 where ((@boxid is null or BoxId in(@boxid)) and (@Fromboxid is null or boxid between @fromboxid and @Toboxid))
 update rvlfOrganization set noofvehicles=noofvehicles+@count where organizationid=@OrgId

End
GO
/****** Object:  StoredProcedure [dbo].[rvlf_Sp_EngineHours_Rpt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_Sp_EngineHours_Rpt] 
 @bigFleetID  bigint = NULL,
 @intBoxID varchar(max) = NULL,
 @dtStartDate DateTime = NULL,
 @dtEndDate DateTime = NULL,
 @bigOrganizationID bigint = NULL,
 @bigQueryingUser bigint = NULL,
 @vechileTypeId bigint=null
 /******************************************************************************/                
 -- Procedure	: rvlf_Sp_EngineHours_Rpt NULL,NULL,NULL,NULL,NULL,NULL
 -- Description	: To get the Vechicle details                
 -- Author		: Asanraj N
 -- Company		: Trinetra Wireless (P) Ltd.
 -- History		: <<Date(dd-MON-yyyy)>> Initial Reason 
 /******************************************************************************/  
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET NOCOUNT ON;

 DECLARE @HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0
 DECLARE @DisplayName nvarchar(30)  
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,
    @DefaultDateFormat=(case when ISNULL(up.DefaultDateFormat,0)=0 then 106 else up.DefaultDateFormat end),
	@DisplayName = U.UserName 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 
  


  Select distinct MD.EquipmentName AS DeviceName, MD.CustomerName AS Gatewayname,
  case when (convert(int, convert(int, isnull(Engine_RunTime,0) /60 / 60))>=10) then 
			convert(varchar(9), convert(int, convert(int, isnull(Engine_RunTime,0) /60 / 60)))
		else
			right('00' +convert(varchar(9), convert(int, convert(int, isnull(Engine_RunTime,0) /60 / 60))),2)
		end
		+ ':' +
        right('00' + convert(varchar(2), convert(int, convert(int, (isnull(Engine_RunTime,0) / 60) - (convert(int, isnull(Engine_RunTime,0) /60 / 60) * 60 )))), 2) + ':' +
        right('00' + convert(varchar(6), isnull(Engine_RunTime,0) % 60), 2) as Engine_RunTime,
		Engine_RunTime,
		Convert(varchar,@dtEndDate,@DefaultDateFormat) as OriginDateTime,
  --T.OriginDateTime,
  Convert(varchar,@dtStartDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtStartDate as time),22) as PasStartDate,Convert(varchar,@dtEndDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEndDate as Time),22) as PasEndDate, 
  --PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()),
  @DisplayName + ' - ' + CONVERT(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ 
	' '+ CONVERT(VARCHAR,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) AS TIME),22) AS PasGeneratedDate
  from 
    rvlfMAKDevices MD 
	INNER JOIN rvlfVehicle V on md.VehicleId=v.VehicleId and VehicleTypeId=@vechileTypeId
	INNER JOIN rvlfFleetVehicles RFV ON MD.VehicleId = RFV.vehicleId
	INNER JOIN rvlfBoxID B ON B.BoxID = MD.BoxId   
	LEFT OUTER JOIN rvlfMsgInHst_Techno T ON T.BoxId = B.BoxId
	LEFT OUTER JOIN rvlfMsgInHst_Techno_355 T3 ON T3.BoxId = B.BoxId
  WHERE
    (@bigFleetID IS NULL OR @bigFleetID='' OR RFV.FleetId=@bigFleetID)                   
    AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR T.BoxID in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))  
	AND  T.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate and Engine_RunTime is not null 
 --ORDER BY T.OriginDateTime DESC    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ExpireCommand]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_ExpireCommand]   
@intBoxID varchar(10) ,  
@dtSendDateTime dateTime,  
@tiAck tinyint  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_ExpireCommand] 999983, '2011-04-22 12:02:55.000', 3  
-- Description : To expire the commands which are timed out  
--      Acknowledged = 1 THEN 'Acknowledged'   
--      Acknowledged = 0 THEN 'Expired'   
--      Acknowledged = 2 THEN 'Success'  
--      Acknowledged = 3 THEN 'Update Failed'  
--      Acknowledged = 4 THEN 'CRC Incorrect'  
--      Acknowledged = 5 THEN 'No Communication'  
--      Acknowledged = 6 THEN 'Aborted'  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Reason  
--    : 26-May-2009 MJJC Created Intial Version   
--    :   22-Apr-2011 LK   Included the Updation of status for OTA in Scheduling of Commands Log  
--    :   26-Apr-2011 LK   Included the additional status 'Aborted' for OTA  
/******************************************************************************/  
BEGIN  
   
 --UPDATE THE ACK FOR OLD OTA MESSAGES  
 UPDATE rvlfMsgOutHst SET Acknowledged=3 WHERE Acknowledged IS NULL AND BoxCmdOutTypeId =22   
  AND GETUTCDATE()>DATEADD(MINUTE,40,SentDateTime)  
   
 UPDATE rvlfMsgOutHst SET   
  Acknowledged = CASE WHEN @tiAck =0 AND BoxCmdOutTypeId =22 THEN 3 ELSE @tiAck END  
 WHERE   
  BoxID = @intBoxID AND SentDateTime = @dtSendDateTime AND BoxCmdOutTypeId <> 21  
    
  DECLARE @tiBoxCmdOutTypeID tinyint  
  DECLARE @vcCustomProp varchar(150)  
      
  SELECT @tiBoxCmdOutTypeID = BoxCmdOutTypeId, @vcCustomProp = CustomProp  
   FROM rvlfMsgOutHst WHERE BoxID = @intBoxID AND SentDateTime = @dtSendDateTime   
      
  IF @tiBoxCmdOutTypeID = 22  
  BEGIN  
    
  DECLARE @bigScheduleId bigint = 0  
    
  SELECT @bigScheduleId = SM.ScheduleId FROM rvlfScheduleOfCommandsMaster SM  
  INNER JOIN rvlfSchedulingOfCommandsLog CL ON CL.ScheduleId = SM.ScheduleId  
  INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId = SM.Boxid   
  WHERE CL.IsCommandSend = 1 AND (CL.ResponseMsg IS NULL OR CL.ResponseMsg = 'Command sent successfully.')  
  AND (CL.ExecutionOn IS NULL OR CONVERT(DATE, CL.ExecutionOn) = CONVERT(DATE, @dtSendDateTime))  
  AND SM.BoxCmdOutTypeId  = 22 AND VA.BoxId = @intBoxID  
    
  UPDATE rvlfSchedulingOfCommandsLog SET   
   ResponseMsg = CASE WHEN @tiAck = 0 THEN 'Expired' WHEN @tiAck = 1 THEN 'Acknowledged'   
          WHEN @tiAck = 2 THEN 'Success' WHEN  @tiAck = 3 THEN 'Update Failed'  
          WHEN @tiAck = 4 THEN 'CRC Incorrect' WHEN @tiAck = 5 THEN 'No Communication'   
          WHEN @tiAck = 6 THEN 'Aborted' ELSE 'Inprogress' END,
   ResponseId = CASE WHEN @tiAck = 0 THEN 6 WHEN @tiAck = 1 THEN 7   
          WHEN @tiAck = 2 THEN 3 WHEN  @tiAck = 3 THEN 8  
          WHEN @tiAck = 4 THEN 9 WHEN @tiAck = 5 THEN 10
          WHEN @tiAck = 6 THEN 5 ELSE 2 END  
  WHERE ScheduleId = @bigScheduleId  
    
  IF @tiAck = 2  
  BEGIN  
     
   UPDATE rvlfBoxSettings SET FwID =   
    CAST(SUBSTRING(@vcCustomProp,CHARINDEX(':', @vcCustomProp,   
    CHARINDEX ('version',@vcCustomProp,1))+1,10) as int)   
   WHERE BoxId = @intBoxID  
    
  END  
 END  
   
END  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_FilterShiftEmployee]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_FilterShiftEmployee]  
 @dtShiftin time=NULL,  
 @dtShiftout time=NULL,  
 @dtShiftDate datetime=NULL,  
 @vcLocality varchar(50)=NULL,  
 @bigLandmarkId bigint=NULL,  
 @bigZoneId bigint=NULL,  
 @vcTripMode varchar(7)=null,  
 @bigBranchId bigint=null  
   
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_FilterShiftEmployee] '08:00:00','17:00:00','06/14/2010',NULL,NULL,null,'Pickup'  
-- Description : To filter the employee details based on shiftin,shiftouttime  
-- Author  : V. Narayanasamy.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 07-01-2010 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
  
 SELECT e.EmployeeID,e.DisplayName, sv.FromAddress as StreetAddress ,e.MobileNo,od.DepartmentName,d.OrgDivisionName,e.Building,lm.LocalityName,e.LocalityId   
  FROM rvlfEmployee e  
   INNER JOIN rvlfScheduledVehicleRequisition sv ON sv.EmployeeId=e.EmployeeID   
   LEFT OUTER JOIN rvlfOrgDepartment od ON od.DepartmentID =e.DepartmentID   
   LEFT OUTER JOIN rvlfOrgDivision d ON d.OrgDivisionID=e.DivisionID   
   INNER JOIN rvlfEmployeeShifts es ON es.EmployeeId=e.EmployeeID   
   INNER JOIN rvlfLocalityMaster lm ON lm.LocalityId=sv.LocalityId   
     
  where (@dtShiftin IS NULL OR @dtShiftin='' OR es.ShiftIn=CONVERT(time,@dtShiftin))  
   AND (@dtShiftout IS NULL OR @dtShiftout='' OR es.ShiftOut=CONVERT(time,@dtShiftout))   
   AND(Available=1)  
   AND(IsDeleted=0)  
   AND (Approval !='R')  
   --AND (@dtShiftDate  IS NULL OR es.ShiftDate =@dtShiftDate)   
   AND (@vcLocality  IS NULL OR @vcLocality='' OR sv.LocalityId=@vcLocality)  
   AND (@bigLandmarkId IS NULL OR @bigLandmarkId='' OR e.NearestLandMark =@bigLandmarkId)  
   AND (@bigZoneId IS NULL OR @bigZoneId='' OR e.ZoneId =@bigZoneId)   
   AND (sv.Closed=0)  
   AND(es.ShiftDate=CASE WHEN @dtShiftDate IS NULL THEN sv.RequisitionFromDate ELSE @dtShiftDate END)      
   AND es.ShiftDate >=sv.RequisitionFromDate   
   AND es.ShiftDate <=sv.RequisitionToDate   
   AND es.Leave=0  
   AND(@vcTripMode IS NULL OR @vcTripMode='' OR sv.RequisitionService=@vcTripMode OR sv.RequisitionService='Both')  
   AND (@bigBranchId IS NULL OR @bigBranchId='' OR e.OrgId=@bigBranchId)  
 ORDER BY lm.LocalityName   
   
    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_FindIdlingPackets]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[rvlf_sp_FindIdlingPackets]
	@bigOrganizationid bigint=null,
	@tintDurationinMonths tinyint=null,
	@intBoxid int =null
AS
/******************************************************************************/
--	Name		:	rvlf_sp_FindIdlingPackets 58,6,9
--	Description	:	To get the idling packets details 
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	23-Jun-2011	VN	Created Intial Version 
/******************************************************************************/
BEGIN

declare @tblIdlingDetails table
(
	id int identity(1,1),
	boxid int,
	origindatetime datetime,
	duration int 
)
declare @tblIdlingends table
(
	id int,
	boxid int,
	origindatetime datetime,
	duration int 
)
declare @tblIdlingstarts table
(
	id int,
	boxid int,
	origindatetime datetime,
	duration int 
)
if(@intBoxid is null)
	begin
		insert into @tblIdlingDetails (boxid,origindatetime,duration)
		select BoxId,OriginDateTime,cast(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,((CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0)))-(CHARINDEX('Idling:',CustomProp,0)+7))) as int)
			from rvlfmsginhst where BoxId in(SELECT BoxId FROM rvlfBoxID WHERE OrganizationId =@bigOrganizationid) 
			and OriginDateTime>DATEADD(M,-@tintDurationinMonths,GETDATE()) and boxmsgintypeid =9 order by BoxId,OriginDateTime  
	end
else
	begin
		insert into @tblIdlingDetails (boxid,origindatetime,duration)
		select BoxId,OriginDateTime,cast(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,((CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0)))-(CHARINDEX('Idling:',CustomProp,0)+7))) as int)
			from rvlfmsginhst where BoxId in(@intBoxid) 
				and OriginDateTime>DATEADD(M,-@tintDurationinMonths,GETDATE()) and boxmsgintypeid =9 order by BoxId,OriginDateTime  
	end
declare @id int=(select MIN(id) from @tblIdlingDetails where duration =0 )
while @id is not null
begin
	 if ((select duration from @tblIdlingDetails where id=@id)=(select duration from @tblIdlingDetails where id=(@id+1)))
		begin		
			insert into @tblIdlingstarts(id,boxid,origindatetime,duration)
			select id,boxid,origindatetime,duration from @tblIdlingDetails where id=(@id) 
			if exists(select id from @tblIdlingDetails where id>@id and duration=0)
				select @id=MIN(id) from @tblIdlingDetails where id>@id and duration=0
			else
				set @id =null
		end
	else if((select duration from @tblIdlingDetails where id=@id)!=(select duration from @tblIdlingDetails where id=(@id+2)))
		begin
			insert into @tblIdlingends(id,boxid,origindatetime,duration)
			select id,boxid,origindatetime,duration from @tblIdlingDetails where id=(@id+2) 
			if exists(select id from @tblIdlingDetails where id>@id and duration=0)
				select @id=MIN(id) from @tblIdlingDetails where id>@id and duration=0
			else
				set @id =null
		end		
	else
		begin
		if exists(select id from @tblIdlingDetails where id=(@id+2))
			select @id=id from @tblIdlingDetails where id=(@id+2)
		else
			set @id =null
		end
end
select 'Overall idling packets from this boxid' as TableName
select * from @tblIdlingDetails 
select 'idling start packets without idling end' as TableName
select * from @tblIdlingstarts 
select 'idling end packets without idling start' as TableName
select * from @tblIdlingends 
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ForDataAnalysis]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[rvlf_sp_ForDataAnalysis]  
@boxId as varchar(max)= NULL,  
@startDate datetime = NULL,  
@endDate datetime = NULL  
AS  
/*********************************************************  
Procedure  : [rvlf_sp_ForDataAnalysis] '999888'  
Created By : Sakthi Gopinath S  
Created Date : 04-Aug-2012  
*********************************************************/  
BEGIN  
SET NOCOUNT ON  
SET @startDate = DATEADD(HH,-4,GETUTCDATE())  
SET @endDate = DATEADD(DD,2,GETUTCDATE())  
DECLARE @tblBoxes TABLE(Slno int,BoxId int)  
INSERT INTO @tblBoxes(Slno,BoxId)  
SELECT ROW_NUMBER()OVER(ORDER BY FieldValue ASC),FieldValue AS BoxID FROM dbo.rvlf_fn_ConvertArrayToTable(@boxId,',')  
DECLARE @fleets varchar(max)=''  
SELECT ROW_NUMBER()OVER(ORDER BY C.BoxID ASC) AS Slno,  
C.BoxId,v.VehicleDescription AS [Vehicle Name],  
CASE WHEN A.ValidGps > 0 THEN 'YES' ELSE 'NO' END AS [Valid GPS],  
CASE WHEN A.GPSShort > 0 THEN 'YES' ELSE 'NO' END AS [GPS Short],  
CASE WHEN A.IgnitionOn > 0 THEN 'YES' ELSE 'NO' END AS [Ignition ON],  
CASE WHEN A.IgnitionOff > 0 THEN 'YES' ELSE 'NO' END AS [Ignition OFF],  
CASE WHEN A.counts =0 THEN 'NO DATA' ELSE A.StreetAddress END AS [Address],  
CONVERT(VARCHAR,DATEADD(HOUR,4,LastReportedTime),103)+CONVERT(varchar,CAST(DATEADD(HOUR,4,LastReportedTime) as Time),22) AS [Last Reported Date],  
A.MessageDetails AS [Last Messages],  
STUFF((SELECT ','+ FleetName FROM rvlfFleet f INNER JOIN rvlfFleetVehicles fv ON fv.FleetId=f.FleetId WHERE fv.VehicleId=v.VehicleId  
FOR XML PATH('')),1,1,'') AS Fleets  
--CONVERT(VARCHAR, @startDate,103)+CONVERT(varchar,CAST(@startDate as Time),22)  AS [Start_Date],  
--CONVERT(VARCHAR,@endDate,103)+CONVERT(varchar,CAST(@endDate as Time),22)  AS [End_Date]  
FROM (SELECT h.BoxId,SUM(CASE WHEN h.ValidGps=0 THEN 1 ELSE 0 END) AS ValidGps,  
SUM(CASE WHEN h.BoxMsgInTypeId=30 THEN 1 ELSE 0 END) AS GPSShort,  
SUM(CASE WHEN h.BoxMsgInTypeId=2 THEN 1 ELSE 0 END) AS IgnitionOn,   
SUM(CASE WHEN h.BoxMsgInTypeId=3 THEN 1 ELSE 0 END) AS IgnitionOff,  
(SELECT LastStreetAddress FROM rvlfBoxId WHERE BoxID=h.BoxId) AS StreetAddress,  
(SELECT dbo.rvlf_fn_GetAlarmDetails_Optimzd(CustomProp,BoxMsgInTypeId,BoxId,MessageInId,NULL,'LanguageEn') FROM rvlfMsgInHst WHERE MessageInId IN   
(SELECT MessageInId FROM rvlfBoxId WHERE BoxID=h.BoxId)) AS MessageDetails,  
MAX(OriginDateTime) AS LastReportedTime,COUNT(h.BoxMsgInTypeId) AS counts FROM rvlfMsgInHst h   
INNER JOIN (SELECT FieldValue AS BoxID FROM dbo.rvlf_fn_ConvertArrayToTable(@boxId,',')) B  
ON h.BoxId=B.BoxID WHERE h.OriginDateTime BETWEEN CAST(@startDate AS DATETIME) AND CAST(@endDate AS DATETIME)  
GROUP BY h.BoxId) A RIGHT OUTER JOIN (SELECT FieldValue AS BoxID FROM dbo.rvlf_fn_ConvertArrayToTable(@boxId,',')) C  
ON C.BoxID=A.BoxId INNER JOIN rvlfVehicleAssignment va ON va.BoxId=C.BoxID INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId  
ORDER BY C.BoxID  
  
DECLARE @tblMessages TABLE([Sl. no] int,[Box Id] bigint,[Date & Time] datetime,[Messages] varchar(500),[Address] varchar(250))  
DECLARE @i int = 1  
DECLARE @deviceId bigint  
WHILE @i <= (SELECT COUNT(*) FROM @tblBoxes)  
BEGIN  
   
 SET @deviceId = (SELECT BoxID FROM @tblBoxes WHERE Slno=@i)  
 INSERT INTO @tblMessages([Sl. no],[Box Id],[Date & Time],[Messages],[Address])  
 SELECT TOP 500 ROW_NUMBER()OVER(ORDER BY OriginDateTime DESC) AS Slno,BoxId,  
 OriginDateTime as [Date & Time],dbo.rvlf_fn_GetAlarmDetails_Optimzd(CustomProp,BoxMsgInTypeId,BoxId,null,null,'LanguageEn') AS [Messages],StreetAddress  
 FROM rvlfMsgInHst WHERE BoxId=@deviceId AND BoxMsgInTypeId NOT IN (5,6)  
 --and BoxMsgInTypeId = 96
 ORDER BY OriginDateTime DESC  
 SET @i=@i+1  
   
END  
  
SELECT *,DATEADD(HOUR,4,[Date & Time]) AS [UAE (GMT + 4)],DATEADD(HOUR,5,DATEADD(MINUTE,30,[Date & Time])) AS [INDIA (GMT + 5:30)]  
FROM @tblMessages  
  
SET NOCOUNT OFF  
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GenerateBoxId]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GenerateBoxId]

AS

/******************************************************************************/
--	Name		:	rvlf_sp_GenerateBoxId
--	Description	:	To generate and insert the Box Id in the database
--	Author		:	L. Kumuthini
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	17-Nov-2009		Created Intial Version 
/******************************************************************************/

BEGIN

	SET NOCOUNT ON
	
	DECLARE @MinNo AS BIGINT = 0
	DECLARE @MaxNo AS BIGINT = 0
	DECLARE @LOOP AS BIGINT = 1
	DECLARE @Missing AS BIGINT = 0

	SET @MaxNo = (SELECT MAX(BoxId) FROM rvlfBoxSettings)

	WHILE(@LOOP <= @MaxNo) 
	BEGIN

		IF EXISTS(SELECT BoxId FROM rvlfBoxSettings WHERE BoxId = @LOOP)
		BEGIN
			SET @LOOP = @LOOP + 1
		END
		ELSE
		BEGIN
			SET @Missing = @LOOP
			SET @LOOP = @MaxNo + 1
		END

	END
	SET @MaxNo = ISNULL(@MaxNo,0)
	IF(@Missing = 0)
	BEGIN
	    INSERT INTO rvlfBoxSettings(BoxId) VALUES (@MaxNo + 1)
	    
		SELECT (@MaxNo + 1) AS BoxId
	END
	ELSE
	BEGIN
		INSERT INTO rvlfBoxSettings(BoxId) VALUES (@Missing)
		
		SELECT @Missing AS BoxId
	END
		
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GenerateBulkBoxId]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GenerateBulkBoxId]  
@isTop int = 1,  
@intBoxId bigint OUTPUT  
AS  
  
--/******************************************************************************/  
---- Name  : rvlf_sp_GenerateBulkBoxId  
---- Description : To generate and insert the Box Id in the database  
---- Author  : S. Jeyanthi  
---- Company  : Angler Technologies  
---- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
----    : 23-Oct-2010  Created Intial Version   
--      06-May-11 TSK Modified script to identify missing BoxID w/o loop  
-- : 19-May-2014 Ranjith Included --- Not in select F2 from DontUseDeviceIds where F2(BoxID) is not null included for Device Id's not to be used.
--/******************************************************************************/  
  
  
BEGIN  
  
 SET NOCOUNT ON  
 IF @isTop = 1  
  BEGIN  
   /*  
   DECLARE @MinNo AS BIGINT = 0  
   DECLARE @MaxNo AS BIGINT = 1  
   DECLARE @intNextValue bigint=0  
  
   SET @MinNo = (SELECT Min(BoxId) FROM rvlfBoxSettings)  
   SET @intNextValue =0  
   SET @intNextValue = @MinNo + 1  
   WHILE @MinNo < @intNextValue  
   BEGIN  
    IF ((Select top 1 BoxId from rvlfBoxSettings where BoxId > @MinNo order by BoxId) = @intNextValue)  
    BEGIN  
     SET @MinNo = @intNextValue  
     SET @intNextValue = @MinNo + 1  
    END  
   ELSE  
    BEGIN  
     SET @intNextValue = @MinNo  
    END    
   END  
      
   SET @intBoxId = @intNextValue + 1 */  
     
	--	Included script to fetch Missing ID w/o loop    
	--	SET @intBoxId = (select top 1 l.BoxId + 1 as NextBoxID from Rvlfboxid as l  
	--  left outer join Rvlfboxid as r on l.BoxId + 1 = r.BoxId and r.BoxId < 10000  and  r.BoxId not In(select ISNULL(F2,0) from DontUseDeviceIds where F2 is not null) 
	--  where r.BoxID is null)  
      
      
         
	--SET @intBoxId =	  (Select NextBoxID from(
	--select top 1 l.BoxId + 1 as NextBoxID from Rvlfboxid as l 
	--left outer join Rvlfboxid as r on l.BoxId + 1 = r.BoxId and r.BoxId < 10000 where r.BoxID is null) as tbl where
	--tbl.NextBoxID not In(select ISNULL(F2,0) as Boxid from DontUseDeviceIds where F2 is not null) )
     
	SET @intBoxId = (select top 1 l.BoxId + 1 as NextBoxID from Rvlfboxid as l
					left outer join Rvlfboxid as r on l.BoxId + 1 = r.BoxId
					where r.BoxID is null and l.BoxId >1000)         
     
  END   
 ELSE  
  BEGIN  
   /*SET @MaxNo = (SELECT Max(BoxId) FROM rvlfBoxSettings)  
   SET @intNextValue=0  
     
   SET @intNextValue = @MaxNo - 1  
   WHILE @MaxNo > @intNextValue  
   BEGIN  
    IF ((Select top 1 BoxId from rvlfBoxSettings where BoxId < @MaxNo order by BoxId Desc) = @intNextValue)  
    BEGIN  
     SET @MaxNo = @intNextValue  
     SET @intNextValue = @MaxNo - 1  
    END  
   ELSE  
    BEGIN  
     SET @intNextValue = @MaxNo  
    END    
   END  
      
   SET @intBoxId = @intNextValue -1 */  
  SET @intBoxId =  (select top 1 l.BoxId - 1 as NextBoxID from Rvlfboxid as l  
       left outer join Rvlfboxid as r on l.BoxId - 1 = r.BoxId  
       where r.BoxID is null order by l.Boxid desc)  
  END  
   
 SET NOCOUNT OFF  
END  
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GenerateMDTMsgID]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GenerateMDTMsgID] 
(
	@bigVehId AS BIGINT = 1
)

/*************************************************************************************
Stored Procedure Name	: rvlf_sp_GenerateMDTMsgID
Purpose					: Generate Group Id & Mesg Id for MDT
Created by				: Kumuthini
Created date			: 15-Jul-09
Updated by				: 
Updated date			: 
**************************************************************************************/

AS

BEGIN	

   DECLARE @bigBoxId AS BIGINT = 0
   SELECT @bigBoxId = BoxId FROM rvlfVehicleAssignment WHERE VehicleId = @bigVehId

   IF NOT EXISTS (SELECT BoxId FROM rvlfMDTMsg WHERE BoxId = @bigBoxId)
   BEGIN
   
		INSERT INTO rvlfMDTMsg (BoxId, GroupId, MsgId) VALUES (@bigBoxId, 1, 1)
		SELECT CONVERT(VARCHAR(3), GroupId) + ',' +  CONVERT(VARCHAR(3), MsgId) AS ID FROM rvlfMDTMsg WHERE BoxId = @bigBoxId
		UPDATE rvlfMDTMsg SET GroupId = GroupId + 1, MsgId = MsgId + 1 WHERE BoxId = @bigBoxId
   
   END
   ELSE
   BEGIN
   
		SELECT CONVERT(VARCHAR(3), GroupId) + ',' +  CONVERT(VARCHAR(3), MsgId) AS ID FROM rvlfMDTMsg WHERE BoxId = @bigBoxId
		UPDATE rvlfMDTMsg SET GroupId = GroupId + 1, MsgId = MsgId + 1 WHERE BoxId = @bigBoxId
		UPDATE rvlfMDTMsg SET GroupId = 1 WHERE GroupId = 1000 AND BoxId = @bigBoxId
		UPDATE rvlfMDTMsg SET MsgId = 1 WHERE MsgId = 10000 AND BoxId = @bigBoxId
	
   END

END





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GeozoneTripBasedRpt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Proc [dbo].[rvlf_sp_GeozoneTripBasedRpt]      
(   

 @bigFleetID bigint = null,                                                
 @intBoxID varchar(max) = null,                                                
 @dtStartDate datetime = null,                                                
 @dtEndDate datetime = null,                                                
 @tiBoxMsgInType tinyint = null,                                          
 @bigOrganizationID bigint = null,                                          
 @bigQueryingUser bigint = null                                                    
)      
as   
/******************************************************************************/                                          
-- Name  : rvlf_sp_GeozoneTripBasedRpt 480,null,'2016-06-25 08:00 AM', '2016-06-29 08:00PM', null, 230, 502        
-- Description : Show Geozone Details based on trip details 
-- Author  : Gopal.R  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--Created Date -30-sep-2014   
/******************************************************************************/   
begin      
 Declare @dtFDate datetime =@dtStartDate                                                
 Declare @dtEDate datetime =@dtEndDate                                                
                                                     
 DECLARE @HoursToBeAdded INT = 0                                                    
 DECLARE @MinsToBeAdded INT = 0                                                    
 DECLARE @DistanceCaptionPrefix varchar(15)                                    
 DECLARE @SpeedCaptionPrefix varchar(15)                                  
 DECLARE @DefaultDateFormat INT = 0                                                    
 DECLARE @ConversionFactor numeric (10,2) = 1.0                                                    
 DECLARE @Lang varchar(50),  @LangSetting varchar(20)                                
                                                               
    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,                        
 @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                                                    
                                                     
 -------------------date convertion--included by Narayanasamy on 03-Nov-09---------------------------------                                                                                        
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                                                    
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                                                    
                                                    
 ---------------------------------------------------------------------------------------------------------- 
 DECLARE @bitIsNotificationSent bit                                
 DECLARE @vcStreedAddress nvarchar(20) = NULL                               
 Declare @TotalGeozone int=0                                                   
 Declare @GeozoneActivityIn int=0                                  
 Declare @GeozoneActivityOut int=0                             
                                                                   
 DECLARE @tblGeozoneActivities TABLE                                                     
  (                             
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,                    
   MessageInID uniqueidentifier,            
   OriginDateTime Datetime,                                                    
   DateTimeReceived DateTime,                                                    
   BoxMsgInTypeDesc nvarchar(50),                                                    
   StreetAddress nvarchar(300),                                                    
   BoxId int,  VehicleDescription varchar(50),                                                    
   Vin varchar(20),                                                   
   LicensePlate varchar(20),                                                    
   FleetName varchar(50),                                                     
   OrganizationID bigint,                                                    
   GeozoneID bigint,                                                    
   BoxMsgInTypeId tinyint ,                                  
   Customprop varchar(max),      
   MxSpeed tinyint                                              
  )                                                    
  Declare @tempSummary table (       
   BoxId int,MaxOdometer varchar(20),MinOdometer varchar(20),TotalRunDuration int,TotalIdling int,TotalTrip int      
   )                                    
      
DECLARE @TripDetails table(TripId bigint ,BoxId bigint,StartDate datetime,EndDate datetime,OdometerStart bigint,OdometerEnd bigint,StartMessageInID uniqueidentifier,EndMessageInID uniqueidentifier,GeozoneIn int,GeozoneOut int,IsTripClosed bit,IdlingDuration int,StopTime int,IsDelete bit)                                      
 INSERT INTO @tblGeozoneActivities  SELECT h.MessageInID,                                                    
  h.OriginDateTime, h.DateTimeReceived,                                              
  case when @Lang='LanguageArNew' then isnull (m.BoxMsgInTypeDesc_Ar,m.BoxMsgInTypeDesc) else m.BoxMsgInTypeDesc end,           
  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'),'''','\''')                                             
  ,h.BoxId, v.VehicleDescription,v.Vin,v.LicensePlate,                                                    
   f.FleetName, v.OrganizationId,                 
   (CAST( SUBSTRING(h.CustomProp, CHARINDEX('GeozoneID=',h.CustomProp,0)+10,                                        
     (CHARINDEX(';',h.CustomProp,CHARINDEX('GeozoneID=',h.CustomProp,1)))                                         
  -(CHARINDEX('GeozoneID=',h.CustomProp,1)+10)) as bigint))  as GeozoneID,         
     h.BoxMsgInTypeId,h.CustomProp,h.Speed                                              
   FROM rvlfMsgInHst h                                                     
    INNER JOIN rvlfVehicleAssignment a ON h.BoxId = a.BoxId                                                    
    INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                                                     
    INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId                                     
    LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID                                                     
    INNER JOIN rvlfVehicle v ON a.VehicleId = v.VehicleId                                                     
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId                                                    
    INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId and f.FleetId = @bigFleetID                                                    
   WHERE                          
    (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR  h.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND               
    (h.BoxMsgintypeid = 5 OR h.BoxMsgintypeid = 6 or (h.BoxMsgInTypeId=114 and CustomProp like '%GeozoneInOutWithDuration:%')) and        
    (@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='' OR h.BoxMsgInTypeId = @tiBoxMsgInType) AND                                                    
    (@dtStartDate IS NULL OR (h.OriginDateTime BETWEEN @dtStartDate AND                                             
     @dtEndDate ) )     order by MessageInID                  
         
   --select * from @tblGeozoneActivities       
                          
declare @tempBoxid bigint                    
declare @tempGezoneid bigint                         
declare @Trip int=0                     
select @Trip=MIN(TripId) from @tblGeozoneActivities                  
                          
                           
while @Trip is not null                            
begin                            
   DECLARE @tripTobeProcessed bigint=0,@bigTripID bigint,@bigPreviousTripID bigint,@BintBoxID bigint,@bigOdoMeterReading bigint,@vcCustomProp varchar(max),@tiBoxMsgInTypeId bigint,@dtOriginDateTime datetime,@uiMsgInID uniqueidentifier ,@GeozoneId int    
 
      
 SELECT @bigTripID=TripId,@BintBoxID=BoxId, @vcCustomProp=Customprop,@tiBoxMsgInTypeId=BoxMsgInTypeId,@dtOriginDateTime=OriginDateTime,@uiMsgInID=MessageInID,@bigOdoMeterReading=(case when BoxMsgInTypeId=114 then[dbo].[rvlf_fn_GetParamValueWithIndex](@vcCustomProp,'Odometer:',null) else [dbo].[rvlf_fn_GetParamValueWithIndex](@vcCustomProp,'Odometer=',';')  end) ,@GeozoneId=GeozoneID     
  from @tblGeozoneActivities where TripId=@Trip      
--select @bigTripID,@BintBoxID,@bigOdoMeterReading,@vcCustomProp,@tiBoxMsgInType,@dtOriginDateTime,@uiMsgInID       
    -- Checks the Geozone status and update starts or ends the trip against boxid.                  
IF EXISTS (SELECT 1 FROM dbo.rvlfBoxId WHERE BoxID=@BintBoxID) --Afcons Clients                
BEGIN         
   SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM @TripDetails WHERE BoxID = @BintBoxID AND IsTripClosed = 0                  
IF(@bigOdoMeterReading IS NULL AND @tiBoxMsgInTypeId=114 AND CHARINDEX(';Odometer:',@vcCustomProp,0) <> 0)                
BEGIN     
  SELECT @bigOdoMeterReading=[dbo].[rvlf_fn_GetParamValueWithIndex](@vcCustomProp,'Odometer=',';')  
  --SUBSTRING(@vcCustomProp,CHARINDEX(';Odometer:',@vcCustomProp,0)+10,                
  --(LEN(@vcCustomProp)-(CHARINDEX(';Odometer:',@vcCustomProp,0)+9)))                
END        
                   
ELSE IF (@bigOdoMeterReading IS NULL AND @tiBoxMsgInTypeId=6)                
BEGIN     
   SELECT @bigOdoMeterReading=[dbo].[rvlf_fn_GetParamValueWithIndex](@vcCustomProp,'Odometer=',';')  
   --SUBSTRING(@vcCustomProp,CHARINDEX(';Odometer=',@vcCustomProp,0)+10,                
   --((CHARINDEX(';Battery',@vcCustomProp,0))-(CHARINDEX(';Odometer=',@vcCustomProp,0)+10)))                
END                        
 
 IF exists (select * from @TripDetails WHERE TripID = @tripTobeProcessed AND BoxId = @BintBoxID AND IsTripClosed = 0 and EndDate is null and 
 @tiBoxMsgInTypeId = 5)
 BEGIN
    UPDATE @TripDetails SET EndDate=@dtOriginDateTime ,GeozoneOut=@GeozoneId ,OdometerEnd = CASE WHEN @bigOdoMeterReading IS NULL THEN	 OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID , IsTripClosed = CASE WHEN @tiBoxMsgInTypeId = 5
 THEN 1 ELSE 0 END       WHERE TripID = @tripTobeProcessed AND BoxId = @BintBoxID AND IsTripClosed = 0
 END

IF @tiBoxMsgInTypeId IN (5,6,114)                
BEGIN            
   IF (@tiBoxMsgInTypeId = 6 OR (@tiBoxMsgInTypeId = 114 AND CHARINDEX('GeozoneInOutWithDuration:',@vcCustomProp,0) <> 0))                 
    AND @tripTobeProcessed = 0                  
    BEGIN                  
        SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM @TripDetails WHERE BoxId = @BintBoxID                   
        SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM @TripDetails                
        INSERT INTO @TripDetails(TripId, BoxId, StartDate, EndDate, OdometerStart, OdometerEnd,                  
         StartMessageInID , EndMessageInID, IsTripClosed,GeozoneIn)  VALUES                   
         (@bigTripID,@BintBoxID, @dtOriginDateTime, null, @bigOdoMeterReading ,                  
          null , @uiMsgInID , null, 0,@GeozoneId)                                       
          UPDATE @TripDetails SET StopTime = DATEDIFF(ss, EndDate, @dtOriginDateTime)                 
          WHERE BoxId = @BintBoxID AND TripID = @bigPreviousTripID                  
     END                  
     ELSE IF @tiBoxMsgInTypeId = 5 AND @tripTobeProcessed = 0                
     BEGIN                  
         SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM @TripDetails WHERE BoxID = @BintBoxID AND IsTripClosed = 1       
         IF EXISTS (SELECT * from @TripDetails where TripID = @tripTobeProcessed AND BoxId = @BintBoxID  and EndDate is null) 
         BEGIN
          UPDATE @TripDetails SET EndDate=@dtOriginDateTime , OdometerEnd = CASE WHEN @bigOdoMeterReading IS NULL                   
          THEN OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID ,IsTripClosed = 1 ,GeozoneOut=@GeozoneId                
          WHERE TripID = @tripTobeProcessed AND BoxId = @BintBoxID   
         END          
     END                  
END                  
END                    
                            
select @Trip=MIN(TripId) from @tblGeozoneActivities where TripId>@Trip                            
end                            
      
     -- select * from @tblGeozoneActivities
      --select * from @TripDetails
        
insert into @tempSummary      
select BoxId,MAX(OdometerEnd),min(OdometerStart),DATEDIFF(SECOND,min(StartDate),max(EndDate)),       
SUM(cast(dbo.rvlf_fn_GetIdlingTime_MFC(BoxId,StartDate,EndDate) as int)),count(BoxId) from @TripDetails group by BoxId      
      
----select * from @tempSummary      
             
select TripId,td.BoxId,TD.StartMessageInID,TD.EndMessageInID,TD.StartDate as StartDatesort,td.EndDate as EndDatesort,MH.StreetAddress as Departure,MH1.StreetAddress as Arrival,OG.GeozoneName as GeozonenameIn,OG1.GeozoneName as GeozonenameOut ,    
isnull((Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,TD.StartDate)),@DefaultDateFormat)+ ' '                         
 + Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,TD.StartDate)) as time),22)),'-') as OriginDateTimeIn,           
  
isnull((Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,TD.EndDate)),@DefaultDateFormat)+ ' '                         
 + Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,TD.EndDate)) as time),22)),'-') as OriginDateTimeOut,      
(isnull (OdometerEnd,0)-isnull(OdometerStart,0)) as Distance,      
dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SECOND,td.StartDate,Td.EndDate)) as RunningDurSec,      
case when dbo.rvlf_fn_GetIdlingTime_MFC(TD.BoxId,TD.StartDate,TD.EndDate)=0 then '-' else dbo.rvlf_fn_GetTimeFromSeconds(dbo.rvlf_fn_GetIdlingTime_MFC(TD.BoxId,TD.StartDate,TD.EndDate)) end as IdlingTime ,      
(select max(Speed) from rvlfMsgInHst where MessageInID between td.StartMessageInID and TD.EndMessageInID and BoxId=TD.BoxId  group by BoxId) as MaxSpeed,  
(TS.MinOdometer + ' - ' + TS.MaxOdometer) as odometer,(cast(TS.MaxOdometer as int) - casT(TS.MinOdometer as int) ) as TotalDistance,      
case when TS.TotalIdling=0 then '-' else  
dbo.rvlf_fn_GetTimeFromSeconds(TS.TotalIdling) end as TotalIdling,dbo.rvlf_fn_GetTimeFromSeconds(TS.TotalRunDuration)as TotalRunDuration,     
v.VehicleDescription,isnull(V.Vin,'-') as Vin ,V.LicensePlate,     
Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,                          
   Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                          
   Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate        



 from @TripDetails TD inner join rvlfMsgInHst as MH on TD.StartMessageInID=MH.MessageInID      
inner join rvlfMsgInHst MH1  on TD.EndMessageInID=MH1.MessageInID inner join @tempSummary TS on TD.BoxId=TS.BoxId 
inner join rvlfVehicleAssignment VA on TD.BoxId=VA.BoxId    
inner join rvlfVehicle V on VA.VehicleId=V.VehicleId  
inner join rvlfOrganizationGeozone OG on TD.GeozoneIn=OG.GeozoneId and V.OrganizationId= OG.OrganizationId
inner join rvlfOrganizationGeozone OG1 on TD.GeozoneOut=OG1.GeozoneId and V.OrganizationId= OG1.OrganizationId
where TD.IsTripClosed=1  
order by BoxId 
 end  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAccidentDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [dbo].[rvlf_sp_GetAccidentDetails]  
@TypeId INT = NULL,  
@bigOrganizationID BIGINT = null,    
@bigQueryingUser BIGINT = 0  
AS  
/*************************************************************************************        
Procedure Name  : rvlf_sp_GetAccidentDetails 2,6  
Purpose     : Get the accident details by table wise  
Created by    : Sakthi Gopinath S  
Created date   : 2014-Sep-24  
**************************************************************************************/        
BEGIN  
SET NOCOUNT ON  
 IF @TypeId = 1  
 BEGIN  
  SELECT AccidentTypeId,AccidentTypeName,AccidentTypeDesc FROM dbo.rvlfAccidentTypes WHERE OrganizationId=@bigOrganizationID AND IsDelete=0  
  SELECT AccidentReasonId,AccidentReasonName,AccidentReasonDesc FROM dbo.rvlfAccidentReasons WHERE OrganizationId=@bigOrganizationID AND [Status]=1  
  SELECT CorrectiveActionId,CorrectiveActionName,CorrectiveActionDesc FROM dbo.rvlfAccidentCorrectiveActions   
  WHERE OrganizationId=@bigOrganizationID AND [Status]=1  
 END  
 ELSE IF @TypeId = 2  
 BEGIN  
  SELECT ad.FleetId,ad.AccidentId,v.VehicleId,v.VehicleDescription,dm.DriverId,dm.DisplayName,at.AccidentTypeId,  
  at.AccidentTypeName,ad.AccidentDate,ad.Location,ad.RouteName,ad.DamageDetails,  
  ad.DamageCost,ar.AccidentReasonId,ar.AccidentReasonName,ac.CorrectiveActionId,ac.CorrectiveActionName,  
  ad.SupervisorName,ad.Trip,ad.IsAnyOneInjured,ad.AnyOneInjuredComments,ad.NoOfPassengers,ad.NoOfPassengersInjured,  
  ad.CompensationPaid,ad.IsInsuraceCoverage,ad.IsInsuranceClaimed,ad.InsuranceComents,  
  ad.ClaimedCost,ISNULL(CAST(ad.ClaimedOn AS VARCHAR),'') AS ClaimedOn,ad.ActionTaken  
  FROM rvlfAccidentDetails ad INNER JOIN rvlfAccidentTypes at ON at.AccidentTypeId=ad.AccidentTypeId AND ad.IsDelete=0  
  INNER JOIN rvlfVehicle v ON v.VehicleId=ad.VehicleId  
  INNER JOIN rvlfDriverMaster dm ON dm.DriverId=ad.DriverId  
  INNER JOIN rvlfAccidentReasons ar ON ar.AccidentReasonId=ad.AccidentReasonId AND ar.[Status]=1  
  INNER JOIN rvlfAccidentCorrectiveActions ac ON ac.CorrectiveActionId=ad.CorrectiveActionId AND ac.[Status]=1  
  WHERE ad.OrganizationId=@bigOrganizationID AND ad.IsDelete=0  
 END  
SET NOCOUNT OFF  
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarms]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetAlarms]      
 @bigAlarmID bigint = null,      
 @bigFleetID bigint = null,      
 @intBoxID varchar(50) = null,      
 @dtStartDate datetime = null,      
 @dtEndDate datetime = null,      
 @bigAcceptedBy bigint = null,      
 @bigClosedBy bigint = null,      
 @tiBoxMsgInType tinyint = null,      
 @bitIsNew bit = null,      
 @bitIsAccepted bit = null,      
 @bitIsClosed bit = null,      
 @bigOrganizationID bigint,      
 @bigQueryingUser bigint = 0,      
 @bitIsAlarmWindow bit = null,      
 @siSeverityLevel smallint = null,      
 @vcAlarmDesc varchar(50) = null      
AS      
/******************************************************************************/      
-- Name   : rvlf_sp_GetAlarms  @bigOrganizationID=84, @dtStartDate = '07/30/2011 08:00:00 AM',@dtEndDate='08/02/2011 08:00:00 PM' ,@bitIsAlarmWindow=1,@bigQueryingUser=62     
-- Description  : To get the alarm messages       
--    :   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin      
-- Author  : M. Jebamalai Jaya Chitra.      
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--    : 28-May-2009 MJJC Created Intial Version       
--              :   Updated by Kumuthini on 16-July-09 for displaying the datetime as per user prefreences      
--    : 25-Jan-2010 MJJC Updated the get alarm details function      
--              :   21-Feb-2010 MJJC Included defalut checking instead of name      
--    : 07-Apr-2010 KL  Included the title for the Severity image      
--              :   08-Apr-2010 KL      Made the Geozone Name smaller if long names      
--              :   11-May-2010 KL      Included padding for aligning the truck icon      
--    : 16-Jun-2010 MJJC Included the angler admin check in order to show or hide the device id row.      
--    : 29-Jun-2010 MJJC Made the Vehicle Display Name to be retrieved as Vehicle Description      
--    : 03-Aug-2010 SJ  Hanlded Previlege to show / hide Previlege for Acknowldge and Close Icon      
--    : 19-Aug-2010 LK      Changed the Vehicle Display Name to Vehicle Name      
--    : 30-Mar-2011 LK     Included the Driver Name      
--              : 04-Aug-2011 Ranjith Date format Included  
--              : 13-Oct-2011 Comment column included - sakthi
/******************************************************************************/      
BEGIN        
 SET NOCOUNT ON         
 
 Declare @dtFDate datetime =@dtStartDate
 Declare @dtEDate datetime =@dtEndDate        
 
 ------- Included by Kumuthini on 16-July-09 ---------------------        
         
 DECLARE @HoursToBeAdded INT = 0        
 DECLARE @MinsToBeAdded INT = 0        
  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         
    --FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz        
    --ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser       
        
       SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,        
     @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)       
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz        
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser         
         
 DECLARE @isAnglerAdmin bit        
         
 select @isAnglerAdmin = CASE WHEN UserGroupName = 'Angler Admin' Then 1 Else 0 END from rvlfUserGroup         
  where UserGroupId in (select UserGroupId from rvlfUserGroupAssignment where UserId=@bigQueryingUser)        
          
 --Included by Jeyanthi on 03-Aug-2010 to show / hide acknowledge         
 Declare @isPrevileged bit        
         
         
 SELECT @isPrevileged = COUNT(*) FROM rvlfUserGroupSecurity s        
     INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId        
     WHERE ga.UserId = @bigQueryingUser and ModuleID=4 and OperationTypeId =15        
             
 --End        
        
 IF @bigFleetID IS NULL         
 BEGIN        
  -- TODO: include the organization check in future        
  SELECT @bigFleetID = th.fleetId from rvlfFleet th where th.isDefault = 1        
   AND OrganizationId = @bigOrganizationID        
 END        
 IF @bitIsAlarmWindow IS NULL OR @bitIsAlarmWindow = 0        
 BEGIN        
  SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))        
  SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))        
          
  SELECT a.AlarmId,         
  --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreated,
  Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)),@DefaultDateFormat)  + ' ' + CONVERT(varchar, cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as time),22 ) as DateTimeCreated,         
  DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreatedSort,         
  a.BoxId, a.AcceptedBy, a.ClosedBy,         
  CASE WHEN a.DateTimeAccepted IS NULL THEN convert(varchar,a.DateTimeAccepted,@DefaultDateFormat)+ ' ' + CONVERT(varchar,cast(a.DateTimeAccepted as Time),22)  ELSE convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeAccepted)),@DefaultDateFormat) + ' ' + CONVERT(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeAccepted)) as Time),22) END AS DateTimeAccepted,         
  CASE WHEN a.DateTimeClosed IS NULL THEN CONVERT(varchar,a.DateTimeClosed,@DefaultDateFormat) + ' ' +  CONVERT(varchar,cast(a.DateTimeClosed as Time),22)  ELSE convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeClosed)),@DefaultDateFormat) + ' ' +  CONVERT(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeClosed))as Time),22)  END AS DateTimeClosed,         
  --dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType, null, a.DateTimeCreated) as AlarmDesc,        
  CASE WHEN a.AlarmType = 4 THEN 'Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *        
    @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' + CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END        
    WHEN a.AlarmType IN (5,6) THEN dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)        
    ELSE a.[Description] END  as AlarmDesc, a.AlarmLevelId,         
  ISNULL(a.StreetAddress,'Address not resolved') as StreetAddress, a.Lat, a.Long,  m.BoxMsgInTypeDesc,        
  CASE         
   WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN  0         
   WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1        
   WHEN /*a.AcceptedBy IS Not NULL AND */a.ClosedBy IS Not NULL THEN 2        
  END AS AlarmStatus,        
  CASE         
   WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 'Pending'         
   WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 'Acknowledged'        
   WHEN /*a.AcceptedBy IS Not NULL AND */a.ClosedBy IS Not NULL THEN 'Closed'        
  END AS AlarmStatusDesc,        
  acc.DisplayName + ' on ' + convert(varchar,a.DateTimeAccepted,@DefaultDateFormat) + ' '+ convert(varchar,cast(a.DateTimeAccepted as Time),22)   as ACKStatus,        
  clo.DisplayName+ ' on ' + convert(varchar ,a.DateTimeClosed,@DefaultDateFormat) + ' ' + convert(varchar ,cast(a.DateTimeClosed as Time),22) as ClosedStatus,        
  v.VehicleDescription,v.Vin, v.LicensePlate,         
  acc.DisplayName as AcceptedUser, clo.DisplayName as ClosedUser,a.Comments,
  f.FleetName, g.OrganizationName ,        
  CASE WHEN a.AlarmType Not IN (5,6) THEN        
   CASE WHEN v.Notify=1 THEN 'Notify'         
    WHEN v.Warning=1 THEN 'Warning' WHEN v.Critical =1 THEN 'Critical'         
    ELSE 'No Notification is set' END         
   WHEN a.AlarmType IN (5,6) THEN        
    (SELECT CASE WHEN Notify=1 THEN 'Notify'         
    WHEN Warning=1 THEN 'Warning' WHEN Critical =1 THEN 'Critical'         
    ELSE 'No Notification is set' END FROM rvlfOrganizationGeozone WHERE         
    GeozoneNo = CAST(a.[Description] AS Bigint) )        
  END as NotificationType, s.AlarmLevelName, CASE WHEN dm.DisplayName IS NULL THEN '-' ELSE dm.DisplayName END AS DriverName,
  Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate   
  
 FROM rvlfAlarm a INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId        
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId        
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId        
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId and f.FleetId = @bigFleetID        
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId        
  INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId         
  LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId        
  LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId        
  INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId        
  LEFT OUTER JOIN rvlfDriverMaster dm on dm.DriverId = a.DriverId        
 WHERE        
  ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND        
  (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR       
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND        
  ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND        
  ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND        
  ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND        
  ((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) AND        
  ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL)) AND        
  ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (/*a.AcceptedBy IS NOT NULL AND */a.ClosedBy IS NOT NULL)) AND        
  ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND        
  ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND        
  ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.Description like '%'+ @vcAlarmDesc  +'%') AND        
  m.VisibleWeb = 1        
  AND v.OrganizationId = @bigOrganizationID        
  ORDER BY DateTimeCreated DESC        
          
 --Included for Graphical Report         
 SELECT v.VehicleDescription,Count(a.AlarmId) 'TotalAlerts'        
 FROM rvlfAlarm a INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId        
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId        
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId        
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId and f.FleetId = @bigFleetID        
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId        
  INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId         
  LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId        
  LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId        
  INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId        
 WHERE        
  ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND        
  (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR        
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND        
  ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND        
  ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND        
  ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND        
  ((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) AND        
  ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL)) AND        
  ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (/*a.AcceptedBy IS NOT NULL AND */a.ClosedBy IS NOT NULL)) AND        
  ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND        
  ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND        
  ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.Description like '%'+ @vcAlarmDesc  +'%') AND        
  m.VisibleWeb = 1        
  AND v.OrganizationId = @bigOrganizationID        
  GROUP by VehicleDescription              
          
 END        
 ELSE         
 BEGIN        
    SELECT  '<li id="'+ CAST(a.AlarmId as varchar(15)) +'"><div class=''' +         
    CASE WHEN a.DateTimeAccepted IS null THEN 'yellow-box' ELSE 'green-box' END        
    +'''><span class=''top''></span><p><span class=''yellow-truck'' style="padding-top:3px"><a href=''javascript:ShowAlarm("'+        
    CAST(a.AlarmId as varchar(15)) + '","' + v.VehicleDescription +'","'+ CAST( a.BoxId AS varchar(6))+'","'+        
    CASE WHEN a.AlarmType = 4 THEN 'Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *        
     @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +        
    CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END        
     WHEN a.AlarmType IN (5,6) THEN        
      dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)        
     ELSE a.[Description] END+'","'+        
   Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) , @DefaultDateFormat)        
    +' ' + Convert(varchar, cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated))as Time) , 22)  
    +'","'+s.AlarmLevelName +'","'+        
    CASE         
     WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 'Pending'         
     WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 'Acknowledged'        
     WHEN a.ClosedBy IS Not NULL THEN 'Closed'        
    END        
    --commented on 03-Aug-2010 for restriction Acknowledge button        
    --+'",'+ CASE WHEN a.DateTimeAccepted IS NOT NULL THEN '1' ELSE '0' END +','+ cast(@isAnglerAdmin as char(1))+')''>'+v.DisplayName +'</a></span>&nbsp;<span class='''+ Lower(s.AlarmLevelName)        
    +'",'+ CASE WHEN a.DateTimeAccepted IS NOT NULL THEN '1' When @isPrevileged = 0 Then '1' Else '0' END +','+ cast(@isAnglerAdmin as char(1))+')''>'+v.VehicleDescription +'</a></span>&nbsp;<span class='''+ Lower(s.AlarmLevelName)        
    --End        
    +'-alert'' title='''+ s.AlarmLevelName +'''>&nbsp; </span><br /><span>'+ Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)), @DefaultDateFormat)+' '         
    + Convert(varchar, cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as Time),22) +'</span><br />'+         
    CASE WHEN a.AlarmType = 4 THEN '<span>Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *        
           @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +         
              CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END        
       WHEN a.AlarmType IN (5,6) THEN CASE WHEN LEN(SUBSTRING(dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),CHARINDEX('>',dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),0)+1,150))>30 THEN SUBSTRING (
  
    
dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),0,30)+'...'+''''          
      ELSE dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId) END          
      ELSE '<span>' + CASE WHEN LEN(a.[Description])>30 THEN SUBSTRING(a.[Description],0,30)+'...'+''''  ELSE a.[Description] END END +'</span></p></div></li>'         
   FROM rvlfAlarm a        
    INNER JOIN rvlfVehicleAssignment va ON va.BoxId = a.BoxId        
    INNER JOIN  rvlfVehicle v ON v.VehicleId = va.VehicleId        
    INNER JOIN rvlfSeverity s ON s.AlarmLevelId = a.AlarmLevelId        
   WHERE        
    ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND        
    (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR        
      a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND        
    ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND        
    ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND        
    ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND        
    (((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) OR        
    ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.ClosedBy IS NULL)) ) and         
    ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND        
    ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND        
    a.AlarmLevelId in (2,3)         
    AND v.OrganizationId = @bigOrganizationID        
    ORDER BY DateTimeCreated DESC        
 END        
         
--  SET NOCOUNT OFF        
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarms_Opt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetAlarms_Opt]                       
 @bigAlarmID bigint = null,                                              
 @bigFleetID bigint = null,                                              
 @intBoxID Varchar(Max) = null,                                              
 @dtStartDate datetime = null,                                              
 @dtEndDate datetime = null,                                              
 @bigAcceptedBy bigint = null,                                              
 @bigClosedBy bigint = null,                                              
 @tiBoxMsgInType tinyint = null,                                              
 @bitIs bit = null,                                     
 @bitIsAccepted bit = null,                                              
 @bitIsClosed bit = null,                                              
 @bigOrganizationID bigint,                                              
 @bigQueryingUser bigint = null,                        
 @bitIsAlarmWindow bit = null,                                              
 @siSeverityLevel smallint = null,                                              
 @vcAlarmDesc varchar(50) = null,                                    
 @isDashboard BIT = 0,            
 @bitIsNew  BIT = null,     
 @bigLastHours int = null,  
 @VehicleId Varchar(Max) = null,
 @bitIs1 BIT = 0,
 @bitIs2 BIT = 0,
 @bitIs3 BIT = 0,
 @bitIs4 BIT = 0,
 @ControllerId int=null,
 @ControllerName varchar(100)=null,
 @bigCustomerId varchar(100)=null
AS                        
/*********************************************************************************************************************************************/                  
-- Name   : rvlf_sp_GetAlarms_Opt @bigQueryingUser=N'453', @bigOrganizationID=N'86',@bitIsNew = true,@bitIs1=true
-- Description  : To get the alarm messages for alarm page and reports                        
-- Author  : V.Narayanasamy                  
-- Company  : Angler Technologies                        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                        
--    : 30-Nov-2011 VN Created Intial Version                         
/*********************************************************************************************************************************************/                        
BEGIN       
 -- Phone Gap Alarms page     
  if @VehicleId is not null and @VehicleId <> ''  
  Begin    
  Select @intBoxID = BoxId from rvlfVehicleAssignment where VehicleId =@VehicleId   
  End  
                       
 DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                  
  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit            
  DECLARE @Lang varchar(50),  @LangSetting varchar(20)                  
                     
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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                   
                     
 SELECT @isAnglerAdmin=CASE WHEN UserGroupName = 'Angler Admin' THEN 1 ELSE 0 END                   
  FROM rvlfUserGroupAssignment UGA                  
   INNER JOIN rvlfUserGroup UG ON UG.UserGroupId =UGA.UserGroupId        
WHERE UserId=@bigQueryingUser                                  
                      
  SELECT @isPrevileged=CASE WHEN COUNT(SecurityId)>0 THEN 1 ELSE 0 END                  
  FROM rvlfUserGroupSecurity s        
    INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId                          
  WHERE ga.UserId = @bigQueryingUser AND ModuleID=4 AND OperationTypeId=15                    
                    
 IF (@bigFleetID IS NULL OR @bigFleetID='')                  
  BEGIN                          
    SELECT @bigFleetID = fleetId FROM rvlfFleet                   
    WHERE  OrganizationId = @bigOrganizationID AND isDefault = 1                      
  END                     

--declare @CheckUser int =null,@lastname nvarchar(100),@CheckUGid int
	--select @CheckUGid=UserGroupId from rvlfUserGroupAssignment where UserId=@bigQueryingUser
	--select @lastname=LastName from rvlfUser where UserId=@bigQueryingUser
	--if((@lastname like '%VXL%' or @lastname like '%trinetra%') or @CheckUGid=1)
	--begin
	--	set @CheckUser=null
	--end
	--else
	--begin
	--	set @CheckUser=1
	--end
       
--------- included by vijay for link to dashboard ---------------                
IF(@isDashboard = 1)                    
 BEGIN                                           
 --select DATEDIFF(HOUR,@dtEDate,@dtFDate)                    
 SET @dtFDate = DATEADD(HOUR,DATEDIFF(HOUR,@dtEDate,@dtFDate),GETUTCDATE())                    
 --select @dtFDate                    
 SET @dtEDate =GETUTCDATE()                     
 SET @dtFDate=DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtFDate))                                          
 SET @dtEDate=DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEDate))                       
 --select GETDATE()                     
 --select @dtFDate                        
 END                
-----------------------------------------------------------------------                    
 if(@bigLastHours <> 0)        
    Begin    
      SET @dtEndDate=@dtStartDate          
      SET @dtStartDate= DATEADD(HOUR,(-1 * @bigLastHours) ,@dtStartDate)    
      print         @dtStartDate
      print   @dtEndDate
 End  
                 
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                          
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                    
    
     print         @dtStartDate
      print   @dtEndDate   
                         
 --Get the alarm details for alarm page.                         
 IF @bitIsAlarmWindow IS NULL OR @bitIsAlarmWindow = 0                
  BEGIN                                 
   SELECT AlarmId,DateTimeCreatedSort,boxid as BoxId,AlarmDesc,StreetAddress,lat,long,AlarmStatusDesc,VehicleDescription,AcceptedUser,ClosedUser,
   Comments,AlarmLevelName,DriverName,AlarmLevelID,AlarmStatusDescID,
   DateTimeCreated = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateTimeCreated),
   CASE WHEN DateTimeAccepted IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeAccepted,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeAccepted),22)) END AS DateTimeAccepted,                  
   CASE WHEN DateTimeClosed IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeClosed,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeClosed),22)) END AS DateTimeClosed,                      
   A.ACKUSER + ' on ' + convert(varchar,DateTimeAccepted,@DefaultDateFormat) + ' '+ convert(varchar,cast(DateTimeAccepted as Time),22) as ACKStatus,            
   A.CLOSEUSER + ' on ' + convert(varchar ,a.DateTimeClosed,@DefaultDateFormat) + ' ' + convert(varchar ,cast(a.DateTimeClosed as Time),22) as ClosedStatus,    
   (CAST(AlarmId AS VARCHAR(20))+'%'+ISNULL(CAST(DateTimeAccepted AS VARCHAR(20)),'null')+'%'+ISNULL(CAST(DateTimeClosed AS VARCHAR(20)),'null')+'%'+REPLACE(StreetAddress,'''','\''')) AS MapitValues    
   ,VehicleId,isMapIT, WarrantyEndDate, ControllerName,CustomerName,Rootcause,Correctiveaction

   FROM(                  
   SELECT distinct a.AlarmId,a.BoxId,a.Lat, a.Long,MD.EquipmentName as VehicleDescription,   acc.DisplayName as AcceptedUser, clo.DisplayName as ClosedUser,a.Comments,                
   (case when @Lang='LanguageArNew' THEN isnull(s.AlarmLevelName_Ar,s.AlarmLevelName)Else s.AlarmLevelName end) as AlarmLevelName,acc.DisplayName AS ACKUSER,clo.DisplayName AS CLOSEUSER,s.AlarmLevelID,                  
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreatedSort,a.DateTimeCreated,                                       
   isnull(d.AlarmName,a.[Description])   as AlarmDesc, 
   Replace(ISNULL( (    
   Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_AR,a.StreetAddress)     
   When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_Hin,a.StreetAddress)     
   ELSE a.StreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress,      
   CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN (case when @Lang='LanguageArNew' then N'لم يتم الاطلاع او الاغلاق' when @Lang='LanguageHindi' then N'अपूर्ण'  else 'Pending'  end)                        
    WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN (case when @Lang='LanguageArNew' then N'تم الاطلاع' when @Lang='LanguageHindi' then N'स्वीकृत' else 'Acknowledged'  end)                
    WHEN a.ClosedBy IS Not NULL THEN (case when @Lang='LanguageArNew' then N'تم الاغلاق' when @Lang='LanguageHindi' then N'बंद'  else 'Closed'  end) END AS AlarmStatusDesc,              
    CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN '1'                               
   WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN '2'               
   WHEN a.ClosedBy IS Not NULL THEN '3' END AS AlarmStatusDescID,                                                    
   null AS DriverName,                  
    CASE WHEN a.DateTimeAccepted IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeAccepted)) END AS DateTimeAccepted,        
    CASE WHEN a.DateTimeClosed IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeClosed)) END AS DateTimeClosed   
 ,MD.VehicleId,  
 (case when  a.StreetAddress not like 'N/A' and a.StreetAddress not like '%Address could not be Resolved!%'  then 1 else 0 end) as isMapIT  
  , cast(md.WarrantyEndDate as date) as WarrantyEndDate, '' as ControllerName,md.CustomerName,a.Rootcause,a.Correctiveaction
    FROM rvlfAlarm a                   
   -- INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId                          
    --INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                          
    INNER JOIN rvlfMAKDevices MD  ON a.BoxId=MD.BoxId
	INNER JOIN rvlfFleetVehicles fv ON MD.VehicleId = fv.VehicleId                                    
    INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId                           
    LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId                          
    LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId         
    INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId
	left join rvlfParamMst c on a.Description=c.ParamName --and MD.SubTypeId=c.VehicleTypeId
    left join rvlfAlarmsDesc d on c.ParamId=d.ParamID and MD.SubTypeId=d.EquipmentType                          
    --LEFT OUTER JOIN rvlfDriverMaster dm on dm.DriverId = a.DriverId                          	
	--INNER JOIN adrControllerMaster CM  ON CM.EquipmentId = a.BoxId and CM.ControllerPositionId = a.ControllerID  and (MD.SubTypeId=1 or CM.DCSIMId = a.DCSIM)
    WHERE (@bigFleetID IS NULL OR @bigFleetID='' OR Fv.FleetId=@bigFleetID)                   
    AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR a.BoxID in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                 
    AND (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
    AND MD.OrganizationId = @bigOrganizationID AND m.VisibleWeb = 1 
    --AND ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy)                   
    --AND ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy )                   
    AND ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel)       
    AND ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)                  
    AND ((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL))                   
    AND ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL))                   
    AND ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (a.ClosedBy IS NOT NULL))                       
    AND ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID )                   
    AND ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.Description like '%'+ @vcAlarmDesc  +'%') --and AlarmRepeatFlag=1            
	AND ((@bigCustomerId IS NULL OR @bigCustomerId='' or @bigCustomerId='0') OR MD.CustomerId = @bigCustomerId )
	--and ((@CheckUser is Null) or (MD.CustomerName = @lastname))
	--AND	((@ControllerId is null or @ControllerId = 0 or a.ControllerID = @ControllerId))
	--AND	((@ControllerName is null or @ControllerName = 'All' or CM.ControllerName = @ControllerName))
     ) AS A  ORDER BY DateTimeCreated DESC                   
                   
    SELECT DISTINCT(ug.OperationTypeId) ,ug.UserGroupId from rvlfOperationType op               
 INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId               
 INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId              
 INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId              
 INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId              
 INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId              
 INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId               
 WHERE ga.UserId = @bigQueryingUser and ug.ModuleId = 4              
                        
  END                   
 --Get the alarms details for report                      
 ELSE                   
  BEGIN                  
    SELECT distinct BoxId,VehicleDescription, EquipmentType, DateTimeCreatedSort, AlarmDesc, StreetAddress, AcceptedUser, ClosedUser, 
	AlarmLevelName, ControllerName, EquipmentLocation, FleetName, Vin, 
	DateTimeCreated = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateTimeCreated),     
    CASE WHEN DateTimeAccepted IS NULL THEN NULL 
	ELSE  (CONVERT(VARCHAR,DateTimeAccepted,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeAccepted),22)) END AS DateTimeAccepted,                  
    CASE WHEN DateTimeClosed IS NULL THEN NULL 
	ELSE  (CONVERT(VARCHAR,DateTimeClosed,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeClosed),22)) END AS DateTimeClosed,                  
    PasStartDate,PasEndDate,PasGenerateddate,StreetAddress,LicensePlate,AlarmLevelId,                   
    CASE	WHEN AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN  0                           
			WHEN AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
			WHEN a.ClosedBy IS Not NULL THEN 2                          
    END		AS AlarmStatusDesc,    
    CASE    WHEN AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN  0     
			WHEN AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
			WHEN a.ClosedBy IS Not NULL THEN 2                          
    END		AS AlarmStatus, WarrantyEndDate, Comments as Remarks,CustomerName,
	case when(@bigCustomerId is null or @bigCustomerId='' or @bigCustomerId='0') then 'ALL' else CustomerName end as Customerfilter,Rootcause,Correctiveaction
    FROM	(                  
		SELECT a.BoxId,MD.EquipmentName as VehicleDescription, VT.VehicleTypeName AS EquipmentType, '' as vin, 
		(Select top 1 rf.FleetName From rvlfFleet rf 
		Inner Join rvlfFleetVehicles rfv on rf.FleetId = rfv.FleetId 
		Where VehicleId = MD.VehicleId and rf.FleetName <> 'All') as FleetName, 
		'' as LicensePlate, a.AlarmLevelId,
		(case when @Lang='LanguageArNew' THEN isnull(s.AlarmLevelName_Ar,s.AlarmLevelName) Else s.AlarmLevelName end) as AlarmLevelName, a.AcceptedBy, a.ClosedBy, 
		Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,                  
		Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                  
		PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()),        
		CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 0 WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
			 WHEN a.ClosedBy IS Not NULL THEN 2 
		END  AS AlarmStatus, '' AS ControllerName, '' as EquipmentLocation, 
		DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreatedSort,a.DateTimeCreated,    
		CASE WHEN a.DateTimeAccepted IS NULL THEN NULL
			 ELSE dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,a.DateTimeAccepted) 
		END  AS DateTimeAccepted,
		CASE WHEN a.DateTimeClosed IS NULL THEN NULL
			 ELSE dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,a.DateTimeClosed)
		END  AS DateTimeClosed,		
		isnull(d.AlarmName,a.[Description])  as AlarmDesc,
		REPLACE(ISNULL((Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_AR,a.StreetAddress)
						When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_Hin,a.StreetAddress)
						ELSE a.StreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress,
		acc.DisplayName as AcceptedUser, clo.DisplayName as ClosedUser, a.Comments, cast(md.WarrantyEndDate as date) as WarrantyEndDate, CT.CustomerName,a.Rootcause,a.Correctiveaction
		FROM rvlfAlarm a
		INNER JOIN rvlfMAKDevices MD  ON a.BoxId=MD.BoxId
		INNER JOIN rvlfFleetVehicles fv ON MD.VehicleId = fv.VehicleId  
		INNER JOIN rvlfFleet F ON fv.FleetId = F.FleetId                   
		INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId          
		LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId         
		LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId        
		INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId         	    		
		LEFT OUTER JOIN rvlfVehicleType VT On MD.SubTypeId = VT.VehicleTypeId 
		INNER JOIN rvlfCustomers CT ON CT.CustomerId = MD.CustomerId
		left join rvlfParamMst c on a.Description=c.ParamName --and MD.SubTypeId=c.VehicleTypeId
    left join rvlfAlarmsDesc d on c.ParamId=d.ParamID and MD.SubTypeId=d.EquipmentType  
		WHERE (@bigFleetID IS NULL OR @bigFleetID='' OR Fv.FleetId=@bigFleetID)                   
		AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR a.BoxID in (SELECT * FROM rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                   
		AND (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR                         
		 a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
		AND MD.OrganizationId = @bigOrganizationID                      
		AND m.VisibleWeb = 1 AND s.AlarmLevelId IN (1,2,3)    
		--AND ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy)                   
		--AND ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy )                   
		AND ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel)                   
		AND ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)                  
		AND ((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL))           
		AND ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL))                   
		AND ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (a.ClosedBy IS NOT NULL))                       
		AND ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID )               
		AND ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.DESCRIPTION like '%'+ @vcAlarmDesc  +'%') --and AlarmRepeatFlag=1
		AND ((@bigCustomerId IS NULL OR @bigCustomerId='' or @bigCustomerId='0') OR ct.CustomerId = @bigCustomerId )               
		--and ((@CheckUser is Null) or (MD.CustomerName = @lastname))    
		--AND F.FleetName <> 'All'                               
     ) AS A  ORDER BY DateTimeCreated DESC 
	 END                                          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarms_Opt_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--USE [AdorPowertron]
--GO
--/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarms_Opt_PhoneGap]    Script Date: 25-Jan-2018 04:34:49 PM ******/
--SET ANSI_NULLS ON
--GO
--SET QUOTED_IDENTIFIER ON
--GO
----USE [AdorPowertron]
----GO
----/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarms_Opt_PhoneGap]    Script Date: 24-Jan-2018 10:58:34 AM ******/
----SET ANSI_NULLS ON
----GO
----SET QUOTED_IDENTIFIER ON
----GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAlarms_Opt_PhoneGap]  
  @bigFleetID bigint = NULL,                                              
  @intBoxID Varchar(Max) = null,                                              
  @dtStartDate datetime = NULL,     
  @dtEndDate datetime = NULL,                                                 
  @bigOrganizationID bigint=NULL,                                              
  @bigQueryingUser bigint = NULL,                                                   
  @bigLastHours int = NULL,  
  @VehicleId Varchar(Max) = NULL, 
  @controllerID varchar(50)=NULL, 
  @SeverityLevel tinyint =NULL            
AS             
/*********************************************************************************************************************************************/                        
-- Name   : rvlf_sp_GetAlarms_Opt_PhoneGap  @bigFleetID=176,@bigOrganizationID=86, @dtStartDate ='22-MAr-17',@dtEndDate='23-MAr-17',@bigQueryingUser=455,@bigLastHours  = 0,  @VehicleId  = 0
-- Description  : To get the alarm messages for alarm page and reports                        
-- Author  : V.Narayanasamy                  
-- Company  : Angler Technologies                        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                        
--    : 30-Nov-2011 VN Created Intial Version         
--       : 09-jan-2018 Asanraj include customername and controllername     
--	:   24-Jan-2018 Asanraj include filter ControllerID         
--  :   25-Jan-2018 Asanraj include filter by SeverityLevel Based.
/*********************************************************************************************************************************************/                        
BEGIN       
 -- Phone Gap Alarms page     
  if @VehicleId is not null and @VehicleId <> ''  
  Begin    
  Select @intBoxID = BoxId from rvlfVehicleAssignment where VehicleId =@VehicleId   
  End  
                       
 DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                  
  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit            
  DECLARE @Lang varchar(50),  @LangSetting varchar(20)                  
                     
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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                   
              
 SELECT @isAnglerAdmin=CASE WHEN UserGroupName = 'Angler Admin' THEN 1 ELSE 0 END                   
  FROM rvlfUserGroupAssignment UGA                  
   INNER JOIN rvlfUserGroup UG ON UG.UserGroupId =UGA.UserGroupId                   
  WHERE UserId=@bigQueryingUser                                  
                      
  SELECT @isPrevileged=CASE WHEN COUNT(SecurityId)>0 THEN 1 ELSE 0 END                  
  FROM rvlfUserGroupSecurity s        
    INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId                          
  WHERE ga.UserId = @bigQueryingUser AND ModuleID=4 AND OperationTypeId=15                    
                    
 IF (@bigFleetID IS NULL OR @bigFleetID='')                  
  BEGIN                          
    SELECT @bigFleetID = fleetId FROM rvlfFleet                   
    WHERE  OrganizationId = @bigOrganizationID AND isDefault = 1                      
  END                                         
              
-----------------------------------------------------------------------                    
 if(@bigLastHours <> 0)        
    Begin    
      SET @dtEndDate=@dtStartDate          
      SET @dtStartDate= DATEADD(HOUR,(-1 * @bigLastHours) ,@dtStartDate)    
      print         @dtStartDate
      print   @dtEndDate
 End  
                 
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                          
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                    
    
    
                         
 --Get the alarm details for alarm page.                                       
  BEGIN                                 
   SELECT ROW_NUMBER() over (order by DateTimeCreated DESC) as AutoNocolumn, AlarmId,
   CONVERT(varchar(max),DateTimeCreatedSort,21) as DateTimeCreatedSort,
   boxid as BoxId,replace(AlarmDesc,'°C',' degrees') as AlarmDesc,StreetAddress,lat,long,AlarmStatusDesc,VehicleDescription,
   --AcceptedUser,ClosedUser,Comments,
    replace(AlarmLevelName,' ','') as AlarmLevelName,
    --DriverName,AlarmLevelID,AlarmStatusDescID,                      
    DateTimeCreated = CONVERT(varchar(max),dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateTimeCreated),21),                                  
    --CONVERT(VARCHAR,DateTimeCreatedSort,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeCreatedSort),22) AS DateTimeCreated,                  
    --CASE WHEN DateTimeAccepted IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeAccepted,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeAccepted),22)) END AS DateTimeAccepted,                  
    --CASE WHEN DateTimeClosed IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeClosed,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeClosed),22)) END AS DateTimeClosed,                      
    --A.ACKUSER + ' on ' + convert(varchar,DateTimeAccepted,@DefaultDateFormat) + ' '+ convert(varchar,cast(DateTimeAccepted as Time),22) as ACKStatus,                           
    --A.CLOSEUSER + ' on ' + convert(varchar ,a.DateTimeClosed,@DefaultDateFormat) + ' ' + convert(varchar ,cast(a.DateTimeClosed as Time),22) as ClosedStatus,              
    --(CAST(AlarmId AS VARCHAR(20))+'%'+ISNULL(AcceptedUser,'null')+'%'+ISNULL(ClosedUser,'null')+'%'+REPLACE(StreetAddress,'''','\''')) AS MapitValues ,AlarmLevelId ,
    VehicleId,isMapIT,ISNULL(cast(a.ControllerID as varchar(50)),'-') as ControllerID,cast(WarrantyDate as varchar(100)) as WarrantyDate,ControllerName,CustomerName, CASE WHEN a.DateTimeClosed IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeClosed,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeClosed),22)) END AS DateTimeClosed
    FROM(                  
    SELECT a.AlarmId,a.BoxId,a.Lat, a.Long,v.VehicleDescription,
    -- acc.DisplayName as AcceptedUser, clo.DisplayName as ClosedUser,a.Comments,                
    (case when @Lang='LanguageArNew' THEN isnull(s.AlarmLevelName_Ar,s.AlarmLevelName)Else s.AlarmLevelName end) as AlarmLevelName,acc.DisplayName AS ACKUSER,clo.DisplayName AS CLOSEUSER,s.AlarmLevelID,                  
    DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreatedSort,
    a.DateTimeCreated,                                       
   
  --  CASE WHEN a.AlarmType = 4 THEN ''+(case when @Lang='LanguageArNew' then N'السرعة:'  when @Lang='LanguageHindi' then N'गति:'  else 'Speed:' end) + '' + CAST(CAST((CAST(a.[Description] AS numeric(10,0)) * @ConversionFactor)AS numeric(10,0)) AS varchar
--(250)) + ' ' +                
  --  --CASE WHEN a.AlarmType = 4 THEN 'Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) * @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +              
  --   CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END            
  --   WHEN a.AlarmType IN (5,6) THEN case when a.CustomProp IS null Then (dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)) 
  --   Else  (cast(dbo.rvlf_fn_GetAlarmDetails_New(a.CustomProp,a.AlarmType,a.BoxId, null,   
		--a.DateTimeCreated,@Lang) as nvarchar(100))) END                                                
      
  --    --ELSE case when a.CustomProp IS null Then a.[Description] Else  --GK May14
  --    ELSE case when a.[Description] IS not null Then a.[Description] Else  
  --    (cast(dbo.rvlf_fn_GetAlarmDetails_New(isnull(a.CustomProp,''),a.AlarmType,a.BoxId, null, a.DateTimeCreated,@Lang) as nvarchar(100))) END END as AlarmDesc,                             

     a.[Description] as AlarmDesc,
      
      -- WHEN a.AlarmType IN (5,6) THEN dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)                          
      --ELSE a.[Description] END  as AlarmDesc,                  
    --ISNULL(a.StreetAddress,'Address not resolved') as StreetAddress,      
    Replace(ISNULL( (    
    Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_AR,a.StreetAddress)     
    When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_Hin,a.StreetAddress)     
    ELSE a.StreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress,      
     CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN (case when @Lang='LanguageArNew' then N'لم يتم الاطلاع او الاغلاق' when @Lang='LanguageHindi' then N'अपूर्ण'  else 'Pending'  end)                        
      WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN (case when @Lang='LanguageArNew' then N'تم الاطلاع' when @Lang='LanguageHindi' then N'स्वीकृत' else 'Acknowledged'  end)                
      WHEN a.ClosedBy IS Not NULL THEN (case when @Lang='LanguageArNew' then N'تم الاغلاق' when @Lang='LanguageHindi' then N'बंद'  else 'Closed'  end) END AS AlarmStatusDesc,              
    --  CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN '1'                               
    -- WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN '2'               
    -- WHEN a.ClosedBy IS Not NULL THEN '3' END AS AlarmStatusDescID,                                                    
    --CASE WHEN dm.DisplayName IS NULL THEN '-' ELSE dm.DisplayName END AS DriverName,                  
    --CASE WHEN a.DateTimeAccepted IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeAccepted)) END AS DateTimeAccepted,                           
    --CASE WHEN a.DateTimeClosed IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeClosed)) END AS DateTimeClosed              
--      ,a.AlarmLevelId,                  
 v.VehicleId,  
 (case when  a.StreetAddress not like 'N/A' and a.StreetAddress not like '%Address could not be Resolved!%'  then 1 else 0 end) as isMapIT,a.ControllerID,
 cast(md.WarrantyEndDate as date) as WarrantyDate,CM.ControllerName,md.CustomerName,CASE WHEN a.DateTimeClosed IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeClosed)) END AS DateTimeClosed 
    FROM rvlfAlarm a                   
    INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId                          
    INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                          
	INNER JOIN rvlfmakdevices md ON md.VehicleId = v.VehicleId                          
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId                                    
    INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId                           
    LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId                          
    LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId         
    INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId
	LEFT OUTER JOIN rvlfVehicleType VT On MD.SubTypeId = VT.VehicleTypeId
	INNER JOIN adrControllerMaster CM  ON CM.EquipmentId = a.BoxId and CM.ControllerPositionId = a.ControllerID and (MD.SubTypeId=1 or CM.DCSIMId = a.DCSIM)	                    
    --LEFT OUTER JOIN rvlfDriverMaster dm on dm.DriverId = a.DriverId                          
    WHERE (Fv.FleetId=@bigFleetID)                   
    AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR a.BoxId = @intBoxID)                   
    AND (a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
    AND v.OrganizationId = @bigOrganizationID                      
    AND m.VisibleWeb = 1 AND (@controllerID is null or @controllerID='' or @controllerID='ALL' or cm.ControllerName =@controllerID) AND ((@SeverityLevel IS NULL OR @SeverityLevel='') OR a.AlarmLevelId = @SeverityLevel)                                                  
    ) AS A  ORDER BY DateTimeCreated DESC                   
                   
 --   SELECT DISTINCT(ug.OperationTypeId) ,ug.UserGroupId from rvlfOperationType op               
 --INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId               
 --INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId              
 --INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId              
 --INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId              
 --INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId              
 --INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId               
 --WHERE ga.UserId = @bigQueryingUser and ug.ModuleId = 4              
                        
  END                   
 --Get the alarms details for report                      
                
                   
END     

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarms_Opt_Techno]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE PROCEDURE [dbo].[rvlf_sp_GetAlarms_Opt_Techno]                       
 @bigAlarmID bigint = null,                                              
 @bigFleetID bigint = null,                                              
 @intBoxID Varchar(Max) = null,                                              
 @dtStartDate datetime = null,                                              
 @dtEndDate datetime = null,                                              
 @bigAcceptedBy bigint = null,                                              
 @bigClosedBy bigint = null,                                              
 @tiBoxMsgInType tinyint = null,                                              
 @bitIs bit = null,                                     
 @bitIsAccepted bit = null,                                              
 @bitIsClosed bit = null,                                              
 @bigOrganizationID bigint,                                              
 @bigQueryingUser bigint = null,                        
 @bitIsAlarmWindow bit = null,                                              
 @siSeverityLevel smallint = null,                                              
 @vcAlarmDesc varchar(50) = null,                                    
 @isDashboard BIT = 0,            
 @bitIsNew  BIT = null,     
 @bigLastHours int = null,  
 @VehicleId Varchar(Max) = null,
 @bitIs1 BIT = 0,
 @bitIs2 BIT = 0,
 @bitIs3 BIT = 0,
 @bitIs4 BIT = 0,
 @ControllerId int=null,
 @ControllerName varchar(100)=null,
 @bigCustomerId varchar(100)=null
AS                        
/*********************************************************************************************************************************************/                  
-- Name   : rvlf_sp_GetAlarms_Opt_Techno  @bigQueryingUser=N'453' ,@bigOrganizationID=N'86', @bitIsAlarmWindow=0,@bigFleetID=N'270'

--  @bigQueryingUser=N'564',@dtStartDate=N'26-jan-2019 12:00:00 PM',@bigOrganizationID=N'6',@dtEndDate=N'05-Feb-2019 12:00:00 PM',@bitIsAlarmWindow=1,@bigFleetID=N'0',@siSeverityLevel=3,@isDashboard=1,@tiBoxMsgInType=0
-- Description  : To get the alarm messages for alarm page and reports                        
-- Author  : V.Narayanasamy                  
-- Company  : Angler Technologies                        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                        
--    : 30-Nov-2011 VN Created Intial Version                         
/*********************************************************************************************************************************************/                        
BEGIN       
 -- Phone Gap Alarms page     
  if @VehicleId is not null and @VehicleId <> ''  
  Begin    
  Select @intBoxID = BoxId from rvlfVehicleAssignment where VehicleId =@VehicleId   
  End  
                       
 DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                  
  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit            
  DECLARE @Lang varchar(50),  @LangSetting varchar(20)                  
                     
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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      
   
SELECT @isAnglerAdmin=CASE WHEN UserGroupName = 'Angler Admin' THEN 1 ELSE 0 END                   
  FROM rvlfUserGroupAssignment UGA                  
   INNER JOIN rvlfUserGroup UG ON UG.UserGroupId =UGA.UserGroupId        
WHERE UserId=@bigQueryingUser                                  
                      
  SELECT @isPrevileged=CASE WHEN COUNT(SecurityId)>0 THEN 1 ELSE 0 END                  
  FROM rvlfUserGroupSecurity s        
    INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId                          
  WHERE ga.UserId = @bigQueryingUser AND ModuleID=4 AND OperationTypeId=15                    
                    
 --IF (@bigFleetID IS NULL OR @bigFleetID='')                  
 -- BEGIN                          
 --   SELECT @bigFleetID = fleetId FROM rvlfFleet                   
 --   WHERE  OrganizationId = @bigOrganizationID AND isDefault = 1                      
 -- END                     

--declare @CheckUser int =null,@lastname nvarchar(100),@CheckUGid int
	--select @CheckUGid=UserGroupId from rvlfUserGroupAssignment where UserId=@bigQueryingUser
	--select @lastname=LastName from rvlfUser where UserId=@bigQueryingUser
	--if((@lastname like '%VXL%' or @lastname like '%trinetra%') or @CheckUGid=1)
	--begin
	--	set @CheckUser=null
	--end
	--else
	--begin
	--	set @CheckUser=1
	--end
       
--------- included by vijay for link to dashboard ---------------                
IF(@isDashboard = 1)                    
 BEGIN                                           
 --select DATEDIFF(HOUR,@dtEDate,@dtFDate)                    
 SET @dtFDate = DATEADD(HOUR,DATEDIFF(HOUR,@dtEDate,@dtFDate),GETUTCDATE())                    
 --select @dtFDate                    
 SET @dtEDate =GETUTCDATE()                     
 SET @dtFDate=DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtFDate))                                          
 SET @dtEDate=DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEDate))   
 set @dtStartDate=null                    
 --select GETDATE()                     
 --select @dtFDate                        
 END                
-----------------------------------------------------------------------                    
 if(@bigLastHours <> 0)        
    Begin    
      SET @dtEndDate=@dtStartDate          
      SET @dtStartDate= DATEADD(HOUR,(-1 * @bigLastHours) ,@dtStartDate)    
      print         @dtStartDate
      print   @dtEndDate
 End  
                 
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                          
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                    
    
     print         @dtStartDate
      print   @dtEndDate   
                         
 --Get the alarm details for alarm page.                         
 IF @bitIsAlarmWindow IS NULL OR @bitIsAlarmWindow = 0                
  BEGIN         
   SELECT AlarmId,DateTimeCreatedSort,boxid as BoxId,AlarmDesc,StreetAddress,lat,long,AlarmStatusDesc,VehicleDescription,AcceptedUser,ClosedUser,
   Comments,AlarmLevelName,DriverName,AlarmLevelID,AlarmStatusDescID,
   DateTimeCreated = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateTimeCreated),
   CASE WHEN DateTimeAccepted IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeAccepted,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeAccepted),22)) END AS DateTimeAccepted,                  
   CASE WHEN DateTimeClosed IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeClosed,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeClosed),22)) END AS DateTimeClosed,                      
   A.ACKUSER + ' on ' + convert(varchar,DateTimeAccepted,@DefaultDateFormat) + ' '+ convert(varchar,cast(DateTimeAccepted as Time),22) as ACKStatus,        
   A.CLOSEUSER + ' on ' + convert(varchar ,a.DateTimeClosed,@DefaultDateFormat) + ' ' + convert(varchar ,cast(a.DateTimeClosed as Time),22) as ClosedStatus,    
   (CAST(AlarmId AS VARCHAR(20))+'%'+ISNULL(CAST(DateTimeAccepted AS VARCHAR(20)),'null')+'%'+ISNULL(CAST(DateTimeClosed AS VARCHAR(20)),'null')+'%'+REPLACE(StreetAddress,'''','\''')) AS MapitValues    
   ,VehicleId,isMapIT, WarrantyEndDate, ControllerName,CustomerName,Rootcause,Correctiveaction

   FROM(                  
   SELECT distinct a.AlarmId,a.BoxId,a.Lat, a.Long,MD.EquipmentName as VehicleDescription,   acc.DisplayName as AcceptedUser, clo.DisplayName as ClosedUser,a.Comments,                
   (case when @Lang='LanguageArNew' THEN isnull(s.AlarmLevelName_Ar,s.AlarmLevelName)Else s.AlarmLevelName end) as AlarmLevelName,acc.DisplayName AS ACKUSER,clo.DisplayName AS CLOSEUSER,s.AlarmLevelID,                  
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreatedSort,a.DateTimeCreated,                                       
   isnull(c.ParamDescription,a.[Description])   as AlarmDesc, 
   
   Replace(ISNULL( (    
   Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_AR,a.StreetAddress)     
   When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_Hin,a.StreetAddress)     
   ELSE a.StreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress,      
   CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN (case when @Lang='LanguageArNew' then N'لم يتم الاطلاع او الاغلاق' when @Lang='LanguageHindi' then N'अपूर्ण'  else 'Pending'  end)                        
    WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN (case when @Lang='LanguageArNew' then N'تم الاطلاع' when @Lang='LanguageHindi' then N'स्वीकृत' else 'Acknowledged'  end)                
    WHEN a.ClosedBy IS Not NULL THEN (case when @Lang='LanguageArNew' then N'تم الاغلاق' when @Lang='LanguageHindi' then N'बंद'  else 'Closed'  end) END AS AlarmStatusDesc,              
    CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN '1'                               
   WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN '2'               
   WHEN a.ClosedBy IS Not NULL THEN '3' END AS AlarmStatusDescID,                                                    
   null AS DriverName,                  
    CASE WHEN a.DateTimeAccepted IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeAccepted)) END AS DateTimeAccepted,        
    CASE WHEN a.DateTimeClosed IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeClosed)) END AS DateTimeClosed   
 ,MD.VehicleId,  
 (case when  a.StreetAddress not like 'N/A' and a.StreetAddress not like '%Address could not be Resolved!%'  then 1 else 0 end) as isMapIT  
  , cast(md.WarrantyEndDate as date) as WarrantyEndDate, '' as ControllerName,md.CustomerName,a.Rootcause,a.Correctiveaction
    FROM rvlfAlarm a                      
    INNER JOIN rvlfMAKDevices MD  ON a.BoxId=MD.BoxId
	INNER JOIN rvlfFleetVehicles fv ON MD.VehicleId = fv.VehicleId                                    
    INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId                           
    LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId                          
    LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId         
    INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId
	left join rvlfParamMst c on a.Description=c.ParamName                            	
	
	-- left join rvlf_CompactorDetails comp on  a.BoxId=comp.DeviceId and comp.SeqNo=c.vehicletypeid 
	-- (d.CompType is null or d.CompType=comp.CompType) and
	--left join rvlfAlarmsDesc d on c.ParamId=d.ParamID  and md.SubTypeId=d.EquipmentType and ( (d.VFantype is null or md.VFantype =0)  or (md.VFantype=1 and d.VFantype =1) or (md.VFantype>1 and d.VFantype>1 ))
	--and (comp.CompType is null or comp.CompType=d.CompType)
	
	--left join rvlf_CompactorDetails comp on (d.CompType is null or  d.CompType=comp.CompType) and a.BoxId=comp.DeviceId
    WHERE (@bigFleetID IS NULL OR @bigFleetID='' OR Fv.FleetId=@bigFleetID)                   
    AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR a.BoxID in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                 
    AND (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
    AND MD.OrganizationId = @bigOrganizationID AND m.VisibleWeb = 1 
    --AND ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy)                   
    --AND ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy )                   
    AND ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel)       
    AND ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)                  
    AND ((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL))                   
    AND ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL))                   
    AND ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (a.ClosedBy IS NOT NULL))                       
    AND ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID )                   
    AND ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.Description like '%'+ @vcAlarmDesc  +'%') --and AlarmRepeatFlag=1            
	--AND ((@bigCustomerId IS NULL OR @bigCustomerId='' or @bigCustomerId='0') OR MD.CustomerId = @bigCustomerId )
	--and ((@CheckUser is Null) or (MD.CustomerName = @lastname))	
	--and comp.Sno is not null
     ) AS A  ORDER BY DateTimeCreated,alarmid DESC                   
                   
    SELECT DISTINCT(ug.OperationTypeId) ,ug.UserGroupId from rvlfOperationType op               
 INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId               
 INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId              
 INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId              
 INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId              
 INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId              
 INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId               
 WHERE ga.UserId = @bigQueryingUser and ug.ModuleId = 4              
                        
  END                   
 --Get the alarms details for report   
 ELSE
 BEGIN
  SELECT distinct AlarmId,DateTimeCreatedSort,boxid as BoxId,AlarmDesc,StreetAddress,lat,long,AlarmStatusDesc,VehicleDescription,AcceptedUser,ClosedUser,
   Comments,AlarmLevelName,DriverName,AlarmLevelID,AlarmStatusDescID,
    Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,                  
    Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                  
     PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()),  
   DateTimeCreated = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateTimeCreated),
   CASE WHEN DateTimeAccepted IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeAccepted,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeAccepted),22)) END AS DateTimeAccepted,                  
   CASE WHEN DateTimeClosed IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeClosed,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeClosed),22)) END AS DateTimeClosed,                      
   A.ACKUSER + ' on ' + convert(varchar,DateTimeAccepted,@DefaultDateFormat) + ' '+ convert(varchar,cast(DateTimeAccepted as Time),22) as ACKStatus,        
   A.CLOSEUSER + ' on ' + convert(varchar ,a.DateTimeClosed,@DefaultDateFormat) + ' ' + convert(varchar ,cast(a.DateTimeClosed as Time),22) as ClosedStatus,    
   (CAST(AlarmId AS VARCHAR(20))+'%'+ISNULL(CAST(DateTimeAccepted AS VARCHAR(20)),'null')+'%'+ISNULL(CAST(DateTimeClosed AS VARCHAR(20)),'null')+'%'+REPLACE(StreetAddress,'''','\''')) AS MapitValues    
   ,VehicleId,isMapIT, WarrantyEndDate, ControllerName,CustomerName,Rootcause,Correctiveaction,
    CASE                        
    WHEN AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN  0     
    WHEN AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
    WHEN a.ClosedBy IS Not NULL THEN 2                          
    END AS AlarmStatus
   FROM(                  
   SELECT distinct a.AlarmId,a.BoxId,a.Lat, a.Long,MD.EquipmentName as VehicleDescription,   acc.DisplayName as AcceptedUser, clo.DisplayName as ClosedUser,a.Comments,                
   (case when @Lang='LanguageArNew' THEN isnull(s.AlarmLevelName_Ar,s.AlarmLevelName)Else s.AlarmLevelName end) as AlarmLevelName,acc.DisplayName AS ACKUSER,clo.DisplayName AS CLOSEUSER,s.AlarmLevelID,                  
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreatedSort,a.DateTimeCreated,                                       
   isnull(c.ParamDescription,a.[Description])   as AlarmDesc,   
   Replace(ISNULL( (    
   Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_AR,a.StreetAddress)     
   When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_Hin,a.StreetAddress)     
   ELSE a.StreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress,      
   CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN (case when @Lang='LanguageArNew' then N'لم يتم الاطلاع او الاغلاق' when @Lang='LanguageHindi' then N'अपूर्ण'  else 'Pending'  end)                        
    WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN (case when @Lang='LanguageArNew' then N'تم الاطلاع' when @Lang='LanguageHindi' then N'स्वीकृत' else 'Acknowledged'  end)                
    WHEN a.ClosedBy IS Not NULL THEN (case when @Lang='LanguageArNew' then N'تم الاغلاق' when @Lang='LanguageHindi' then N'बंद'  else 'Closed'  end) END AS AlarmStatusDesc,              
    CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN '1'                               
   WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN '2'               
   WHEN a.ClosedBy IS Not NULL THEN '3' END AS AlarmStatusDescID, 
      CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 0 WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
      WHEN a.ClosedBy IS Not NULL THEN 2 END AS AlarmStatus,                                                   
   null AS DriverName,                  
    CASE WHEN a.DateTimeAccepted IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeAccepted)) END AS DateTimeAccepted,        
    CASE WHEN a.DateTimeClosed IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeClosed)) END AS DateTimeClosed   
 ,MD.VehicleId,  
 (case when  a.StreetAddress not like 'N/A' and a.StreetAddress not like '%Address could not be Resolved!%'  then 1 else 0 end) as isMapIT  
  , cast(md.WarrantyEndDate as date) as WarrantyEndDate, '' as ControllerName,md.CustomerName,a.Rootcause,a.Correctiveaction,a.AcceptedBy,a.ClosedBy
    FROM rvlfAlarm a                      
    INNER JOIN rvlfMAKDevices MD  ON a.BoxId=MD.BoxId
	INNER JOIN rvlfFleetVehicles fv ON MD.VehicleId = fv.VehicleId                                    
    INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId                           
    LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId                          
    LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId         
    INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId
	left join rvlfParamMst c on a.Description=c.ParamName                            	
	
	-- left join rvlf_CompactorDetails comp on  a.BoxId=comp.DeviceId and comp.SeqNo=c.vehicletypeid 
	-- (d.CompType is null or d.CompType=comp.CompType) and
	--left join rvlfAlarmsDesc d on c.ParamId=d.ParamID  and md.SubTypeId=d.EquipmentType and ( (d.VFantype is null or md.VFantype =0)  or (md.VFantype=1 and d.VFantype =1) or (md.VFantype>1 and d.VFantype>1 ))
	--and (comp.CompType is null or comp.CompType=d.CompType)
	
	--left join rvlf_CompactorDetails comp on (d.CompType is null or  d.CompType=comp.CompType) and a.BoxId=comp.DeviceId
    WHERE (@bigFleetID IS NULL OR @bigFleetID='' OR Fv.FleetId=@bigFleetID)                   
    AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR a.BoxID in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                 
    AND (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
    AND MD.OrganizationId = @bigOrganizationID AND m.VisibleWeb = 1 
    --AND ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy)                   
    --AND ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy )                   
    AND ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel)       
    AND ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)                  
    AND ((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL))                   
    AND ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL))                   
    AND ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (a.ClosedBy IS NOT NULL))                       
    AND ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID )                   
    AND ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.Description like '%'+ @vcAlarmDesc  +'%') --and AlarmRepeatFlag=1            
	--AND ((@bigCustomerId IS NULL OR @bigCustomerId='' or @bigCustomerId='0') OR MD.CustomerId = @bigCustomerId )
	--and ((@CheckUser is Null) or (MD.CustomerName = @lastname))	
	--and comp.Sno is not null
     ) AS A  ORDER BY DateTimeCreated,alarmid DESC    
 END                   
 --ELSE                   
 -- BEGIN                  
 --   SELECT distinct BoxId,VehicleDescription, EquipmentType, DateTimeCreatedSort, AlarmDesc, StreetAddress, AcceptedUser, ClosedUser, 
	--AlarmLevelName, ControllerName, EquipmentLocation, FleetName, Vin, 
	--DateTimeCreated = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateTimeCreated),     
 --   CASE WHEN DateTimeAccepted IS NULL THEN NULL 
	--ELSE  (CONVERT(VARCHAR,DateTimeAccepted,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeAccepted),22)) END AS DateTimeAccepted,                  
 --   CASE WHEN DateTimeClosed IS NULL THEN NULL 
	--ELSE  (CONVERT(VARCHAR,DateTimeClosed,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeClosed),22)) END AS DateTimeClosed,                  
 --   PasStartDate,PasEndDate,PasGenerateddate,StreetAddress,LicensePlate,AlarmLevelId,                   
 --   CASE	WHEN AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN  0                           
	--		WHEN AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
	--		WHEN a.ClosedBy IS Not NULL THEN 2                          
 --   END		AS AlarmStatusDesc,    
 --   CASE    WHEN AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN  0     
	--		WHEN AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
	--		WHEN a.ClosedBy IS Not NULL THEN 2                          
 --   END		AS AlarmStatus, WarrantyEndDate, Comments as Remarks,CustomerName,
	--case when(@bigCustomerId is null or @bigCustomerId='' or @bigCustomerId='0') then 'ALL' else CustomerName end as Customerfilter,CorrectiveAction,Reason
 --  ,Reason as Rootcause
 --   FROM	(                  
	--	SELECT a.BoxId,MD.EquipmentName as VehicleDescription, VT.VehicleTypeName AS EquipmentType, '' as vin, 
	--	(Select top 1 rf.FleetName From rvlfFleet rf 
	--	Inner Join rvlfFleetVehicles rfv on rf.FleetId = rfv.FleetId 
	--	Where VehicleId = MD.VehicleId and rf.FleetName <> 'All') as FleetName, 
	--	'' as LicensePlate, a.AlarmLevelId,
	--	(case when @Lang='LanguageArNew' THEN isnull(s.AlarmLevelName_Ar,s.AlarmLevelName) Else s.AlarmLevelName end) as AlarmLevelName, a.AcceptedBy, a.ClosedBy, 
	--	Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,                  
	--	Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                  
	--	PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()),        
	--	CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 0 WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
	--		 WHEN a.ClosedBy IS Not NULL THEN 2 
	--	END  AS AlarmStatus, '' AS ControllerName, '' as EquipmentLocation, 
	--	DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreatedSort,a.DateTimeCreated,    
	--	CASE WHEN a.DateTimeAccepted IS NULL THEN NULL
	--		 ELSE dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,a.DateTimeAccepted) 
	--	END  AS DateTimeAccepted,
	--	CASE WHEN a.DateTimeClosed IS NULL THEN NULL
	--		 ELSE dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,a.DateTimeClosed)
	--	END  AS DateTimeClosed,		
	--	isnull(case when CHARINDEX('Ventilator',d.AlarmName,0)>0 then REPLACE(d.AlarmName,'label',comp.VentilatorModel ) else REPLACE(d.AlarmName,'label',comp.CompModel ) end
 --  ,a.[Description])   as AlarmDesc,
	--	--isnull(d.AlarmName,a.[Description])   as AlarmDesc,  
	--	REPLACE(ISNULL((Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_AR,a.StreetAddress)
	--					When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_Hin,a.StreetAddress)
	--					ELSE a.StreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress,
	--	acc.DisplayName as AcceptedUser, clo.DisplayName as ClosedUser, a.Comments, cast(md.WarrantyEndDate as date) as WarrantyEndDate, CT.CustomerName,a.Correctiveaction as CorrectiveAction,a.Rootcause as Reason 
	--	FROM rvlfAlarm a
	--	INNER JOIN rvlfMAKDevices MD  ON a.BoxId=MD.BoxId
	--	INNER JOIN rvlfFleetVehicles fv ON MD.VehicleId = fv.VehicleId  
	--	INNER JOIN rvlfFleet F ON fv.FleetId = F.FleetId                   
	--	INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId          
	--	LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId         
	--	LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId        
	--	INNER JOIN rvlfVehicleType VT On MD.SubTypeId = VT.VehicleTypeId
	--	INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId         	    		
	--	left join rvlfParamMst c on a.Description=c.ParamName 
	--	--left join rvlfAlarmsDesc d on c.ParamId=d.ParamID and MD.SubTypeId=d.EquipmentType    
	----	 left join rvlfAlarmsDesc d on c.ParamId=d.ParamID  and md.SubTypeId=d.EquipmentType and ( d.VFantype is null or md.VFantype=0 or md.VFantype=d.VFantype or md.VFantype>=d.VFantype)
	----left join rvlf_CompactorDetails comp on (d.CompType is null or  d.CompType=comp.CompType) and a.BoxId=comp.DeviceId              	
	--left join rvlf_CompactorDetails comp on  a.BoxId=comp.DeviceId and comp.SeqNo=c.vehicletypeid 
	---- (d.CompType is null or d.CompType=comp.CompType) and
	--left join rvlfAlarmsDesc d on c.ParamId=d.ParamID  and md.SubTypeId=d.EquipmentType and ( (d.VFantype is null or md.VFantype =0)  or (md.VFantype=1 and d.VFantype =1) or (md.VFantype>1 and d.VFantype>1 ))
	--and (comp.CompType is null or comp.CompType=d.CompType)
	--	INNER JOIN rvlfCustomers CT ON CT.CustomerId = MD.CustomerId
	--	WHERE (@bigFleetID IS NULL OR @bigFleetID='' OR Fv.FleetId=@bigFleetID)                   
	--	AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR a.BoxID in (SELECT * FROM rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                   
	--	AND (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR                         
	--	 a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
	--	AND MD.OrganizationId = @bigOrganizationID                      
	--	AND m.VisibleWeb = 1 AND s.AlarmLevelId IN (1,2,3)    
	--	--AND ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy)                   
	--	--AND ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy )                   
	--	AND ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel)                   
	--	AND ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)                  
	--	AND ((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL))           
	--	AND ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL))                   
	--	AND ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (a.ClosedBy IS NOT NULL))  
	--	AND ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID )  
	--	--AND ((@isDashboard IS NULL OR @isDashboard='0') OR (a.AlarmType = m.BoxMsgInTypeId and isnull(a.IsClosed,0) <> 1))
	--	AND ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.DESCRIPTION like '%'+ @vcAlarmDesc  +'%') --and AlarmRepeatFlag=1
	--	AND ((@bigCustomerId IS NULL OR @bigCustomerId='' or @bigCustomerId='0') OR ct.CustomerId = @bigCustomerId )               
	--	--and ((@CheckUser is Null) or (MD.CustomerName = @lastname))
	--	--and comp.Sno is not null 
	--	--AND F.FleetName <> 'All'                               
 --    ) AS A  ORDER BY DateTimeCreated DESC 
 --   	 END                                          
END 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarms_Opt_Test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetAlarms_Opt_Test]                       
 @bigAlarmID bigint = null,                                              
 @bigFleetID bigint = null,                                              
 @intBoxID Varchar(Max) = null,                                              
 @dtStartDate datetime = null,                                              
 @dtEndDate datetime = null,                                              
 @bigAcceptedBy bigint = null,                                              
 @bigClosedBy bigint = null,                                              
 @tiBoxMsgInType tinyint = null,                                              
 @bitIs bit = null,                                     
 @bitIsAccepted bit = null,                                              
 @bitIsClosed bit = null,                                              
 @bigOrganizationID bigint,                                              
 @bigQueryingUser bigint = null,                        
 @bitIsAlarmWindow bit = null,                                              
 @siSeverityLevel smallint = null,                                              
 @vcAlarmDesc varchar(50) = null,                                    
 @isDashboard BIT = 0,            
 @bitIsNew  BIT = null,     
 @bigLastHours int = null,  
 @VehicleId Varchar(Max) = null,
 @bitIs1 BIT = 0,
 @bitIs2 BIT = 0,
 @bitIs3 BIT = 0,
 @bitIs4 BIT = 0                              
AS                        
/*********************************************************************************************************************************************/                        
-- Name   : rvlf_sp_GetAlarms_opt  @bigFleetID=301,@bigOrganizationID=170, @dtStartDate ='2014-06-12 17:49:55',@dtEndDate='2014-06-12 17:49:55',@bitIsAlarmWindow=0,@bigQueryingUser=845,@bigLastHours  = 3,  @VehicleId  = 2112
-- Description  : To get the alarm messages for alarm page and reports                        
-- Author  : V.Narayanasamy                  
-- Company  : Angler Technologies                        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                        
--    : 30-Nov-2011 VN Created Intial Version                         
/*********************************************************************************************************************************************/                        
BEGIN       
 -- Phone Gap Alarms page     
  if @VehicleId is not null and @VehicleId <> ''  
  Begin    
  Select @intBoxID = BoxId from rvlfVehicleAssignment where VehicleId =@VehicleId   
  End  
                       
 DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                  
  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit            
  DECLARE @Lang varchar(50),  @LangSetting varchar(20)                  
                     
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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                   
                     
 SELECT @isAnglerAdmin=CASE WHEN UserGroupName = 'Angler Admin' THEN 1 ELSE 0 END                   
  FROM rvlfUserGroupAssignment UGA                  
   INNER JOIN rvlfUserGroup UG ON UG.UserGroupId =UGA.UserGroupId                   
  WHERE UserId=@bigQueryingUser                                  
                      
  SELECT @isPrevileged=CASE WHEN COUNT(SecurityId)>0 THEN 1 ELSE 0 END                  
  FROM rvlfUserGroupSecurity s        
    INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId                          
  WHERE ga.UserId = @bigQueryingUser AND ModuleID=4 AND OperationTypeId=15                    
                    
 IF (@bigFleetID IS NULL OR @bigFleetID='')                  
  BEGIN                          
    SELECT @bigFleetID = fleetId FROM rvlfFleet                   
    WHERE  OrganizationId = @bigOrganizationID AND isDefault = 1                      
  END                     
                    
--------- included by vijay for link to dashboard ---------------                
IF(@isDashboard = 1)                    
 BEGIN                                           
 --select DATEDIFF(HOUR,@dtEDate,@dtFDate)                    
 SET @dtFDate = DATEADD(HOUR,DATEDIFF(HOUR,@dtEDate,@dtFDate),GETUTCDATE())                    
 --select @dtFDate                    
 SET @dtEDate =GETUTCDATE()                     
 SET @dtFDate=DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtFDate))                                          
 SET @dtEDate=DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEDate))                       
 --select GETDATE()                     
 --select @dtFDate                        
 END                
-----------------------------------------------------------------------                    
 if(@bigLastHours <> 0)        
    Begin    
      SET @dtEndDate=@dtStartDate          
      SET @dtStartDate= DATEADD(HOUR,(-1 * @bigLastHours) ,@dtStartDate)    
      print         @dtStartDate
      print   @dtEndDate
 End  
                 
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                          
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                    
    
     print         @dtStartDate
      print   @dtEndDate   
                         
 --Get the alarm details for alarm page.                         
 IF @bitIsAlarmWindow IS NULL OR @bitIsAlarmWindow = 0                
  BEGIN                                 
   SELECT AlarmId,DateTimeCreatedSort,boxid as BoxId,AlarmDesc,StreetAddress,lat,long,AlarmStatusDesc,VehicleDescription,AcceptedUser,ClosedUser,                  
    Comments,AlarmLevelName,DriverName,AlarmLevelID,AlarmStatusDescID,                      
    DateTimeCreated = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateTimeCreated),                              
    --CONVERT(VARCHAR,DateTimeCreatedSort,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeCreatedSort),22) AS DateTimeCreated,                  
    CASE WHEN DateTimeAccepted IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeAccepted,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeAccepted),22)) END AS DateTimeAccepted,                  
    CASE WHEN DateTimeClosed IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeClosed,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeClosed),22)) END AS DateTimeClosed,                      
    A.ACKUSER + ' on ' + convert(varchar,DateTimeAccepted,@DefaultDateFormat) + ' '+ convert(varchar,cast(DateTimeAccepted as Time),22) as ACKStatus,                           
    A.CLOSEUSER + ' on ' + convert(varchar ,a.DateTimeClosed,@DefaultDateFormat) + ' ' + convert(varchar ,cast(a.DateTimeClosed as Time),22) as ClosedStatus,              
    (CAST(AlarmId AS VARCHAR(20))+'%'+ISNULL(AcceptedUser,'null')+'%'+ISNULL(ClosedUser,'null')+'%'+REPLACE(StreetAddress,'''','\''')) AS MapitValues  --,AlarmLevelId               
    ,VehicleId,isMapIT  
    FROM(                  
    SELECT a.AlarmId,a.BoxId,a.Lat, a.Long,v.VehicleDescription,   acc.DisplayName as AcceptedUser, clo.DisplayName as ClosedUser,a.Comments,                
    (case when @Lang='LanguageArNew' THEN isnull(s.AlarmLevelName_Ar,s.AlarmLevelName)Else s.AlarmLevelName end) as AlarmLevelName,acc.DisplayName AS ACKUSER,clo.DisplayName AS CLOSEUSER,s.AlarmLevelID,                  
    DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreatedSort,a.DateTimeCreated,                                       
   
    CASE WHEN a.AlarmType = 4 THEN ''+(case when @Lang='LanguageArNew' then N'السرعة:'  when @Lang='LanguageHindi' then N'गति:'  else 'Speed:' end) + '' + CAST(CAST((CAST(a.[Description] AS numeric(10,0)) * @ConversionFactor)AS numeric(10,0)) AS varchar(




250)) + ' ' +                
    --CASE WHEN a.AlarmType = 4 THEN 'Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) * @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +              
     CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END            
     WHEN a.AlarmType IN (5,6) THEN case when a.CustomProp IS null Then (dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)) 
     Else  (cast(dbo.rvlf_fn_GetAlarmDetails_New(a.CustomProp,a.AlarmType,a.BoxId, null,   
		a.DateTimeCreated,@Lang) as nvarchar(100))) END                                                
      
      --ELSE case when a.CustomProp IS null Then a.[Description] Else  --GK May14
      ELSE case when a.[Description] IS not null Then a.[Description] Else  
      (cast(dbo.rvlf_fn_GetAlarmDetails_New(isnull(a.CustomProp,''),a.AlarmType,a.BoxId, null, a.DateTimeCreated,@Lang) as nvarchar(100))) END END as AlarmDesc,                             
      
      -- WHEN a.AlarmType IN (5,6) THEN dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)                          
      --ELSE a.[Description] END  as AlarmDesc,                  
    --ISNULL(a.StreetAddress,'Address not resolved') as StreetAddress,      
    Replace(ISNULL( (    
    Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_AR,a.StreetAddress)     
    When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_Hin,a.StreetAddress)     
    ELSE a.StreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress,      
     CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN (case when @Lang='LanguageArNew' then N'لم يتم الاطلاع او الاغلاق' when @Lang='LanguageHindi' then N'अपूर्ण'  else 'Pending'  end)                        
      WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN (case when @Lang='LanguageArNew' then N'تم الاطلاع' when @Lang='LanguageHindi' then N'स्वीकृत' else 'Acknowledged'  end)                
      WHEN a.ClosedBy IS Not NULL THEN (case when @Lang='LanguageArNew' then N'تم الاغلاق' when @Lang='LanguageHindi' then N'बंद'  else 'Closed'  end) END AS AlarmStatusDesc,              
      CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN '1'                               
     WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN '2'               
     WHEN a.ClosedBy IS Not NULL THEN '3' END AS AlarmStatusDescID,                                                    
    CASE WHEN dm.DisplayName IS NULL THEN '-' ELSE dm.DisplayName END AS DriverName,                  
    CASE WHEN a.DateTimeAccepted IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeAccepted)) END AS DateTimeAccepted,                           
    CASE WHEN a.DateTimeClosed IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeClosed)) END AS DateTimeClosed              
--      ,a.AlarmLevelId                  
 ,v.VehicleId,  
 (case when  a.StreetAddress not like 'N/A' and a.StreetAddress not like '%Address could not be Resolved!%'  then 1 else 0 end) as isMapIT  
    FROM rvlfAlarm a                   
    INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId                          
    INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                          
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId                                    
    INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId                           
    LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId                          
    LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId         
    INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId                          
    LEFT OUTER JOIN rvlfDriverMaster dm on dm.DriverId = a.DriverId                          
    WHERE (@bigFleetID IS NULL OR @bigFleetID='' OR Fv.FleetId=@bigFleetID)                   
    AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR a.BoxID in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                 
    AND (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR                         
     a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
    AND v.OrganizationId = @bigOrganizationID                      
    AND m.VisibleWeb = 1                    
    AND ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy)                   
    AND ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy )                   
    AND ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel)                   
    AND ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)                  
    AND ((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL))                   
    AND ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL))                   
    AND ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (a.ClosedBy IS NOT NULL))                       
    AND ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID )                   
    AND ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.Description like '%'+ @vcAlarmDesc  +'%')                               
     ) AS A  ORDER BY DateTimeCreated DESC                   
                   
    SELECT DISTINCT(ug.OperationTypeId) ,ug.UserGroupId from rvlfOperationType op               
 INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId               
 INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId              
 INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId              
 INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId              
 INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId              
 INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId               
 WHERE ga.UserId = @bigQueryingUser and ug.ModuleId = 4              
   --get the total number of alarm based on vehicle---
  SELECT v.VehicleDescription,Count(a.AlarmId) 'TotalAlerts'       
 FROM rvlfAlarm a INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId          
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId          
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId          
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId and f.FleetId = @bigFleetID          
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId          
  INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId           
  LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId          
  LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId          
  INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId          
 WHERE          
  ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND          
  (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR          
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND          
  ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND          
  ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND          
  ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND          
  --((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) AND          
  ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL)) AND          
  ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (/*a.AcceptedBy IS NOT NULL AND */a.ClosedBy IS NOT NULL)) AND          
  ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND          
  ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND          
  ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.Description like '%'+ @vcAlarmDesc  +'%') AND          
  m.VisibleWeb = 1          
  AND v.OrganizationId = @bigOrganizationID          
  GROUP by VehicleDescription 
  ------END-----------
 ---- Count the alarm based on Severity level----
   SELECT Count(a.AlarmId) 'SeverityAlarms',s.AlarmLevelName
 FROM rvlfAlarm a INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId          
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId          
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId          
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId and f.FleetId = @bigFleetID          
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId          
  INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId           
  LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId          
  LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId          
  INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId          
 WHERE          
  ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND          
  (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR          
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND          
  ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND          
  ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND          
  ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND          
  --((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) AND          
  ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL)) AND          
  ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (/*a.AcceptedBy IS NOT NULL AND */a.ClosedBy IS NOT NULL)) AND          
  ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND          
  ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND          
  ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.Description like '%'+ @vcAlarmDesc  +'%') AND          
  m.VisibleWeb = 1          
  AND v.OrganizationId = @bigOrganizationID          
  GROUP by s.AlarmLevelName             
  --- END-----       
 ---count the statitics based on Alarms--
   select count(s.AlarmLevelId) 'AlarmStatistics',case WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 'Pending'           
   WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 'Acknowledged'          
   WHEN /*a.AcceptedBy IS Not NULL AND */a.ClosedBy IS Not NULL THEN 'Closed'          
  END AS AlarmStatusDesc 
  FROM rvlfAlarm a INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId          
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId          
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId          
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId and f.FleetId = @bigFleetID          
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId          
  INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId           
  LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId          
  LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId          
  INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId          
  LEFT OUTER JOIN rvlfDriverMaster dm on dm.DriverId = a.DriverId        
 WHERE          
  ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND          
  (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR         
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND          
  ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND          
  ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND          
  ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND          
 -- ((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) AND          
  ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL)) AND          
  ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (/*a.AcceptedBy IS NOT NULL AND */a.ClosedBy IS NOT NULL)) AND          
  ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND          
  ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND          
  ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.Description like '%'+ @vcAlarmDesc  +'%') AND          
  m.VisibleWeb = 1          
  AND v.OrganizationId = @bigOrganizationID 
   GROUP by case WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 'Pending'           
   WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 'Acknowledged'          
   WHEN /*a.AcceptedBy IS Not NULL AND */a.ClosedBy IS Not NULL THEN 'Closed'   
 ---End---      
  END                                        
  END                   
 --Get the alarms details for report                      
 ELSE                   
  BEGIN                  
    SELECT BoxId,VehicleDescription, DateTimeCreatedSort,AlarmDesc,StreetAddress,AcceptedUser,ClosedUser,AlarmLevelName,DriverName,FleetName,Vin,                  
    DateTimeCreated = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateTimeCreated),                              
    --(CONVERT(VARCHAR,DateTimeCreatedSort,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeCreatedSort),22)) AS DateTimeCreated,                  
    CASE WHEN DateTimeAccepted IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeAccepted,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeAccepted),22)) END AS DateTimeAccepted,                  
    CASE WHEN DateTimeClosed IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeClosed,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeClosed),22)) END AS DateTimeClosed,                  
    PasStartDate,PasEndDate,PasGenerateddate,DriverName ,StreetAddress,LicensePlate,AlarmLevelId,                   
    CASE                        
    WHEN AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN  0                           
    WHEN AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
    WHEN a.ClosedBy IS Not NULL THEN 2                          
    END AS AlarmStatusDesc,    
    CASE                        
    WHEN AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN  0     
    WHEN AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
    WHEN a.ClosedBy IS Not NULL THEN 2                          
    END AS AlarmStatus    
    FROM(                  
    SELECT a.BoxId,v.VehicleDescription,V.Vin,F.FleetName,V.LicensePlate,a.AlarmLevelId,(case when @Lang='LanguageArNew' THEN isnull(s.AlarmLevelName_Ar,s.AlarmLevelName)Else s.AlarmLevelName end) as AlarmLevelName,a.AcceptedBy,a.ClosedBy,               




   
    Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,                  
    Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                  
     PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()),                              
--Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,         


       
             
             
    CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 0 WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
      WHEN a.ClosedBy IS Not NULL THEN 2 END AS AlarmStatus,                    
    CASE WHEN dm.DisplayName IS NULL THEN '-' ELSE dm.DisplayName END AS DriverName,                  
    DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreatedSort,a.DateTimeCreated,    
    CASE WHEN a.DateTimeAccepted IS NULL THEN NULL ELSE dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,a.DateTimeAccepted) END AS DateTimeAccepted,                  
    --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeAccepted)) END AS DateTimeAccepted,                           
    CASE WHEN a.DateTimeClosed IS NULL THEN NULL ELSE dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,a.DateTimeClosed) END AS DateTimeClosed,                  
    --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeClosed)) END AS DateTimeClosed,                   
     CASE WHEN a.AlarmType = 4 THEN ''+(case when @Lang='LanguageArNew' then N'السرعة:' when @Lang='LanguageHindi' then N'गति:'  else 'Speed:' end) + '' +  
      CAST(CAST((CAST(a.[Description] AS numeric(10,0)) * @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +                   
     CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END             
       WHEN a.AlarmType IN (5,6) THEN case when a.CustomProp IS null Then (dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)) ELse  (cast(dbo.rvlf_fn_GetAlarmDetails_New(a.CustomProp,a.AlarmType,a.BoxId, null,   
       a.DateTimeCreated,@Lang) as nvarchar(100))) END                                                
      ELSE case when a.CustomProp IS null Then a.[Description] else  (cast(dbo.rvlf_fn_GetAlarmDetails_New(a.CustomProp,a.AlarmType,a.BoxId, null, a.DateTimeCreated,@Lang) as nvarchar(100))) END END as AlarmDesc,                                     
        
          
      -- WHEN a.AlarmType IN (5,6) THEN dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)                          
     -- ELSE a.[Description] END  as AlarmDesc,                  
    --ISNULL(a.StreetAddress,'Address not resolved') as StreetAddress,                      
     Replace(ISNULL( (    
    Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_AR,a.StreetAddress)     
    When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_Hin,a.StreetAddress)     
    ELSE a.StreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress,         
      acc.DisplayName as AcceptedUser, clo.DisplayName as ClosedUser                  
    FROM rvlfAlarm a                   
    INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId                          
    INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                          
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId                   
    INNER JOIN rvlfFleet F ON fv.FleetId=F.FleetId                                    
    INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId                           
    LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId                          
    LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId                 
    INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId                          
    LEFT OUTER JOIN rvlfDriverMaster dm on dm.DriverId = a.DriverId                          
    WHERE (@bigFleetID IS NULL OR @bigFleetID='' OR Fv.FleetId=@bigFleetID)                   
    AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR a.BoxID in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                   
    AND (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR                         
     a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
    AND v.OrganizationId = @bigOrganizationID                      
    AND m.VisibleWeb = 1 AND s.AlarmLevelId IN (1,2,3)    
    AND ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy)                   
    AND ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy )                   
    AND ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel)                   
    AND ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)                  
    AND ((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL))                   
    AND ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL))                   
    AND ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (a.ClosedBy IS NOT NULL))                       
    AND ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID )                   
    AND ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.Description like '%'+ @vcAlarmDesc  +'%')                               
     ) AS A  ORDER BY DateTimeCreated DESC                   
  END                       
                   
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarms_Opt_VXL]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE PROCEDURE [dbo].[rvlf_sp_GetAlarms_Opt_VXL]                       
 @bigAlarmID bigint = null,                                              
 @bigFleetID bigint = null,                                              
 @intBoxID Varchar(Max) = null,                                              
 @dtStartDate datetime = null,                                              
 @dtEndDate datetime = null,                                              
 @bigAcceptedBy bigint = null,                                              
 @bigClosedBy bigint = null,                                              
 @tiBoxMsgInType tinyint = null,                                              
 @bitIs bit = null,                                     
 @bitIsAccepted bit = null,                                              
 @bitIsClosed bit = null,                                              
 @bigOrganizationID bigint,                                              
 @bigQueryingUser bigint = null,                        
 @bitIsAlarmWindow bit = null,                                              
 @siSeverityLevel smallint = null,                                              
 @vcAlarmDesc varchar(50) = null,                                    
 @isDashboard BIT = 0,            
 @bitIsNew  BIT = null,     
 @bigLastHours int = null,  
 @VehicleId Varchar(Max) = null,
 @bitIs1 BIT = 0,
 @bitIs2 BIT = 0,
 @bitIs3 BIT = 0,
 @bitIs4 BIT = 0,
 @ControllerId int=null,
 @ControllerName varchar(100)=null,
 @bigCustomerId varchar(100)=null
AS                        
/*********************************************************************************************************************************************/                  
-- Name   : rvlf_sp_GetAlarms_Opt_VXL  @bigQueryingUser=N'453' ,@bigOrganizationID=N'86', @bitIsAlarmWindow=0,@bigFleetID=N'270'

--rvlf_sp_GetAlarms_Opt_VXL  @bigQueryingUser=N'564',@dtStartDate=N'26-jan-2019 12:00:00 PM',@bigOrganizationID=N'6',@dtEndDate=N'05-Feb-2019 12:00:00 PM',@bitIsAlarmWindow=1,@bigFleetID=N'0',@siSeverityLevel=3,@isDashboard=1,@tiBoxMsgInType=0
-- Description  : To get the alarm messages for alarm page and reports                        
-- Author  : V.Narayanasamy                  
-- Company  : Angler Technologies                        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                        
--    : 30-Nov-2011 VN Created Intial Version                         
/*********************************************************************************************************************************************/                        
BEGIN       
 -- Phone Gap Alarms page     
  if @VehicleId is not null and @VehicleId <> ''  
  Begin    
  Select @intBoxID = BoxId from rvlfVehicleAssignment where VehicleId =@VehicleId   
  End  
                       
 DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                  
  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit            
  DECLARE @Lang varchar(50),  @LangSetting varchar(20)                  
                     
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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      
   
SELECT @isAnglerAdmin=CASE WHEN UserGroupName = 'Angler Admin' THEN 1 ELSE 0 END                   
  FROM rvlfUserGroupAssignment UGA                  
   INNER JOIN rvlfUserGroup UG ON UG.UserGroupId =UGA.UserGroupId        
WHERE UserId=@bigQueryingUser                                  
                      
  SELECT @isPrevileged=CASE WHEN COUNT(SecurityId)>0 THEN 1 ELSE 0 END                  
  FROM rvlfUserGroupSecurity s        
    INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId                          
  WHERE ga.UserId = @bigQueryingUser AND ModuleID=4 AND OperationTypeId=15                    
                    
 --IF (@bigFleetID IS NULL OR @bigFleetID='')                  
 -- BEGIN                          
 --   SELECT @bigFleetID = fleetId FROM rvlfFleet                   
 --   WHERE  OrganizationId = @bigOrganizationID AND isDefault = 1                      
 -- END                     

--declare @CheckUser int =null,@lastname nvarchar(100),@CheckUGid int
	--select @CheckUGid=UserGroupId from rvlfUserGroupAssignment where UserId=@bigQueryingUser
	--select @lastname=LastName from rvlfUser where UserId=@bigQueryingUser
	--if((@lastname like '%VXL%' or @lastname like '%trinetra%') or @CheckUGid=1)
	--begin
	--	set @CheckUser=null
	--end
	--else
	--begin
	--	set @CheckUser=1
	--end
       
--------- included by vijay for link to dashboard ---------------                
IF(@isDashboard = 1)                    
 BEGIN                                           
 --select DATEDIFF(HOUR,@dtEDate,@dtFDate)                    
 SET @dtFDate = DATEADD(HOUR,DATEDIFF(HOUR,@dtEDate,@dtFDate),GETUTCDATE())                    
 --select @dtFDate                    
 SET @dtEDate =GETUTCDATE()                     
 SET @dtFDate=DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtFDate))                                          
 SET @dtEDate=DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),@dtEDate))   
 set @dtStartDate=null                    
 --select GETDATE()                     
 --select @dtFDate                        
 END                
-----------------------------------------------------------------------                    
 if(@bigLastHours <> 0)        
    Begin    
      SET @dtEndDate=@dtStartDate          
      SET @dtStartDate= DATEADD(HOUR,(-1 * @bigLastHours) ,@dtStartDate)    
      print         @dtStartDate
      print   @dtEndDate
 End  
                 
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                          
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                    
    
     print         @dtStartDate
      print   @dtEndDate   
                         
 --Get the alarm details for alarm page.                         
 IF @bitIsAlarmWindow IS NULL OR @bitIsAlarmWindow = 0                
  BEGIN         
   SELECT AlarmId,DateTimeCreatedSort,boxid as BoxId,AlarmDesc,StreetAddress,lat,long,AlarmStatusDesc,VehicleDescription,AcceptedUser,ClosedUser,
   Comments,AlarmLevelName,DriverName,AlarmLevelID,AlarmStatusDescID,
   DateTimeCreated = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateTimeCreated),
   CASE WHEN DateTimeAccepted IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeAccepted,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeAccepted),22)) END AS DateTimeAccepted,                  
   CASE WHEN DateTimeClosed IS NULL THEN NULL ELSE  (CONVERT(VARCHAR,DateTimeClosed,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeClosed),22)) END AS DateTimeClosed,                      
   A.ACKUSER + ' on ' + convert(varchar,DateTimeAccepted,@DefaultDateFormat) + ' '+ convert(varchar,cast(DateTimeAccepted as Time),22) as ACKStatus,        
   A.CLOSEUSER + ' on ' + convert(varchar ,a.DateTimeClosed,@DefaultDateFormat) + ' ' + convert(varchar ,cast(a.DateTimeClosed as Time),22) as ClosedStatus,    
   (CAST(AlarmId AS VARCHAR(20))+'%'+ISNULL(CAST(DateTimeAccepted AS VARCHAR(20)),'null')+'%'+ISNULL(CAST(DateTimeClosed AS VARCHAR(20)),'null')+'%'+REPLACE(StreetAddress,'''','\''')) AS MapitValues    
   ,VehicleId,isMapIT, WarrantyEndDate, ControllerName,CustomerName,Rootcause,Correctiveaction

   FROM(                  
   SELECT distinct a.AlarmId,a.BoxId,a.Lat, a.Long,MD.EquipmentName as VehicleDescription,   acc.DisplayName as AcceptedUser, clo.DisplayName as ClosedUser,a.Comments,                
   (case when @Lang='LanguageArNew' THEN isnull(s.AlarmLevelName_Ar,s.AlarmLevelName)Else s.AlarmLevelName end) as AlarmLevelName,acc.DisplayName AS ACKUSER,clo.DisplayName AS CLOSEUSER,s.AlarmLevelID,                  
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreatedSort,a.DateTimeCreated,                                       
   --isnull(d.AlarmName,a.[Description])   as AlarmDesc, 
   isnull(case when CHARINDEX('Ventilator',d.AlarmName,0)>0 then REPLACE(d.AlarmName,'label',isnull(comp.VentilatorModel,'') ) else REPLACE(d.AlarmName,'label',isnull(comp.CompModel,'') ) end
   ,a.[Description])   as AlarmDesc,
   Replace(ISNULL( (    
   Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_AR,a.StreetAddress)     
   When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_Hin,a.StreetAddress)     
   ELSE a.StreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress,      
   CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN (case when @Lang='LanguageArNew' then N'لم يتم الاطلاع او الاغلاق' when @Lang='LanguageHindi' then N'अपूर्ण'  else 'Pending'  end)                        
    WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN (case when @Lang='LanguageArNew' then N'تم الاطلاع' when @Lang='LanguageHindi' then N'स्वीकृत' else 'Acknowledged'  end)                
    WHEN a.ClosedBy IS Not NULL THEN (case when @Lang='LanguageArNew' then N'تم الاغلاق' when @Lang='LanguageHindi' then N'बंद'  else 'Closed'  end) END AS AlarmStatusDesc,              
    CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN '1'                               
   WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN '2'               
   WHEN a.ClosedBy IS Not NULL THEN '3' END AS AlarmStatusDescID,                                                    
   null AS DriverName,                  
    CASE WHEN a.DateTimeAccepted IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeAccepted)) END AS DateTimeAccepted,        
    CASE WHEN a.DateTimeClosed IS NULL THEN NULL ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeClosed)) END AS DateTimeClosed   
 ,MD.VehicleId,  
 (case when  a.StreetAddress not like 'N/A' and a.StreetAddress not like '%Address could not be Resolved!%'  then 1 else 0 end) as isMapIT  
  , cast(md.WarrantyEndDate as date) as WarrantyEndDate, '' as ControllerName,md.CustomerName,a.Rootcause,a.Correctiveaction
    FROM rvlfAlarm a                      
    INNER JOIN rvlfMAKDevices MD  ON a.BoxId=MD.BoxId
	INNER JOIN rvlfFleetVehicles fv ON MD.VehicleId = fv.VehicleId                                    
    INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId                           
    LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId                          
    LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId         
    INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId
	left join rvlfParamMst c on a.Description=c.ParamName                            	
	
	 left join rvlf_CompactorDetails comp on  a.BoxId=comp.DeviceId and comp.SeqNo=c.vehicletypeid 
	-- (d.CompType is null or d.CompType=comp.CompType) and
	left join rvlfAlarmsDesc d on c.ParamId=d.ParamID  and md.SubTypeId=d.EquipmentType and ( (d.VFantype is null or md.VFantype =0)  or (md.VFantype=1 and d.VFantype =1) or (md.VFantype>1 and d.VFantype>1 ))
	and (comp.CompType is null or comp.CompType=d.CompType)
	
	--left join rvlf_CompactorDetails comp on (d.CompType is null or  d.CompType=comp.CompType) and a.BoxId=comp.DeviceId
    WHERE (@bigFleetID IS NULL OR @bigFleetID='' OR Fv.FleetId=@bigFleetID)                   
    AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR a.BoxID in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                 
    AND (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
    AND MD.OrganizationId = @bigOrganizationID AND m.VisibleWeb = 1 
    --AND ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy)                   
    --AND ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy )                   
    AND ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel)       
    AND ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)                  
    AND ((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL))                   
    AND ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL))                   
    AND ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (a.ClosedBy IS NOT NULL))                       
    AND ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID )                   
    AND ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.Description like '%'+ @vcAlarmDesc  +'%') --and AlarmRepeatFlag=1            
	AND ((@bigCustomerId IS NULL OR @bigCustomerId='' or @bigCustomerId='0') OR MD.CustomerId = @bigCustomerId )
	--and ((@CheckUser is Null) or (MD.CustomerName = @lastname))	
	--and comp.Sno is not null
     ) AS A  ORDER BY DateTimeCreated,alarmid DESC                   
                   
    SELECT DISTINCT(ug.OperationTypeId) ,ug.UserGroupId from rvlfOperationType op               
 INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId               
 INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId              
 INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId              
 INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId              
 INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId              
 INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId               
 WHERE ga.UserId = @bigQueryingUser and ug.ModuleId = 4              
                        
  END                   
 --Get the alarms details for report                      
 ELSE                   
  BEGIN                  
    SELECT distinct BoxId,VehicleDescription, EquipmentType, DateTimeCreatedSort, AlarmDesc, StreetAddress, AcceptedUser, ClosedUser, 
	AlarmLevelName, ControllerName, EquipmentLocation, FleetName, Vin, 
	DateTimeCreated = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateTimeCreated),     
    CASE WHEN DateTimeAccepted IS NULL THEN NULL 
	ELSE  (CONVERT(VARCHAR,DateTimeAccepted,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeAccepted),22)) END AS DateTimeAccepted,                  
    CASE WHEN DateTimeClosed IS NULL THEN NULL 
	ELSE  (CONVERT(VARCHAR,DateTimeClosed,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,DateTimeClosed),22)) END AS DateTimeClosed,                  
    PasStartDate,PasEndDate,PasGenerateddate,StreetAddress,LicensePlate,AlarmLevelId,                   
    CASE	WHEN AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN  0                           
			WHEN AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
			WHEN a.ClosedBy IS Not NULL THEN 2                          
    END		AS AlarmStatusDesc,    
    CASE    WHEN AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN  0     
			WHEN AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
			WHEN a.ClosedBy IS Not NULL THEN 2                          
    END		AS AlarmStatus, WarrantyEndDate, Comments as Remarks,CustomerName,
	case when(@bigCustomerId is null or @bigCustomerId='' or @bigCustomerId='0') then 'ALL' else CustomerName end as Customerfilter,CorrectiveAction,Reason
   ,Reason as Rootcause
    FROM	(                  
		SELECT a.BoxId,MD.EquipmentName as VehicleDescription, VT.VehicleTypeName AS EquipmentType, '' as vin, 
		(Select top 1 rf.FleetName From rvlfFleet rf 
		Inner Join rvlfFleetVehicles rfv on rf.FleetId = rfv.FleetId 
		Where VehicleId = MD.VehicleId and rf.FleetName <> 'All') as FleetName, 
		'' as LicensePlate, a.AlarmLevelId,
		(case when @Lang='LanguageArNew' THEN isnull(s.AlarmLevelName_Ar,s.AlarmLevelName) Else s.AlarmLevelName end) as AlarmLevelName, a.AcceptedBy, a.ClosedBy, 
		Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,                  
		Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                  
		PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()),        
		CASE WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 0 WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1                          
			 WHEN a.ClosedBy IS Not NULL THEN 2 
		END  AS AlarmStatus, '' AS ControllerName, '' as EquipmentLocation, 
		DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreatedSort,a.DateTimeCreated,    
		CASE WHEN a.DateTimeAccepted IS NULL THEN NULL
			 ELSE dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,a.DateTimeAccepted) 
		END  AS DateTimeAccepted,
		CASE WHEN a.DateTimeClosed IS NULL THEN NULL
			 ELSE dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,a.DateTimeClosed)
		END  AS DateTimeClosed,		
		isnull(case when CHARINDEX('Ventilator',d.AlarmName,0)>0 then REPLACE(d.AlarmName,'label',comp.VentilatorModel ) else REPLACE(d.AlarmName,'label',comp.CompModel ) end
   ,a.[Description])   as AlarmDesc,
		--isnull(d.AlarmName,a.[Description])   as AlarmDesc,  
		REPLACE(ISNULL((Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_AR,a.StreetAddress)
						When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN ISNULL(a.StreetAddress_Hin,a.StreetAddress)
						ELSE a.StreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress,
		acc.DisplayName as AcceptedUser, clo.DisplayName as ClosedUser, a.Comments, cast(md.WarrantyEndDate as date) as WarrantyEndDate, CT.CustomerName,a.Correctiveaction as CorrectiveAction,a.Rootcause as Reason 
		FROM rvlfAlarm a
		INNER JOIN rvlfMAKDevices MD  ON a.BoxId=MD.BoxId
		INNER JOIN rvlfFleetVehicles fv ON MD.VehicleId = fv.VehicleId  
		INNER JOIN rvlfFleet F ON fv.FleetId = F.FleetId                   
		INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId          
		LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId         
		LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId        
		INNER JOIN rvlfVehicleType VT On MD.SubTypeId = VT.VehicleTypeId
		INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId         	    		
		left join rvlfParamMst c on a.Description=c.ParamName 
		--left join rvlfAlarmsDesc d on c.ParamId=d.ParamID and MD.SubTypeId=d.EquipmentType    
	--	 left join rvlfAlarmsDesc d on c.ParamId=d.ParamID  and md.SubTypeId=d.EquipmentType and ( d.VFantype is null or md.VFantype=0 or md.VFantype=d.VFantype or md.VFantype>=d.VFantype)
	--left join rvlf_CompactorDetails comp on (d.CompType is null or  d.CompType=comp.CompType) and a.BoxId=comp.DeviceId              	
	left join rvlf_CompactorDetails comp on  a.BoxId=comp.DeviceId and comp.SeqNo=c.vehicletypeid 
	-- (d.CompType is null or d.CompType=comp.CompType) and
	left join rvlfAlarmsDesc d on c.ParamId=d.ParamID  and md.SubTypeId=d.EquipmentType and ( (d.VFantype is null or md.VFantype =0)  or (md.VFantype=1 and d.VFantype =1) or (md.VFantype>1 and d.VFantype>1 ))
	and (comp.CompType is null or comp.CompType=d.CompType)
		left JOIN rvlfCustomers CT ON CT.CustomerId = MD.CustomerId
		WHERE (@bigFleetID IS NULL OR @bigFleetID='' OR Fv.FleetId=@bigFleetID)                   
		AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR a.BoxID in (SELECT * FROM rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                   
		AND (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR                         
		 a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
		AND MD.OrganizationId = @bigOrganizationID                      
		AND m.VisibleWeb = 1 AND s.AlarmLevelId IN (1,2,3)    
		--AND ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy)                   
		--AND ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy )                   
		AND ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel)                   
		AND ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)                  
		AND ((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL))           
		AND ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL))                   
		AND ((@bitIsClosed IS NULL OR @bitIsClosed='') OR (a.ClosedBy IS NOT NULL))  
		AND ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID )  
		--AND ((@isDashboard IS NULL OR @isDashboard='0') OR (a.AlarmType = m.BoxMsgInTypeId and isnull(a.IsClosed,0) <> 1))
		AND ((@vcAlarmDesc IS NULL OR @vcAlarmDesc='') OR a.DESCRIPTION like '%'+ @vcAlarmDesc  +'%') --and AlarmRepeatFlag=1
		AND ((@bigCustomerId IS NULL OR @bigCustomerId='' or @bigCustomerId='0') OR ct.CustomerId = @bigCustomerId )               
		--and ((@CheckUser is Null) or (MD.CustomerName = @lastname))
		--and comp.Sno is not null 
		--AND F.FleetName <> 'All'                               
     ) AS A  ORDER BY DateTimeCreated DESC 
    	 END                                          
END 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarms1]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetAlarms1]  
 @bigAlarmID bigint = null,  
 @bigFleetID bigint = null,  
 @intBoxID int = null,  
 @dtStartDate datetime = null,  
 @dtEndDate datetime = null,  
 @bigAcceptedBy bigint = null,  
 @bigClosedBy bigint = null,  
 @tiBoxMsgInType tinyint = null,  
 @bitIsNew bit = null,  
 @bitIsAccepted bit = null,  
 @bitIsClosed bit = null,  
 @bigOrganizationID bigint,  
 @bigQueryingUser bigint = 0,  
 @bitIsAlarmWindow bit = null,  
 @siSeverityLevel smallint = null,  
 @vcAlarmDesc varchar(50) = null  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetAlarms1 @bigFleetID =74, @bigOrganizationID=51, @dtStartDate ='2011/02/27 08:00:00 AM',@dtEndDate='2011/03/01 08:00:00 AM'  
-- Description : To get the alarm messages   
--    :   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 28-May-2009 MJJC Created Intial Version   
--              :   Updated by Kumuthini on 16-July-09 for displaying the datetime as per user prefreences  
--    : 25-Jan-2010 MJJC Updated the get alarm details function  
--              :   21-Feb-2010 MJJC Included defalut checking instead of name  
--    : 07-Apr-2010 KL  Included the title for the Severity image  
--              :   08-Apr-2010 KL      Made the Geozone Name smaller if long names  
--              :   11-May-2010 KL      Included padding for aligning the truck icon  
--    : 16-Jun-2010 MJJC Included the angler admin check in order to show or hide the device id row.  
--    : 29-Jun-2010 MJJC Made the Vehicle Display Name to be retrieved as Vehicle Description  
--    : 03-Aug-2010 SJ  Hanlded Previlege to show / hide Previlege for Acknowldge and Close Icon  
--    : 19-Aug-2010 LK      Changed the Vehicle Display Name to Vehicle Name   
--    : 27-jAN-2011 VN  Restricted the number of alarms for defense organization.  
--    : 04-Feb-2011 TSK  Modified to show Landmark Name instead of StreetAddress  
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
 DECLARE @intTopNos int=1000  
 --restrict the no of alarms.  
 IF(@bigOrganizationID=55)  
  BEGIN  
   SET @intTopNos=20   
  END  
   
 ------- Included by Kumuthini on 16-July-09 ---------------------  
   
 DECLARE @HoursToBeAdded INT = 0  
 DECLARE @MinsToBeAdded 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   
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz  
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser  
   
 DECLARE @isAnglerAdmin bit  
   
 select @isAnglerAdmin = CASE WHEN UserGroupName = 'Angler Admin' Then 1 Else 0 END from rvlfUserGroup   
  where UserGroupId in (select UserGroupId from rvlfUserGroupAssignment where UserId=@bigQueryingUser)  
    
 --Included by Jeyanthi on 03-Aug-2010 to show / hide acknowledge   
 Declare @isPrevileged bit  
   
 SELECT @isPrevileged = COUNT(*) FROM rvlfUserGroupSecurity s  
     INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId  
     WHERE ga.UserId = @bigQueryingUser and ModuleID=4 and OperationTypeId =15  
       
 --End  
  
 IF @bigFleetID IS NULL   
 BEGIN  
  -- TODO: include the organization check in future  
  SELECT @bigFleetID = th.fleetId from rvlfFleet th where th.isDefault = 1  
   AND OrganizationId = @bigOrganizationID  
 END  
 IF @bitIsAlarmWindow IS NULL  OR @bitIsAlarmWindow = 0  
 BEGIN  
 PRINT 'A'  
  SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))  
  SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))  
    
  SELECT TOP(@intTopNos)   
  a.AlarmId,   
  DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as DateTimeCreated,   
  a.BoxId, a.AcceptedBy, a.ClosedBy,   
  CASE WHEN a.DateTimeAccepted IS NULL THEN a.DateTimeAccepted ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeAccepted)) END AS DateTimeAccepted,   
  CASE WHEN a.DateTimeClosed IS NULL THEN a.DateTimeClosed ELSE DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeClosed)) END AS DateTimeClosed,   
  --dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType, null, a.DateTimeCreated) as AlarmDesc,  
  CASE WHEN a.AlarmType = 4 THEN 'Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *  
    @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' + CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END  
    WHEN a.AlarmType IN (5,6) THEN dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)  
    ELSE a.[Description] END  as AlarmDesc, a.AlarmLevelId,   
  ISNULL(a.StreetAddress,'Address not resolved') as StreetAddress,   
  --CASE WHEN (H.LandMarkID IS NULL OR H.LandMarkID = 0) THEN   
  --     Replace(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''') ELSE L.LandmarkName END AS StreetAddress,  
  a.Lat, a.Long,  m.BoxMsgInTypeDesc,  
  CASE   
   WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN  0   
   WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 1  
   WHEN /*a.AcceptedBy IS Not NULL AND */a.ClosedBy IS Not NULL THEN 2  
  END AS AlarmStatus,  
  CASE   
   WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 'Pending'   
   WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 'Acknowledged'  
   WHEN /*a.AcceptedBy IS Not NULL AND */a.ClosedBy IS Not NULL THEN 'Closed'  
  END AS AlarmStatusDesc,  
  acc.DisplayName + ' on ' + convert(varchar ,a.DateTimeAccepted,103) as ACKStatus,  
  clo.DisplayName+ ' on ' + convert(varchar ,a.DateTimeClosed,103) as ClosedStatus,  
  v.VehicleDescription,v.Vin, v.LicensePlate,   
  acc.DisplayName as AcceptedUser, clo.DisplayName as ClosedUser,  
  f.FleetName, g.OrganizationName ,  
  CASE WHEN a.AlarmType Not IN (5,6) THEN  
   CASE WHEN v.Notify=1 THEN 'Notify'   
    WHEN v.Warning=1 THEN 'Warning' WHEN v.Critical =1 THEN 'Critical'   
    ELSE 'No Notification is set' END   
   WHEN a.AlarmType IN (5,6) THEN  
    (SELECT CASE WHEN Notify=1 THEN 'Notify'   
    WHEN Warning=1 THEN 'Warning' WHEN Critical =1 THEN 'Critical'   
    ELSE 'No Notification is set' END FROM rvlfOrganizationGeozone WHERE   
    GeozoneNo = CAST(a.[Description] AS Bigint) )  
  END as NotificationType,  
  s.AlarmLevelName  
 FROM rvlfAlarm a INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId   
  INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId   
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId and f.FleetId = @bigFleetID  
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
  INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId   
  LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId  
  LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId  
  INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId    
  --INNER JOIN rvlfmsginhst H on h.OriginDateTime = A.DateTimeCreated and H.BoxId=a.BoxId and a.Lat=H.Latitude and a.Long=H.Longitude   
  --LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID  and H.BoxId = A.boxid   
  
 WHERE  
  --a.AlarmType =h.BoxMsgInTypeId and a.BoxId=h.BoxId and  
    
  (@intBoxID IS NULL or @intBoxID IS NULL OR a.BoxId = @intBoxID) AND  
  ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND  
  (@bigAcceptedBy IS NULL OR a.AcceptedBy = @bigAcceptedBy) AND  
  (@bigClosedBy IS NULL OR a.ClosedBy = @bigClosedBy ) AND  
  (@tiBoxMsgInType IS NULL OR a.AlarmType = @tiBoxMsgInType)AND  
  (@bitIsNew IS NULL OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) AND  
  (@bitIsAccepted IS NULL OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL)) AND  
  (@bitIsClosed IS NULL OR (/*a.AcceptedBy IS NOT NULL AND */a.ClosedBy IS NOT NULL)) AND  
  (@siSeverityLevel IS NULL OR a.AlarmLevelId = @siSeverityLevel) AND  
  (@bigAlarmID IS NULL OR a.AlarmId = @bigAlarmID ) AND  
  (@vcAlarmDesc IS NULL OR a.Description like '%'+ @vcAlarmDesc  +'%') AND  
  m.VisibleWeb = 1  
  --and H.BoxMsgInTypeId in (11,14,15,16,17,23,41,24,27)  
  AND v.OrganizationId = @bigOrganizationID  
  ORDER BY DateTimeCreated DESC  
    
 --Included for Graphical Report    
 SELECT TOP(@intTopNos)  v.VehicleDescription,Count(a.AlarmId) 'TotalAlerts'  
 FROM rvlfAlarm a INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId and f.FleetId = @bigFleetID  
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
  INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId   
  LEFT OUTER JOIN rvlfUser acc ON a.AcceptedBy = acc.UserId  
  LEFT OUTER JOIN rvlfUser clo ON a.ClosedBy = clo.UserId  
  INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId  
 WHERE  
  (@intBoxID IS NULL or @intBoxID IS NULL OR a.BoxId = @intBoxID) AND  
  ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND  
  (@bigAcceptedBy IS NULL OR a.AcceptedBy = @bigAcceptedBy) AND  
  (@bigClosedBy IS NULL OR a.ClosedBy = @bigClosedBy ) AND  
  (@tiBoxMsgInType IS NULL OR a.AlarmType = @tiBoxMsgInType)AND  
  (@bitIsNew IS NULL OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) AND  
  (@bitIsAccepted IS NULL OR (a.AcceptedBy IS NOT NULL AND a.ClosedBy IS NULL)) AND  
  (@bitIsClosed IS NULL OR (/*a.AcceptedBy IS NOT NULL AND */a.ClosedBy IS NOT NULL)) AND  
  (@siSeverityLevel IS NULL OR a.AlarmLevelId = @siSeverityLevel) AND  
  (@bigAlarmID IS NULL OR a.AlarmId = @bigAlarmID ) AND  
  (@vcAlarmDesc IS NULL OR a.Description like '%'+ @vcAlarmDesc  +'%') AND  
  m.VisibleWeb = 1  
  AND v.OrganizationId = @bigOrganizationID  
  GROUP by VehicleDescription   
  --End  
 END  
 ELSE   
 BEGIN  
    SELECT TOP(@intTopNos)  '<li id="'+ CAST(a.AlarmId as varchar(5)) +'"><div class=''' +   
    CASE WHEN a.DateTimeAccepted IS null THEN 'yellow-box' ELSE 'green-box' END  
    +'''><span class=''top''></span><p><span class=''yellow-truck'' style="padding-top:3px"><a href=''javascript:ShowAlarm("'+  
    CAST(a.AlarmId as varchar(5)) + '","' + v.VehicleDescription +'","'+ CAST( a.BoxId AS varchar(6))+'","'+  
    CASE WHEN a.AlarmType = 4 THEN 'Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *  
     @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +  
    CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END  
     WHEN a.AlarmType IN (5,6) THEN  
      dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)  
     ELSE a.[Description] END+'","'+  
    Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) , 101)  
    +' ' +Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) , 108)   
    +'","'+s.AlarmLevelName +'","'+  
    CASE   
     WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 'Pending'   
     WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 'Acknowledged'  
     WHEN a.ClosedBy IS Not NULL THEN 'Closed'  
    END  
    --commented on 03-Aug-2010 for restriction Acknowledge button  
    --+'",'+ CASE WHEN a.DateTimeAccepted IS NOT NULL THEN '1' ELSE '0' END +','+ cast(@isAnglerAdmin as char(1))+')''>'+v.DisplayName +'</a></span>&nbsp;<span class='''+ Lower(s.AlarmLevelName)  
    +'",'+ CASE WHEN a.DateTimeAccepted IS NOT NULL THEN '1' When @isPrevileged = 0 Then '1' Else '0' END +','+ cast(@isAnglerAdmin as char(1))+')''>'+v.VehicleDescription +'</a></span>&nbsp;<span class='''+ Lower(s.AlarmLevelName)  
    --End  
    +'-alert'' title='''+ s.AlarmLevelName +'''>&nbsp; </span><br /><span>'+Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)), 101)+' '   
    +Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) ,108)+'</span><br />'+   
    CASE WHEN a.AlarmType = 4 THEN '<span>Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *  
           @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +   
              CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END  
      WHEN a.AlarmType IN (5,6) THEN dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId)  
      ELSE '<span>' + a.[Description] END +'</span></p></div></li>'  
   FROM rvlfAlarm a  
    INNER JOIN rvlfVehicleAssignment va ON va.BoxId = a.BoxId  
    INNER JOIN  rvlfVehicle v ON v.VehicleId = va.VehicleId  
    INNER JOIN rvlfSeverity s ON s.AlarmLevelId = a.AlarmLevelId  
   WHERE  
    (@intBoxID IS NULL or @intBoxID IS NULL OR a.BoxId = @intBoxID) AND  
    ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
      a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND  
    (@bigAcceptedBy IS NULL OR a.AcceptedBy = @bigAcceptedBy) AND  
    (@bigClosedBy IS NULL OR a.ClosedBy = @bigClosedBy ) AND  
    (@tiBoxMsgInType IS NULL OR a.AlarmType = @tiBoxMsgInType)AND  
    ((@bitIsNew IS NULL OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) OR  
    (@bitIsAccepted IS NULL OR (a.ClosedBy IS NULL)) ) and   
    (@siSeverityLevel IS NULL OR a.AlarmLevelId = @siSeverityLevel) AND  
    (@bigAlarmID IS NULL OR a.AlarmId = @bigAlarmID ) AND  
    a.AlarmLevelId in (2,3)   
    AND v.OrganizationId = @bigOrganizationID  
    ORDER BY DateTimeCreated DESC  
 END  
   
 SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarmsForDrillDownCriticalChart]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--use Adorpowertron
CREATE PROCEDURE [dbo].[rvlf_sp_GetAlarmsForDrillDownCriticalChart]    

 @VehicleDesc varchar(max) = NULL,    
 @bigOrganizationID bigint = NULL,    
 @bigQueryingUser bigint = NULL,
 @dtStartDate datetime = Null,    
 @dtEndDate datetime = NULL,
 @bigFleetID bigint = null 
 
AS  
/********************************************************************************************************    
-- Name		   : rvlf_sp_GetAlarmsForDrillDownCriticalChart 'Precicon-III',86,322,'12/12/2016 12:00:00 AM','12/14/2016 12:00:00 AM',176
-- Description : To get the Critical Alerts details  for Drill down chart      
-- Author      : Ranjith N 
-- History     :       
--			   : 27-Apr-2013 Sakthi Get the alarms based on alarm message for mobile application
*********************************************************************************************************/ 
BEGIN    
 SET NOCOUNT ON 

--select b.BoxMsgInTypeName,COUNT(b.BoxMsgInTypeId) as NoofAlarms from rvlfBoxMsgSeverity a
--inner join rvlfBoxMsgInType b on a.BoxMsgInTypeId=b.BoxMsgInTypeId 
--inner join rvlfVehicleAssignment c on c.BoxId=a.BoxId
--inner join rvlfVehicle d on d.VehicleId=c.VehicleId 
-- and a.AlarmLevelID=3 and d.VehicleDescription = @VehicleDesc and d.OrganizationId=@bigOrganizationID   --a.BoxId=1
--group by  b.BoxMsgInTypeName 

	--select  (case when len(mt.BoxMsgInTypeName)> 15 then (SUBSTRING(mt.BoxMsgInTypeName,1,12) + '...') else mt.BoxMsgInTypeName end) as BoxMsgInTypeName, isnull(SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END),0) as NoofAlarms from rvlfAlarm a
	--	inner join rvlfVehicleAssignment v on v.BoxId=a.BoxId
	--	inner join rvlfVehicle vi on vi.VehicleId =v.VehicleId
	--	inner join rvlfBoxMsgSeverity ms on ms.BoxId = a.BoxId
	--	inner join rvlfBoxMsgInType mt on mt.BoxMsgInTypeId = ms.BoxMsgInTypeId
	--	INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId  
	--	where	   
	--	   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR vi.OrganizationId = @bigOrganizationID) AND 
 --          (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and  
	--		a.DateTimeCreated between @dtStartDate and @dtEndDate  and 
	--		a.AlarmLevelId =3 and 
	--		vi.VehicleDescription =@VehicleDesc 
	--		and ms.BoxMsgInTypeId = a.AlarmType 
	--		--vi.OrganizationId = @bigOrganizationID
	--	group by a.AlarmLevelId,mt.BoxMsgInTypeName
	declare @Lang varchar(50)         
	select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser   
	--IF (SELECT ISNULL(OrgId,0) FROM rvlfOrganizationServiceURL_App WHERE OrgId=@bigOrganizationID) <> 0 
 --   BEGIN
 --   	select  a.Description as BoxMsgInTypeName, 
	--	isnull(SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END),0) as NoofAlarms,a.Description as BoxMsgTypeName from 
	--	rvlfAlarm a	inner join rvlfVehicleAssignment v on v.BoxId=a.BoxId
	--	inner join rvlfVehicle vi on vi.VehicleId =v.VehicleId
	--	INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId  		
	--	inner join rvlfBoxMsgInType mt on a.AlarmType=mt.BoxMsgInTypeId 
	--	where	   
	--	   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR vi.OrganizationId = @bigOrganizationID) AND
 --           (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and
	--		a.DateTimeCreated between @dtStartDate and @dtEndDate  and 
	--		a.AlarmLevelId =3 and 
	--		(case when @Lang='LanguageArNew' then  isnull(vi.VehicleDescription,vi.VehicleDescription ) else vi.VehicleDescription  end) = @VehicleDesc			
	--		and a.AlarmType = mt.BoxMsgInTypeId --and a.Description like '%Alarm%'
	--		--vi.OrganizationId = @bigOrganizationID
	--	group by a.AlarmType, a.Description

 --   END
 --   ELSE
 --   BEGIN   
	--	--select  (case when len(mt.BoxMsgInTypeName)> 15 then (SUBSTRING(mt.BoxMsgInTypeName,1,12) + '...') else mt.BoxMsgInTypeName end) as BoxMsgInTypeName, 
	--isnull(SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END),0) as NoofAlarms from rvlfAlarm a
	--	select  
	--	--distinct(case when len(mt.BoxMsgInTypeName)> 15 then (SUBSTRING((case when @Lang='LanguageEn' then 
	--mt.BoxMsgInTypeName else isnull(mt.BoxMsgInTypeDesc_Ar,mt.BoxMsgInTypeName) end),1,12) + '...') else (case when @Lang='LanguageEn' then 
	--mt.BoxMsgInTypeName else isnull(mt.BoxMsgInTypeDesc_Ar,mt.BoxMsgInTypeName) end) end) as BoxMsgInTypeName,
	--	distinct (case when (a.AlarmType = 11) then (case when len(a.[Description])> 15 then SUBSTRING(a.[Description],1,12) + '...' 
	--else a.[Description] end) else (case when len(mt.BoxMsgInTypeName)> 15 then mt.BoxMsgInTypeName else mt.BoxMsgInTypeName end)end) as BoxMsgInTypeName,
	--	 isnull(SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END),0) as NoofAlarms from rvlfAlarm a      
	--	inner join rvlfVehicleAssignment v on v.BoxId=a.BoxId
	--	inner join rvlfVehicle vi on vi.VehicleId =v.VehicleId
	--	INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId  		
	--	inner join rvlfBoxMsgInType mt on a.AlarmType=mt.BoxMsgInTypeId 
		
	--	where	   
	--	   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR vi.OrganizationId = @bigOrganizationID) AND
 --           (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and
	--		a.DateTimeCreated between @dtStartDate and @dtEndDate  and 
	--		a.AlarmLevelId =3 and 
	--		vi.VehicleDescription =@VehicleDesc 
	--		and a.AlarmType = mt.BoxMsgInTypeId --and a.Description like '%Alarm%'
	--		--vi.OrganizationId = @bigOrganizationID
	--	group by a.AlarmType, mt.BoxMsgInTypeName,mt.BoxMsgInTypeDesc_Ar,(case when len(a.[Description])> 15 then SUBSTRING(a.[Description],1,12) + '...' else a.[Description] end)--a.[Description] 
	--END	


				
		--Select 'Site 1' as VehicleDescription,16 as NoofAlarmsCritical,8 as NoofAlarmsWarning1,4 as NoofAlarmsWarning2
		--union  all
		--Select 'Site 2' as VehicleDescription,7 as NoofAlarmsCritical,4 as NoofAlarmsWarning1,2 as NoofAlarmsWarning2
		--union  all
		--Select 'Site 3' as VehicleDescription,6 as NoofAlarmsCritical,3 as NoofAlarmsWarning1,2 as NoofAlarmsWarning2
		--union  all
		--Select 'Site 4' as VehicleDescription,2 as NoofAlarmsCritical,1 as NoofAlarmsWarning1,1 as NoofAlarmsWarning2
		--	union  all
		--Select 'Site 5' as VehicleDescription,1 as NoofAlarmsCritical,5 as NoofAlarmsWarning1,6 as NoofAlarmsWarning2
		--union  all

		--Select 'ADR_HVR_III_6' as VehicleDescription,60 as NoofAlarms
		--union  all
		--Select 'ADR_HVR_III_7' as VehicleDescription,70 as NoofAlarms
		--	union  all
		--Select 'ADR_HVR_III_8' as VehicleDescription,80 as NoofAlarms
		--union  all
		--Select 'ADR_HVR_III_9' as VehicleDescription,90 as NoofAlarms
		--union  all
		--Select 'ADR_HVR_III_10' as VehicleDescription,100 as NoofAlarms
		--union  all
		--Select 'ADR_HVR_III_11' as VehicleDescription,110 as NoofAlarms
		--union  all
		--Select 'ADR_HVR_III_12' as VehicleDescription,120 as NoofAlarms
		--union  all
		--Select 'ADR_HVR_III_13' as VehicleDescription,130 as NoofAlarms
		--	union  all
		--Select 'ADR_HVR_III_14' as VehicleDescription,140 as NoofAlarms
		--union  all
		--Select 'ADR_HVR_III_15' as VehicleDescription,150 as NoofAlarms
	

	select  top 15
		--distinct(case when len(mt.BoxMsgInTypeName)> 15 then (SUBSTRING((case when @Lang='LanguageEn' then mt.BoxMsgInTypeName else 
		--isnull(mt.BoxMsgInTypeDesc_Ar,mt.BoxMsgInTypeName) end),1,12) + '...') else (case when @Lang='LanguageEn' then mt.BoxMsgInTypeName else isnull(mt.BoxMsgInTypeDesc_Ar,mt.BoxMsgInTypeName) end) end) as BoxMsgInTypeName,
		Vi.VehicleDescription
         ,isnull(SUM(CASE WHEN AlarmLevelId = 3 THEN 1 ELSE 0 END),0) as NoofAlarmsCritical
		 ,isnull(SUM(CASE WHEN AlarmLevelId = 1 THEN 1 ELSE 0 END),0) as NoofAlarmsWarning1
		 ,isnull(SUM(CASE WHEN AlarmLevelId = 2 THEN 1 ELSE 0 END),0) as NoofAlarmsWarning2 from rvlfAlarm a      
		inner join rvlfVehicleAssignment v on v.BoxId=a.BoxId
		inner join rvlfVehicle vi on vi.VehicleId =v.VehicleId
		INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId  		
		inner join rvlfBoxMsgInType mt on a.AlarmType=mt.BoxMsgInTypeId 
		inner join rvlfVehicleType vt on vt.VehicleTypeId =vi.VehicleTypeId
		where	   
			(vi.OrganizationId = @bigOrganizationID) AND
            (fv.FleetId = @bigFleetID) and
			CONVERT(date,a.DateTimeCreated)  between CONVERT(date,@dtStartDate) and CONVERT(date,@dtEndDate)  and
			a.AlarmLevelId in(2,1,3) and 
			VT.vehicletypename =@VehicleDesc 
			and a.AlarmType = mt.BoxMsgInTypeId
		group by Vi.VehicleDescription order by NoofAlarmsCritical desc  --a.AlarmType, mt.BoxMsgInTypeName,mt.BoxMsgInTypeDesc_Ar 


 SET NOCOUNT OFF    
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarmsForDrillDownCriticalChart_FleetBased]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetAlarmsForDrillDownCriticalChart_FleetBased]    

 @VehicleDesc varchar(max) = NULL,    
 @bigOrganizationID bigint = NULL,    
 @bigQueryingUser bigint = NULL,
 @dtStartDate datetime = Null,    
 @dtEndDate datetime = NULL,
 @bigFleetID bigint = null 
 
AS  
/********************************************************************************************************    
-- Name		   : rvlf_sp_GetAlarmsForDrillDownCriticalChart_FleetBased
-- Description : To get the Critical Alerts details  for Drill down chart      
-- Author      : Kapil 
-- History     :       
--			   : 27-Apr-2013 Sakthi Get the alarms based on alarm message for mobile application
*********************************************************************************************************/ 
BEGIN    
 SET NOCOUNT ON 

--select b.BoxMsgInTypeName,COUNT(b.BoxMsgInTypeId) as NoofAlarms from rvlfBoxMsgSeverity a
--inner join rvlfBoxMsgInType b on a.BoxMsgInTypeId=b.BoxMsgInTypeId 
--inner join rvlfVehicleAssignment c on c.BoxId=a.BoxId
--inner join rvlfVehicle d on d.VehicleId=c.VehicleId 
-- and a.AlarmLevelID=3 and d.VehicleDescription = @VehicleDesc and d.OrganizationId=@bigOrganizationID   --a.BoxId=1
--group by  b.BoxMsgInTypeName 

	--select  (case when len(mt.BoxMsgInTypeName)> 15 then (SUBSTRING(mt.BoxMsgInTypeName,1,12) + '...') else mt.BoxMsgInTypeName end) as BoxMsgInTypeName, isnull(SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END),0) as NoofAlarms from rvlfAlarm a
	--	inner join rvlfVehicleAssignment v on v.BoxId=a.BoxId
	--	inner join rvlfVehicle vi on vi.VehicleId =v.VehicleId
	--	inner join rvlfBoxMsgSeverity ms on ms.BoxId = a.BoxId
	--	inner join rvlfBoxMsgInType mt on mt.BoxMsgInTypeId = ms.BoxMsgInTypeId
	--	INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId  
	--	where	   
	--	   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR vi.OrganizationId = @bigOrganizationID) AND 
 --          (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and  
	--		a.DateTimeCreated between @dtStartDate and @dtEndDate  and 
	--		a.AlarmLevelId =3 and 
	--		vi.VehicleDescription =@VehicleDesc 
	--		and ms.BoxMsgInTypeId = a.AlarmType 
	--		--vi.OrganizationId = @bigOrganizationID
	--	group by a.AlarmLevelId,mt.BoxMsgInTypeName
	declare @Lang varchar(50)         
	select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser   
	IF (SELECT ISNULL(OrgId,0) FROM rvlfOrganizationServiceURL_App WHERE OrgId=@bigOrganizationID) <> 0 
    BEGIN
    	select  a.Description as BoxMsgInTypeName, 
		isnull(SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END),0) as NoofAlarms,a.Description as BoxMsgTypeName from 
		rvlfAlarm a	inner join rvlfVehicleAssignment v on v.BoxId=a.BoxId
		inner join rvlfVehicle vi on vi.VehicleId =v.VehicleId
		INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId  		
		inner join rvlfBoxMsgInType mt on a.AlarmType=mt.BoxMsgInTypeId 
		where	   
		   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR vi.OrganizationId = @bigOrganizationID) AND
            (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and
			a.DateTimeCreated between @dtStartDate and @dtEndDate  and 
			a.AlarmLevelId =3 and 
			(case when @Lang='LanguageArNew' then  isnull(vi.VehicleDescription,vi.VehicleDescription ) else vi.VehicleDescription  end) = @VehicleDesc			
			and a.AlarmType = mt.BoxMsgInTypeId --and a.Description like '%Alarm%'
			--vi.OrganizationId = @bigOrganizationID
		group by a.AlarmType, a.Description

    END
    ELSE
    BEGIN   
    
    
		 select 
		--distinct(case when len(mt.BoxMsgInTypeName)> 15 then (SUBSTRING((case when @Lang='LanguageEn' then mt.BoxMsgInTypeName else isnull(mt.BoxMsgInTypeDesc_Ar,mt.BoxMsgInTypeName) end),1,12) + '...') else (case when @Lang='LanguageEn' then mt.BoxMsgInTypeName else isnull(mt.BoxMsgInTypeDesc_Ar,mt.BoxMsgInTypeName) end) end) as BoxMsgInTypeName,
		distinct (case when (a.AlarmType = 11) then (case when len(a.[Description])> 15 then SUBSTRING(a.[Description],1,12) + '...' else a.[Description] end) else (case when len(mt.BoxMsgInTypeName)> 15 then mt.BoxMsgInTypeName else mt.BoxMsgInTypeName end)end) as BoxMsgInTypeName,
		isnull(SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END),0) as NoofAlarms,F.FleetName from rvlfAlarm a      
		INNER JOIN rvlfVehicleAssignment v on v.BoxId=a.BoxId
		INNER JOIN rvlfVehicle vi on vi.VehicleId =v.VehicleId
		INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId  		
		INNER JOIN rvlfBoxMsgInType mt on a.AlarmType=mt.BoxMsgInTypeId
		INNER JOIN rvlfFleet F on fv.FleetId = F.FleetId		
		where
		(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR vi.OrganizationId = @bigOrganizationID) 
   --    AND    (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and
		AND a.DateTimeCreated between @dtStartDate and @dtEndDate   
		and a.AlarmLevelId =3
		and F.FleetName = @VehicleDesc 
		and a.AlarmType = mt.BoxMsgInTypeId --and a.Description like '%Alarm%'
		--	--vi.OrganizationId = @bigOrganizationID
		group by a.AlarmType, mt.BoxMsgInTypeName,mt.BoxMsgInTypeDesc_Ar,F.FleetName,
		(case when len(a.[Description])> 15 then SUBSTRING(a.[Description],1,12) + '...' else a.[Description] end)--a.[Description]
    
    
    
		--select  (case when len(mt.BoxMsgInTypeName)> 15 then (SUBSTRING(mt.BoxMsgInTypeName,1,12) + '...') else mt.BoxMsgInTypeName end) as BoxMsgInTypeName, isnull(SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END),0) as NoofAlarms from rvlfAlarm a
		select  
		--distinct(case when len(mt.BoxMsgInTypeName)> 15 then (SUBSTRING((case when @Lang='LanguageEn' then mt.BoxMsgInTypeName else isnull(mt.BoxMsgInTypeDesc_Ar,mt.BoxMsgInTypeName) end),1,12) + '...') else (case when @Lang='LanguageEn' then mt.BoxMsgInTypeName else isnull(mt.BoxMsgInTypeDesc_Ar,mt.BoxMsgInTypeName) end) end) as BoxMsgInTypeName,
		distinct (case when (a.AlarmType = 11) then (case when len(a.[Description])> 15 then SUBSTRING(a.[Description],1,12) + '...' else a.[Description] end) else (case when len(mt.BoxMsgInTypeName)> 15 then mt.BoxMsgInTypeName else mt.BoxMsgInTypeName end)end) as BoxMsgInTypeName,
		 isnull(SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END),0) as NoofAlarms from rvlfAlarm a      
		inner join rvlfVehicleAssignment v on v.BoxId=a.BoxId
		inner join rvlfVehicle vi on vi.VehicleId =v.VehicleId
		INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId  		
		inner join rvlfBoxMsgInType mt on a.AlarmType=mt.BoxMsgInTypeId 
		
		where	   
		   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR vi.OrganizationId = @bigOrganizationID) AND
            (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and
			a.DateTimeCreated between @dtStartDate and @dtEndDate  and 
			a.AlarmLevelId =3 and 
			vi.VehicleDescription =@VehicleDesc 
			and a.AlarmType = mt.BoxMsgInTypeId --and a.Description like '%Alarm%'
			--vi.OrganizationId = @bigOrganizationID
		group by a.AlarmType, mt.BoxMsgInTypeName,mt.BoxMsgInTypeDesc_Ar,(case when len(a.[Description])> 15 then SUBSTRING(a.[Description],1,12) + '...' else a.[Description] end)--a.[Description] 
		
		
		
		
	END	
 SET NOCOUNT OFF    
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarmsForMonitor]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAlarmsForMonitor]          
 @bigAlarmID bigint = null,          
 @bigFleetID bigint = null,          
 @intBoxID int = null,          
 @dtStartDate datetime = null,          
 @dtEndDate datetime = null,          
 @bigAcceptedBy bigint = null,          
 @bigClosedBy bigint = null,          
 @tiBoxMsgInType tinyint = null,          
 @bitIsNew bit = null,          
 @bitIsAccepted bit = null,          
 @bitIsClosed bit = null,          
 @bigOrganizationID bigint,          
 @bigQueryingUser bigint = 0,          
 @bitIsAlarmWindow bit = null,          
 @siSeverityLevel smallint = null,          
 @vcAlarmDesc varchar(50) = null          
AS        
  
/***********************************************************************************************************************************************************************/          
-- Name   : RVLF_SP_GetAlarmsForMonitor @bigQueryingUser=N'458',@bigOrganizationID=N'86',@bigFleetID=N'257',@dtStartDate=N'8/10/2018 6:26:57 AM',@dtEndDate=N'8/13/2018 6:26:57 AM',@bitIsNew=N'True',@bitIsAccepted=N'True',@bitIsAlarmWindow=N'True'
-- Description  : To get the alarm messages for monitor    
-- Author  : Sakthi        
-- Created Date : 25-Nov-2011    
--    : Sakthi - Alarms load based on fleet id      
/******************************************************************************************************************************************************/          
BEGIN            
 SET NOCOUNT off             
     
 Declare @dtFDate datetime =@dtStartDate    
 Declare @dtEDate datetime =@dtEndDate            
     
 ------- Included by Kumuthini on 16-July-09 ---------------------            
             
 DECLARE @HoursToBeAdded INT = 0            
 DECLARE @MinsToBeAdded INT = 0            
 DECLARE @DefaultDateFormat INT = 0;              
 DECLARE @ConversionFactor numeric (10,2) = 1.0    
 DECLARE @Privelege INT =0                
 DECLARE @Lang varchar(50)               
    
    
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,            
 @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')        
 FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz            
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser             
             
 DECLARE @isAnglerAdmin bit            
             
 SELECT @isAnglerAdmin = CASE WHEN UserGroupName = 'Angler Admin' THEN 1 ELSE 0 END FROM rvlfUserGroup             
 WHERE UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId=@bigQueryingUser)            
              
 --Included by Jeyanthi on 03-Aug-2010 to show / hide acknowledge             
 Declare @isPrevileged bit            
             
 SELECT @isPrevileged = COUNT(*) FROM rvlfUserGroupSecurity s            
 INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId            
 WHERE ga.UserId = @bigQueryingUser and ModuleID=4 and OperationTypeId =15            
-- included for Ack/close based on priviledge
 DECLARE @tblAcknowledgeOperation TABLE (UserId int,OperationId int)    
 INSERT INTO @tblAcknowledgeOperation(UserId,OperationId)    
 SELECT ga.UserId,s.OperationTypeId FROM rvlfUserGroupSecurity s                              
 INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId                              
 WHERE ga.UserId = @bigQueryingUser and ModuleID=4 and OperationTypeId IN (369,370)    
     
 Declare @isPrevilegedOpr SMALLINT    
 SELECT @isPrevilegedOpr = (CASE WHEN (SELECT COUNT(OperationId) FROM @tblAcknowledgeOperation) = 2 THEN 1     
 WHEN (SELECT 1 FROM @tblAcknowledgeOperation WHERE OperationId=369)=1 THEN 2     
 WHEN (SELECT 1 FROM @tblAcknowledgeOperation WHERE OperationId=370)=1 THEN 3 ELSE 0 END)  
--
 SELECT  @Privelege =  count(ug.UserGroupId) FROM rvlfOperationType op     
 INNER JOIN rvlfUserGroupSecurity  ug ON ug.OperationTypeId = op.OperationTypeId     
 INNER JOIN rvlfUserGroup u ON u.UserGroupId = ug.UserGroupId    
 INNER JOIN rvlfModule m ON M.ModuleID = ug.ModuleId    
 INNER JOIN rvlfUser ur ON ur.OrganizationId = u.OrganizationId    
 INNER JOIN rvlfUserGroupAssignment ga ON ga.UserGroupId = ug.UserGroupId  
 WHERE ga.UserId = @bigQueryingUser and ug.ModuleId = 28                   
 --End            
            
 IF @bigFleetID IS NULL             
 BEGIN            
  -- TODO: include the organization check in future            
  --SELECT @bigFleetID = th.fleetId from rvlfFleet th where th.isDefault = 1            
  -- AND OrganizationId = @bigOrganizationID            
 SELECT @bigFleetID = f.fleetId from rvlfFleet f INNER JOIN rvlfUserPreferences up ON up.DefaultFleetId=FleetId     
 WHERE up.UserId=@bigQueryingUser AND f.OrganizationId = @bigOrganizationID     
 END            
 IF @bitIsAlarmWindow = 1    
 BEGIN            
  DECLARE @cAlarmHtml nvarchar(max)    
 DECLARE @nCount int    
 SET @cAlarmHtml = ''    
 SET @nCount = 0    
     
     IF(@Privelege > 0)  
   BEGIN  
   print @Privelege  
    SELECT @cAlarmHtml=COALESCE(@cAlarmHtml,'')+Java,@nCount=COALESCE(@nCount,'')+1  FROM (select top 25 ('<li id="'+ CAST(a.AlarmId as varchar(15)) +'"><div class=''' +             
    CASE WHEN a.DateTimeAccepted IS null THEN 'yellow-box' ELSE 'green-box' END            
    +'''><span class=''top-'+ Lower(s.AlarmLevelName) + '''></span><p>
	<span class='''+ Lower(s.AlarmLevelName)                
    +'-alert'' title='''+ s.AlarmLevelName +'''>&nbsp; </span>
	<span class=''yellow-truck'' style="padding-top:3px">'	
	+MD.EquipmentName +'-'+cM.ControllerName+'
	</span>&nbsp;<br /><span>'+            
   dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)    
   +'</span><br />'+             
     (case when a.CustomProp is null then a.[Description] else dbo.rvlf_fn_GetAlarmDetails_New(a.customProp,a.AlarmType,a.BoxId, null, a.DateTimeCreated,@Lang) END)+'</span></p></div></li>' ) as Java   
   
    FROM rvlfAlarm a            
    inner join rvlfMAKDevices MD on a.boxid=md.boxid   
    INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId =MD.VehicleId    
    INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId    
    INNER JOIN rvlfSeverity s ON s.AlarmLevelId = a.AlarmLevelId
	INNER JOIN adrControllerMaster CM  ON CM.EquipmentId = a.BoxId 
	--and CM.ControllerPositionId = a.ControllerID --- and (MD.SubTypeId=1 or CM.DCSIMId = a.DCSIM)       
    WHERE     
    ((@bigFleetID IS NULL OR @bigFleetID='') OR f.FleetId = @bigFleetID) AND           
    ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND            
    (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR            
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND            
    ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND            
    ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND            
    ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND            
    (((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) OR            
    ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.ClosedBy IS NULL)) ) and 
    ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND            
    ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND            
    a.AlarmLevelId in (2,3)   --and AlarmRepeatFlag=1           
    AND MD.OrganizationId = @bigOrganizationID            
    ORDER BY DateTimeCreated DESC) as tbl       
   END      
  ELSE    
   BEGIN    
    SELECT @cAlarmHtml=COALESCE(@cAlarmHtml,'')+Java,@nCount=COALESCE(@nCount,'')+1  FROM (select top 25 ('<li id="'+ CAST(a.AlarmId as varchar(15)) +'"><div class=''' +             
    CASE WHEN a.DateTimeAccepted IS null THEN 'yellow-box' ELSE 'green-box' END            
    +'''><span class=''top-'+ Lower(s.AlarmLevelName) + '''></span><p><span class='''+ Lower(s.AlarmLevelName)            
              
    +'-alert'' title='''+ s.AlarmLevelName +'''>&nbsp; </span><span class=''yellow-truck'' style="padding-top:3px">'	
	+MD.EquipmentName +'-'+cM.ControllerName+'</span>&nbsp;	
	<br /><span>'+            
   dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)    
   +'</span><br />'+             
    (case when a.CustomProp is null then a.[Description] else dbo.rvlf_fn_GetAlarmDetails_New(a.customProp,a.AlarmType,a.BoxId, null, a.DateTimeCreated,@Lang) END) +'</span></p></div></li>' ) as Java   
        
    FROM rvlfAlarm a            
  inner join rvlfMAKDevices MD on a.BoxId=md.BoxId    
    INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = MD.VehicleId    
    INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId    
    INNER JOIN rvlfSeverity s ON s.AlarmLevelId = a.AlarmLevelId    
	INNER JOIN adrControllerMaster CM  ON CM.EquipmentId = a.BoxId and CM.ControllerPositionId = a.ControllerID  and (MD.SubTypeId=1 or CM.DCSIMId = a.DCSIM)    
    WHERE     
    ((@bigFleetID IS NULL OR @bigFleetID='') OR f.FleetId = @bigFleetID) AND           
    ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND            
    (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR            
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND            
    ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND            
    ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND            
    ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND            
    (((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) OR            
    ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.ClosedBy IS NULL)) ) and             
    ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND            
    ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND            
    a.AlarmLevelId in (2,3)       --and AlarmRepeatFlag=1      
    AND MD.OrganizationId = @bigOrganizationID            
    ORDER BY DateTimeCreated DESC) as tbl           
    END  
    SELECT @cAlarmHtml as AlarmTemplate,@nCount as AlarmCount  
 END          
  --SET NOCOUNT OFF            
END    
  
  
  
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarmsForMonitor_1]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAlarmsForMonitor_1]        
 @bigAlarmID bigint = null,        
 @bigFleetID bigint = null,        
 @intBoxID int = null,        
 @dtStartDate datetime = null,        
 @dtEndDate datetime = null,        
 @bigAcceptedBy bigint = null,        
 @bigClosedBy bigint = null,        
 @tiBoxMsgInType tinyint = null,        
 @bitIsNew bit = null,        
 @bitIsAccepted bit = null,        
 @bitIsClosed bit = null,        
 @bigOrganizationID bigint,        
 @bigQueryingUser bigint = 0,        
 @bitIsAlarmWindow bit = null,        
 @siSeverityLevel smallint = null,        
 @vcAlarmDesc varchar(50) = null        
AS        
/***********************************************************************************************************************************************************************/        
-- Name   : rvlf_sp_GetAlarmsForMonitor_1 @bigFleetID  = 61, @bigOrganizationID=40, @dtStartDate = '05/24/2012',@dtEndDate='05/25/2012' ,@bitIsAlarmWindow=1,@bigQueryingUser=125       
-- Description  : To get the alarm messages for monitor  
-- Author  : Sakthi      
-- Created Date : 25-Nov-2011  
--    : Sakthi - Alarms load based on fleet id    
/******************************************************************************************************************************************************/        
BEGIN          
 SET NOCOUNT ON           
   
 Declare @dtFDate datetime =@dtStartDate  
 Declare @dtEDate datetime =@dtEndDate          
   
 ------- Included by Kumuthini on 16-July-09 ---------------------          
           
 DECLARE @HoursToBeAdded INT = 0          
 DECLARE @MinsToBeAdded INT = 0          
 DECLARE @DefaultDateFormat INT = 0;            
 DECLARE @ConversionFactor numeric (10,2) = 1.0  
 DECLARE @Privelege INT =0              
          
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,          
 @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)         
 FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz          
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser           
           
 DECLARE @isAnglerAdmin bit          
           
 SELECT @isAnglerAdmin = CASE WHEN UserGroupName = 'Angler Admin' THEN 1 ELSE 0 END FROM rvlfUserGroup           
 WHERE UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId=@bigQueryingUser)          
            
 --Included by Jeyanthi on 03-Aug-2010 to show / hide acknowledge           
 Declare @isPrevileged bit          
           
 SELECT @isPrevileged = COUNT(*) FROM rvlfUserGroupSecurity s          
 INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId          
 WHERE ga.UserId = @bigQueryingUser and ModuleID=4 and OperationTypeId =15          
 
 SELECT  @Privelege =  count(ug.UserGroupId) FROM rvlfOperationType op   
 INNER JOIN rvlfUserGroupSecurity  ug ON ug.OperationTypeId = op.OperationTypeId   
 INNER JOIN rvlfUserGroup u ON u.UserGroupId = ug.UserGroupId  
 INNER JOIN rvlfModule m ON M.ModuleID = ug.ModuleId  
 INNER JOIN rvlfUser ur ON ur.OrganizationId = u.OrganizationId  
 INNER JOIN rvlfUserGroupAssignment ga ON ga.UserGroupId = ug.UserGroupId
 WHERE ga.UserId = @bigQueryingUser and ug.ModuleId = 28                
 PRINT @Privelege
 --End          
          
 IF @bigFleetID IS NULL           
 BEGIN          
  -- TODO: include the organization check in future          
  --SELECT @bigFleetID = th.fleetId from rvlfFleet th where th.isDefault = 1          
  -- AND OrganizationId = @bigOrganizationID          
 SELECT @bigFleetID = f.fleetId from rvlfFleet f INNER JOIN rvlfUserPreferences up ON up.DefaultFleetId=FleetId   
 WHERE up.UserId=@bigQueryingUser AND f.OrganizationId = @bigOrganizationID   
 END          
 IF @bitIsAlarmWindow = 1  
 BEGIN          
  DECLARE @cAlarmHtml nvarchar(max)  
 DECLARE @nCount int  
 SET @cAlarmHtml = ''  
 SET @nCount = 0  
   
     IF(@Privelege > 0)
   BEGIN
    SELECT @cAlarmHtml=COALESCE(@cAlarmHtml,'')+Java,@nCount=COALESCE(@nCount,'')+1  FROM (select top 25 ('<li id="'+ CAST(a.AlarmId as varchar(15)) +'"><div class=''' +           
    CASE WHEN a.DateTimeAccepted IS null THEN 'yellow-box' ELSE 'green-box' END          
    +'''><span class=''top''></span><p><span class=''yellow-truck'' style="padding-top:3px"><a href=''javascript:ShowAlarm("'+          
    CAST(a.AlarmId as varchar(15)) + '","' + v.VehicleDescription +'","'+CASE WHEN @Privelege = 0 THEN '-' ELSE  ISNULL(dm.DisplayName,dm.DriverName)  END+'","'+case WHEN @Privelege = 0 THEN '-' ELSE ISNULL(dm.MobileNo,dm.PhoneNo) END+'","'+ CAST( a.BoxId AS varchar(6))+'","'+CASE WHEN a.AlarmType = 4 THEN 'Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *          
    @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +          
    CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END          
    WHEN a.AlarmType IN (5,6) THEN          
    dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)          
    ELSE a.[Description] END+'","'+          
    dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)  
   -- Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) , @DefaultDateFormat)          
   -- +' ' + Convert(varchar, cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated))as Time) , 22)    
    +'","'+s.AlarmLevelName +'","'+          
    CASE           
    WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 'Pending'           
    WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 'Acknowledged'          
    WHEN a.ClosedBy IS Not NULL THEN 'Closed'          
    END          
    --commented on 03-Aug-2010 for restriction Acknowledge button          
    --+'",'+ CASE WHEN a.DateTimeAccepted IS NOT NULL THEN '1' ELSE '0' END +','+ cast(@isAnglerAdmin as char(1))+')''>'+v.DisplayName +'</a></span>&nbsp;<span class='''+ Lower(s.AlarmLevelName)          
    +'",'+ CASE WHEN a.DateTimeAccepted IS NOT NULL THEN '1' When @isPrevileged = 0 Then '1' Else '0' END +','+ cast(@isAnglerAdmin as char(1))+')''>'+v.VehicleDescription +'</a></span>&nbsp;<span class='''+ Lower(s.AlarmLevelName)          
    --End          
    +'-alert'' title='''+ s.AlarmLevelName +'''>&nbsp; </span><br /><span>'+       
   -- Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)), @DefaultDateFormat)+' '           
   --+ Convert(varchar, cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as Time),22)   
   dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)  
   +'</span><br />'+           
    CASE WHEN a.AlarmType = 4 THEN '<span>Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *          
    @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +           
    CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END          
    WHEN a.AlarmType IN (5,6) THEN CASE WHEN LEN(SUBSTRING(dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),CHARINDEX('>',dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),0)+1,150))>30 THEN SUBSTRING (  
 dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),0,30)+'...'+''''            
    ELSE dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId) END            
    ELSE '<span>' + CASE WHEN LEN(a.[Description])>30 THEN SUBSTRING(a.[Description],0,30)+'...'+''''  ELSE a.[Description] END END +'</span></p></div></li>' ) as Java  
    FROM rvlfAlarm a          
    INNER JOIN rvlfVehicleAssignment va ON va.BoxId = a.BoxId          
    INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId    
    INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId  
    INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId  
    INNER JOIN rvlfSeverity s ON s.AlarmLevelId = a.AlarmLevelId 
	INNER JOIN rvlfDriverAssignment da on da.BoxId =  va.BoxId 
    INNER JOIN rvlfDriverMaster dm on  dm.DriverId  =  da.DriverId     
    WHERE   
    ((@bigFleetID IS NULL OR @bigFleetID='') OR f.FleetId = @bigFleetID) AND         
    ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND          
    (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR          
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND          
    ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND          
    ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND          
    ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND          
    (((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) OR          
    ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.ClosedBy IS NULL)) ) and           
    ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND          
    ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND          
    a.AlarmLevelId in (2,3)           
    AND v.OrganizationId = @bigOrganizationID          
    ORDER BY DateTimeCreated DESC) as tbl     
   END    
  ELSE  
   BEGIN  
    SELECT @cAlarmHtml=COALESCE(@cAlarmHtml,'')+Java,@nCount=COALESCE(@nCount,'')+1  FROM (select top 25 ('<li id="'+ CAST(a.AlarmId as varchar(15)) +'"><div class=''' +           
    CASE WHEN a.DateTimeAccepted IS null THEN 'yellow-box' ELSE 'green-box' END          
    +'''><span class=''top''></span><p><span class=''yellow-truck'' style="padding-top:3px"><a href=''javascript:ShowAlarm("'+          
    CAST(a.AlarmId as varchar(15)) + '","' + v.VehicleDescription +'","'+CASE WHEN @Privelege = 0 THEN '-'   END+'","'+case WHEN @Privelege = 0 THEN '-'  END+'","'+ CAST( a.BoxId AS varchar(6))+'","'+CASE WHEN a.AlarmType = 4 THEN 'Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *          
    @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +          
    CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END          
    WHEN a.AlarmType IN (5,6) THEN          
    dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)          
    ELSE a.[Description] END+'","'+          
    dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)  
   -- Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) , @DefaultDateFormat)          
   -- +' ' + Convert(varchar, cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated))as Time) , 22)    
    +'","'+s.AlarmLevelName +'","'+          
    CASE           
    WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN 'Pending'           
    WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN 'Acknowledged'          
    WHEN a.ClosedBy IS Not NULL THEN 'Closed'          
    END          
    --commented on 03-Aug-2010 for restriction Acknowledge button          
    --+'",'+ CASE WHEN a.DateTimeAccepted IS NOT NULL THEN '1' ELSE '0' END +','+ cast(@isAnglerAdmin as char(1))+')''>'+v.DisplayName +'</a></span>&nbsp;<span class='''+ Lower(s.AlarmLevelName)          
    +'",'+ CASE WHEN a.DateTimeAccepted IS NOT NULL THEN '1' When @isPrevileged = 0 Then '1' Else '0' END +','+ cast(@isAnglerAdmin as char(1))+')''>'+v.VehicleDescription +'</a></span>&nbsp;<span class='''+ Lower(s.AlarmLevelName)          
    --End          
    +'-alert'' title='''+ s.AlarmLevelName +'''>&nbsp; </span><br /><span>'+       
   -- Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)), @DefaultDateFormat)+' '           
   --+ Convert(varchar, cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as Time),22)   
   dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)  
   +'</span><br />'+           
    CASE WHEN a.AlarmType = 4 THEN '<span>Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *          
    @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +           
    CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END          
    WHEN a.AlarmType IN (5,6) THEN CASE WHEN LEN(SUBSTRING(dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),CHARINDEX('>',dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),0)+1,150))>30 THEN SUBSTRING (  
 dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),0,30)+'...'+''''            
    ELSE dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId) END            
    ELSE '<span>' + CASE WHEN LEN(a.[Description])>30 THEN SUBSTRING(a.[Description],0,30)+'...'+''''  ELSE a.[Description] END END +'</span></p></div></li>' ) as Java  
    FROM rvlfAlarm a          
    INNER JOIN rvlfVehicleAssignment va ON va.BoxId = a.BoxId          
    INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId    
    INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId  
    INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId  
    INNER JOIN rvlfSeverity s ON s.AlarmLevelId = a.AlarmLevelId 	
    WHERE   
    ((@bigFleetID IS NULL OR @bigFleetID='') OR f.FleetId = @bigFleetID) AND         
    ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND          
    (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR          
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND          
    ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND          
    ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND          
    ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND          
    (((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) OR          
    ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.ClosedBy IS NULL)) ) and           
    ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND          
    ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND          
    a.AlarmLevelId in (2,3)           
    AND v.OrganizationId = @bigOrganizationID          
    ORDER BY DateTimeCreated DESC) as tbl         
    END  
      
    SELECT @cAlarmHtml as AlarmTemplate,@nCount as AlarmCount    
      
 END          

           
  SET NOCOUNT OFF          
END  



--select * from rvlfOrganization where OrganizationId = 40
--select * from rvlfUser where OrganizationId =40

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarmsForMonitor_New]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[rvlf_sp_GetAlarmsForMonitor_New]        
 @bigAlarmID bigint = null,        
 @bigFleetID bigint = null,        
 @intBoxID int = null,        
 @dtStartDate datetime = null,        
 @dtEndDate datetime = null,        
 @bigAcceptedBy bigint = null,        
 @bigClosedBy bigint = null,        
 @tiBoxMsgInType tinyint = null,        
 @bitIsNew bit = null,        
 @bitIsAccepted bit = null,        
 @bitIsClosed bit = null,        
 @bigOrganizationID bigint,        
 @bigQueryingUser bigint = 0,        
 @bitIsAlarmWindow bit = null,        
 @siSeverityLevel smallint = null,        
 @vcAlarmDesc varchar(50) = null        
AS     

/***********************************************************************************************************************************************************************/        
-- Name   : rvlf_sp_GetAlarmsForMonitor @bigFleetID  = 61, @bigOrganizationID=40, @dtStartDate = '05/24/2012',@dtEndDate='05/25/2012' ,@bitIsAlarmWindow=1,@bigQueryingUser=125       
-- Description  : To get the alarm messages for monitor  
-- Author  : Sakthi      
-- Created Date : 25-Nov-2011  
--    : Sakthi - Alarms load based on fleet id    
/******************************************************************************************************************************************************/        
BEGIN          
 SET NOCOUNT ON           
   
 Declare @dtFDate datetime =@dtStartDate  
 Declare @dtEDate datetime =@dtEndDate          
   
 ------- Included by Kumuthini on 16-July-09 ---------------------          
           
 DECLARE @HoursToBeAdded INT = 0          
 DECLARE @MinsToBeAdded INT = 0          
 DECLARE @DefaultDateFormat INT = 0;            
 DECLARE @ConversionFactor numeric (10,2) = 1.0  
 DECLARE @Privelege INT =0              
 DECLARE @Lang varchar(50)             
  
  
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,          
 @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')      
 FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz          
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser           
           
 DECLARE @isAnglerAdmin bit          
           
 SELECT @isAnglerAdmin = CASE WHEN UserGroupName = 'Angler Admin' THEN 1 ELSE 0 END FROM rvlfUserGroup           
 WHERE UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId=@bigQueryingUser)          
            
 --Included by Jeyanthi on 03-Aug-2010 to show / hide acknowledge           
 Declare @isPrevileged bit          
           
 SELECT @isPrevileged = COUNT(*) FROM rvlfUserGroupSecurity s          
 INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId          
 WHERE ga.UserId = @bigQueryingUser and ModuleID=4 and OperationTypeId =15          
 
 SELECT  @Privelege =  count(ug.UserGroupId) FROM rvlfOperationType op   
 INNER JOIN rvlfUserGroupSecurity  ug ON ug.OperationTypeId = op.OperationTypeId   
 INNER JOIN rvlfUserGroup u ON u.UserGroupId = ug.UserGroupId  
 INNER JOIN rvlfModule m ON M.ModuleID = ug.ModuleId  
 INNER JOIN rvlfUser ur ON ur.OrganizationId = u.OrganizationId  
 INNER JOIN rvlfUserGroupAssignment ga ON ga.UserGroupId = ug.UserGroupId
 WHERE ga.UserId = @bigQueryingUser and ug.ModuleId = 28                 
 --End          
          
 IF @bigFleetID IS NULL           
 BEGIN          
  -- TODO: include the organization check in future          
  --SELECT @bigFleetID = th.fleetId from rvlfFleet th where th.isDefault = 1          
  -- AND OrganizationId = @bigOrganizationID          
 SELECT @bigFleetID = f.fleetId from rvlfFleet f INNER JOIN rvlfUserPreferences up ON up.DefaultFleetId=FleetId   
 WHERE up.UserId=@bigQueryingUser AND f.OrganizationId = @bigOrganizationID   
 END          
 IF @bitIsAlarmWindow = 1  
 BEGIN          
  DECLARE @cAlarmHtml nvarchar(max)  
 DECLARE @nCount int  
 SET @cAlarmHtml = ''  
 SET @nCount = 0  
   
     IF(@Privelege > 0)
   BEGIN
    SELECT @cAlarmHtml=COALESCE(@cAlarmHtml,'')+Java,@nCount=COALESCE(@nCount,'')+1  FROM (select top 25 ('<li id="'+ CAST(a.AlarmId as varchar(15)) +'"><div class=''' +           
    CASE WHEN a.DateTimeAccepted IS null THEN 'yellow-box' ELSE 'green-box' END          
    +'''><span class=''top''></span><p><span class=''yellow-truck'' style="padding-top:3px"><a href=''javascript:ShowAlarm("'+          
    CAST(a.AlarmId as varchar(15)) + '","' + v.VehicleDescription +'","'+CASE WHEN @Privelege = 0 THEN '-' ELSE  ISNULL(ISNULL(dm.DisplayName,dm.DriverName),'-')  END+'","'+case WHEN @Privelege = 0 THEN '-' ELSE ISNULL(ISNULL(dm.MobileNo,dm.PhoneNo),'-') END+'","'+ CAST( a.BoxId AS varchar(6))+'","'+CASE WHEN a.AlarmType = 4 THEN (case when @Lang='LanguageArNew' then N'السرعة:' else 'Speed:' end)+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *          
    @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +          
    CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END          
    WHEN a.AlarmType IN (5,6) THEN 
    case when a.CustomProp IS null Then a.[Description] else (dbo.rvlf_fn_GetAlarmDetails_New(a.customProp,a.AlarmType,a.BoxId, null, a.DateTimeCreated,@Lang)) end                           
    --dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)          
    ELSE (case when a.CustomProp IS null Then a.[Description] else (dbo.rvlf_fn_GetAlarmDetails_New(a.customProp,a.AlarmType,a.BoxId, null, a.DateTimeCreated,@Lang)) end) END+'","'+   
    --ELSE a.[Description] END+'","'+          
    dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)  
   -- Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) , @DefaultDateFormat)          
   -- +' ' + Convert(varchar, cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated))as Time) , 22)    
     +'","'+(case when @Lang='LanguageArNew' then isnull(s.AlarmLevelName_Ar,s.AlarmLevelName) else s.AlarmLevelName end) +'","'+
    --+'","'+s.AlarmLevelName +'","'+          
    CASE           
    WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN case when @Lang='LanguageArNew' then N'لم يتم الاطلاع او الاغلاق'else 'Pending' end                  
    WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN case when @Lang='LanguageArNew' then N'تم الاطلاع'else 'Acknowledged' end                  
    WHEN a.ClosedBy IS Not NULL THEN case when @Lang='LanguageArNew' then N'تم الاغلاق 'else 'Closed' end          
    END          
    --commented on 03-Aug-2010 for restriction Acknowledge button          
    --+'",'+ CASE WHEN a.DateTimeAccepted IS NOT NULL THEN '1' ELSE '0' END +','+ cast(@isAnglerAdmin as char(1))+')''>'+v.DisplayName +'</a></span>&nbsp;<span class='''+ Lower(s.AlarmLevelName)          
    +'",'+ CASE WHEN a.DateTimeAccepted IS NOT NULL THEN '1' When @isPrevileged = 0 Then '1' Else '0' END +','+ cast(@isAnglerAdmin as char(1))+')''>'+v.VehicleDescription +'</a></span>&nbsp;<span class='''+ Lower(s.AlarmLevelName)          
    --End          
    +'-alert'' title='''+ s.AlarmLevelName +'''>&nbsp; </span><br /><span>'+       
   -- Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)), @DefaultDateFormat)+' '           
   --+ Convert(varchar, cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as Time),22)   
   dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)  
   +'</span><br />'+           
    CASE WHEN a.AlarmType = 4 THEN '<span>'+(case when @Lang='LanguageArNew' then N'السرعة:' else 'Speed:' end) + ''+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *          
    @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +           
    CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END          
    WHEN a.AlarmType IN (5,6) THEN CASE WHEN LEN(SUBSTRING(dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),CHARINDEX('>',dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),0)+1,150))>30 THEN SUBSTRING (  
 dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),0,30)+'...'+''''            
    ELSE dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId) END            
    ELSE '<span>' + CASE WHEN LEN(a.[Description])>30 THEN SUBSTRING(a.[Description],0,30)+'...'+''''  ELSE a.[Description] END END +'</span></p></div></li>' ) as Java  
    FROM rvlfAlarm a          
    INNER JOIN rvlfVehicleAssignment va ON va.BoxId = a.BoxId          
    INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId    
    INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId  
    INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId  
    INNER JOIN rvlfSeverity s ON s.AlarmLevelId = a.AlarmLevelId 
	OUTER APPLY (SELECT TOP 1 da.* FROM rvlfDriverAssignment da WHERE da.BoxId =  va.BoxId ORDER BY da.AssignmentId desc) DAS
    LEFT OUTER JOIN rvlfDriverMaster dm on  dm.DriverId  =  DAS.DriverId         
    WHERE   
    ((@bigFleetID IS NULL OR @bigFleetID='') OR f.FleetId = @bigFleetID) AND         
    ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND          
    (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR          
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND          
    ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND          
    ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND          
    ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND          
    (((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) OR          
    ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.ClosedBy IS NULL)) ) and           
    ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND          
    ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND          
    a.AlarmLevelId in (2,3)           
    AND v.OrganizationId = @bigOrganizationID          
    ORDER BY DateTimeCreated DESC) as tbl     
   END    
  ELSE  
   BEGIN  
    SELECT @cAlarmHtml=COALESCE(@cAlarmHtml,'')+Java,@nCount=COALESCE(@nCount,'')+1  FROM (select top 25 ('<li id="'+ CAST(a.AlarmId as varchar(15)) +'"><div class=''' +           
    CASE WHEN a.DateTimeAccepted IS null THEN 'yellow-box' ELSE 'green-box' END          
    +'''><span class=''top''></span><p><span class=''yellow-truck'' style="padding-top:3px"><a href=''javascript:ShowAlarm("'+          
    CAST(a.AlarmId as varchar(15)) + '","' + v.VehicleDescription +'","'+CASE WHEN @Privelege = 0 THEN '-'   END+'","'+case WHEN @Privelege = 0 THEN '-'  END+'","'+ CAST( a.BoxId AS varchar(6))+'","'+CASE WHEN a.AlarmType = 4 THEN ''+(case when @Lang='LanguageArNew' then N'السرعة:' else 'Speed:' end)+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *          
    @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +          
    CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END          
    WHEN a.AlarmType IN (5,6) THEN          
    case when a.CustomProp IS null Then a.[Description] else (dbo.rvlf_fn_GetAlarmDetails_New(a.customProp,a.AlarmType,a.BoxId, null, a.DateTimeCreated,@Lang)) end                           
   -- dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)          
   ELSE (case when a.CustomProp IS null Then a.[Description] else (dbo.rvlf_fn_GetAlarmDetails_New(a.customProp,a.AlarmType,a.BoxId, null, a.DateTimeCreated,@Lang)) end) END+'","'+   
   -- ELSE a.[Description] END+'","'+          
    dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)  
   -- Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) , @DefaultDateFormat)          
   -- +' ' + Convert(varchar, cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated))as Time) , 22)    
     +'","'+(case when @Lang='LanguageArNew' then isnull(s.AlarmLevelName_Ar,s.AlarmLevelName) else s.AlarmLevelName end) +'","'+
  --  +'","'+s.AlarmLevelName +'","'+          
    CASE           
    WHEN a.AcceptedBy IS NULL AND a.ClosedBy IS NULL THEN case when @Lang='LanguageArNew' then N'لم يتم الاطلاع او الاغلاق'else 'Pending' end                  
    WHEN a.AcceptedBy IS Not NULL AND a.ClosedBy IS NULL THEN case when @Lang='LanguageArNew' then N'تم الاطلاع'else 'Acknowledged' end                  
    WHEN a.ClosedBy IS Not NULL THEN case when @Lang='LanguageArNew' then N'تم الاغلاق 'else 'Closed' end              
    END          
    --commented on 03-Aug-2010 for restriction Acknowledge button          
    --+'",'+ CASE WHEN a.DateTimeAccepted IS NOT NULL THEN '1' ELSE '0' END +','+ cast(@isAnglerAdmin as char(1))+')''>'+v.DisplayName +'</a></span>&nbsp;<span class='''+ Lower(s.AlarmLevelName)          
    +'",'+ CASE WHEN a.DateTimeAccepted IS NOT NULL THEN '1' When @isPrevileged = 0 Then '1' Else '0' END +','+ cast(@isAnglerAdmin as char(1))+')''>'+v.VehicleDescription +'</a></span>&nbsp;<span class='''+ Lower(s.AlarmLevelName)          
    --End          
    +'-alert'' title='''+ s.AlarmLevelName +'''>&nbsp; </span><br /><span>'+       
   -- Convert(varchar, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)), @DefaultDateFormat)+' '           
   --+ Convert(varchar, cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) as Time),22)   
   dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)  
   +'</span><br />'+           
    CASE WHEN a.AlarmType = 4 THEN '<span>'+(case when @Lang='LanguageArNew' then N'السرعة:' else 'Speed:' end) + ''+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *          
    @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' +           
    CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END          
    WHEN a.AlarmType IN (5,6) THEN CASE WHEN LEN(SUBSTRING(dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),CHARINDEX('>',dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),0)+1,150))>30 THEN SUBSTRING (  
 dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),0,30)+'...'+''''            
    ELSE dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId) END            
    ELSE '<span>' + CASE WHEN LEN(a.[Description])>30 THEN SUBSTRING(a.[Description],0,30)+'...'+''''  ELSE a.[Description] END END +'</span></p></div></li>' ) as Java  
    FROM rvlfAlarm a          
    INNER JOIN rvlfVehicleAssignment va ON va.BoxId = a.BoxId          
    INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId    
    INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId  
    INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId  
    INNER JOIN rvlfSeverity s ON s.AlarmLevelId = a.AlarmLevelId 	
    WHERE   
    ((@bigFleetID IS NULL OR @bigFleetID='') OR f.FleetId = @bigFleetID) AND         
    ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND          
    (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR          
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND          
    ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND          
    ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND          
    ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND          
    (((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) OR          
    ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.ClosedBy IS NULL)) ) and           
    ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND          
    ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND          
    a.AlarmLevelId in (2,3)           
    AND v.OrganizationId = @bigOrganizationID          
    ORDER BY DateTimeCreated DESC) as tbl         
    END  
      
    SELECT @cAlarmHtml as AlarmTemplate,@nCount as AlarmCount    
      
 END          

           
  SET NOCOUNT OFF          
END  




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarmsForMonitor_Techno]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAlarmsForMonitor_Techno]          
 @bigAlarmID bigint = null,          
 @bigFleetID bigint = null,          
 @intBoxID nvarchar(15) = null,          
 @dtStartDate datetime = null,          
 @dtEndDate datetime = null,          
 @bigAcceptedBy bigint = null,          
 @bigClosedBy bigint = null,          
 @tiBoxMsgInType tinyint = null,          
 @bitIsNew bit = null,          
 @bitIsAccepted bit = null,          
 @bitIsClosed bit = null,          
 @bigOrganizationID bigint,          
 @bigQueryingUser bigint = 0,          
 @bitIsAlarmWindow bit = null,          
 @siSeverityLevel smallint = null,          
 @vcAlarmDesc varchar(50) = null          
AS        
  
/***********************************************************************************************************************************************************************/          
-- Name   : RVLF_SP_GetAlarmsForMonitor @bigQueryingUser=N'458',@bigOrganizationID=N'86',@bigFleetID=N'257',@dtStartDate=N'8/10/2018 6:26:57 AM',@dtEndDate=N'8/13/2018 6:26:57 AM',@bitIsNew=N'True',@bitIsAccepted=N'True',@bitIsAlarmWindow=N'True'
-- Description  : To get the alarm messages for monitor    
-- Author  : Sakthi        
-- Created Date : 25-Nov-2011    
--    : Sakthi - Alarms load based on fleet id      
/******************************************************************************************************************************************************/          
BEGIN            
 SET NOCOUNT off             
     
 Declare @dtFDate datetime =@dtStartDate    
 Declare @dtEDate datetime =@dtEndDate            
     
 ------- Included by Kumuthini on 16-July-09 ---------------------            
             
 DECLARE @HoursToBeAdded INT = 0            
 DECLARE @MinsToBeAdded INT = 0            
 DECLARE @DefaultDateFormat INT = 0;              
 DECLARE @ConversionFactor numeric (10,2) = 1.0    
 DECLARE @Privelege INT =0                
 DECLARE @Lang varchar(50)               
    
    
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,            
 @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')        
 FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz            
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser             
             
 DECLARE @isAnglerAdmin bit            
             
 SELECT @isAnglerAdmin = CASE WHEN UserGroupName = 'Angler Admin' THEN 1 ELSE 0 END FROM rvlfUserGroup             
 WHERE UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId=@bigQueryingUser)            
              
 --Included by Jeyanthi on 03-Aug-2010 to show / hide acknowledge             
 Declare @isPrevileged bit            
             
 SELECT @isPrevileged = COUNT(*) FROM rvlfUserGroupSecurity s            
 INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId            
 WHERE ga.UserId = @bigQueryingUser and ModuleID=4 and OperationTypeId =15            
-- included for Ack/close based on priviledge
 DECLARE @tblAcknowledgeOperation TABLE (UserId int,OperationId int)    
 INSERT INTO @tblAcknowledgeOperation(UserId,OperationId)    
 SELECT ga.UserId,s.OperationTypeId FROM rvlfUserGroupSecurity s                              
 INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId                              
 WHERE ga.UserId = @bigQueryingUser and ModuleID=4 and OperationTypeId IN (369,370)    
     
 Declare @isPrevilegedOpr SMALLINT    
 SELECT @isPrevilegedOpr = (CASE WHEN (SELECT COUNT(OperationId) FROM @tblAcknowledgeOperation) = 2 THEN 1     
 WHEN (SELECT 1 FROM @tblAcknowledgeOperation WHERE OperationId=369)=1 THEN 2     
 WHEN (SELECT 1 FROM @tblAcknowledgeOperation WHERE OperationId=370)=1 THEN 3 ELSE 0 END)  
--
 SELECT  @Privelege =  count(ug.UserGroupId) FROM rvlfOperationType op     
 INNER JOIN rvlfUserGroupSecurity  ug ON ug.OperationTypeId = op.OperationTypeId     
 INNER JOIN rvlfUserGroup u ON u.UserGroupId = ug.UserGroupId    
 INNER JOIN rvlfModule m ON M.ModuleID = ug.ModuleId    
 INNER JOIN rvlfUser ur ON ur.OrganizationId = u.OrganizationId    
 INNER JOIN rvlfUserGroupAssignment ga ON ga.UserGroupId = ug.UserGroupId  
 WHERE ga.UserId = @bigQueryingUser and ug.ModuleId = 28                   
 --End            
            
 IF @bigFleetID IS NULL             
 BEGIN            
  -- TODO: include the organization check in future            
  --SELECT @bigFleetID = th.fleetId from rvlfFleet th where th.isDefault = 1            
  -- AND OrganizationId = @bigOrganizationID            
 SELECT @bigFleetID = f.fleetId from rvlfFleet f INNER JOIN rvlfUserPreferences up ON up.DefaultFleetId=FleetId     
 WHERE up.UserId=@bigQueryingUser AND f.OrganizationId = @bigOrganizationID     
 END            
 IF @bitIsAlarmWindow = 1    
 BEGIN            
  DECLARE @cAlarmHtml nvarchar(max)    
 DECLARE @nCount int    
 SET @cAlarmHtml = ''    
 SET @nCount = 0    
     
     IF(@Privelege > 0)  
   BEGIN  
   print @Privelege  
    SELECT @cAlarmHtml=COALESCE(@cAlarmHtml,'')+Java,@nCount=COALESCE(@nCount,'')+1  FROM (select top 25 ('<li id="'+ CAST(a.AlarmId as varchar(15)) +'"><div class=''' +             
    CASE WHEN a.DateTimeAccepted IS null THEN 'yellow-box' ELSE 'green-box' END            
    +'''><span class=''top-'+ Lower(s.AlarmLevelName) + '''></span><p>
	<span class='''+ Lower(s.AlarmLevelName)                
    +'-alert'' title='''+ s.AlarmLevelName +'''>&nbsp; </span>
	<span class=''yellow-truck'' style="padding-top:3px">'	
	+MD.EquipmentName +'-'+cM.ControllerName+'
	</span>&nbsp;<br /><span>'+            
   dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)    
   +'</span><br />'+             
     (isnull(c.ParamDescription,a.[Description]))+'</span></p></div></li>' ) as Java   
   
    FROM rvlfAlarm a            
    inner join rvlfMAKDevices MD on a.boxid=md.boxid   
    INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId =MD.VehicleId    
    INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId    
    INNER JOIN rvlfSeverity s ON s.AlarmLevelId = a.AlarmLevelId
	INNER JOIN adrControllerMaster CM  ON CM.EquipmentId = a.BoxId 
	left join rvlfParamMst c on a.Description=c.ParamName  
	--and CM.ControllerPositionId = a.ControllerID --- and (MD.SubTypeId=1 or CM.DCSIMId = a.DCSIM)       
    WHERE     
    ((@bigFleetID IS NULL OR @bigFleetID='') OR f.FleetId = @bigFleetID) AND           
    ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND            
    (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR            
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND            
    ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND            
    ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND            
    ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND            
    (((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) OR            
    ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.ClosedBy IS NULL)) ) and 
    ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND            
    ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) 
	--AND a.AlarmLevelId in (2,3)   --and AlarmRepeatFlag=1           
    AND MD.OrganizationId = @bigOrganizationID            
    ORDER BY DateTimeCreated DESC) as tbl       
   END      
  ELSE    
   BEGIN    
    SELECT @cAlarmHtml=COALESCE(@cAlarmHtml,'')+Java,@nCount=COALESCE(@nCount,'')+1  FROM (select top 25 ('<li id="'+ CAST(a.AlarmId as varchar(15)) +'"><div class=''' +             
    CASE WHEN a.AlarmLevelId=1 THEN 'Information-box'
	WHEN a.AlarmLevelId=2 THEN 'yellow-box' 
	WHEN a.AlarmLevelId=3 THEN 'Electricaltrip-box'
	ELSE 'Shutdown-box' END            
    +'''><span class=''top-'+ Lower(s.AlarmLevelName) + '''></span><p></span><span class=''yellow-truck'' style="padding-top:3px">'	
	+MD.EquipmentName +'</span>&nbsp;	
	<br /><span>'+            
   dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)    
   +'</span><br />'+             
    (case when a.CustomProp is null then isnull(P.ParamDescription,a.[Description]) else 
	isnull(P.ParamDescription,a.[Description]) END) +'</span></p></div></li>' ) as Java   
        
    FROM rvlfAlarm a            
  inner join rvlfMAKDevices MD on a.BoxId=md.BoxId    
    INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = MD.VehicleId    
    INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId    
    INNER JOIN rvlfSeverity s ON s.AlarmLevelId = a.AlarmLevelId  
	left join rvlfParamMst P on p.ParamName=a.Description
	--INNER JOIN adrControllerMaster CM  ON CM.EquipmentId = a.BoxId and CM.ControllerPositionId = a.ControllerID  and (MD.SubTypeId=1 or CM.DCSIMId = a.DCSIM)    
    WHERE     
    ((@bigFleetID IS NULL OR @bigFleetID='') OR f.FleetId = @bigFleetID) AND           
    ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND            
    (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR            
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND            
    ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND            
    ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND            
    ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND            
    (((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) OR            
    ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.ClosedBy IS NULL)) ) and             
    ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND            
    ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) 
	--AND a.AlarmLevelId in (2,3)       --and AlarmRepeatFlag=1      
    AND MD.OrganizationId = @bigOrganizationID            
    ORDER BY DateTimeCreated DESC) as tbl           
    END  
    SELECT @cAlarmHtml as AlarmTemplate,@nCount as AlarmCount  
 END          
  --SET NOCOUNT OFF            
END    
  
  
  
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlarmsForMonitor_Test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAlarmsForMonitor_Test]          
 @bigAlarmID bigint = null,          
 @bigFleetID bigint = null,          
 @intBoxID int = null,          
 @dtStartDate datetime = null,          
 @dtEndDate datetime = null,          
 @bigAcceptedBy bigint = null,          
 @bigClosedBy bigint = null,          
 @tiBoxMsgInType tinyint = null,          
 @bitIsNew bit = null,          
 @bitIsAccepted bit = null,          
 @bitIsClosed bit = null,          
 @bigOrganizationID bigint,          
 @bigQueryingUser bigint = 0,          
 @bitIsAlarmWindow bit = null,          
 @siSeverityLevel smallint = null,          
 @vcAlarmDesc varchar(50) = null          
AS        
  
/***********************************************************************************************************************************************************************/          
-- Name   : [rvlf_sp_GetAlarmsForMonitor_Test] @bigFleetID  = 8, @bigOrganizationID=6, @dtStartDate = '22/Dec/2017',@dtEndDate='23/Dec/2017' ,@bitIsAlarmWindow=1,@bigQueryingUser=292
-- Description  : To get the alarm messages for monitor    
-- Author  : Sakthi        
-- Created Date : 25-Nov-2011    
--    : Sakthi - Alarms load based on fleet id      
/******************************************************************************************************************************************************/          
BEGIN            
 SET NOCOUNT ON             
     
 Declare @dtFDate datetime ='22/Dec/2017'    
 Declare @dtEDate datetime ='23/Dec/2017'            
 set @dtStartDate ='22/Dec/2017'    
 set @dtEndDate	  ='23/Dec/2017'            
 ------- Included by Kumuthini on 16-July-09 ---------------------            
             
 DECLARE @HoursToBeAdded INT = 0            
 DECLARE @MinsToBeAdded INT = 0            
 DECLARE @DefaultDateFormat INT = 0;              
 DECLARE @ConversionFactor numeric (10,2) = 1.0    
 DECLARE @Privelege INT =0                
 DECLARE @Lang varchar(50)               
    
    
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,            
 @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')        
 FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz            
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser             
             
 DECLARE @isAnglerAdmin bit            
             
 SELECT @isAnglerAdmin = CASE WHEN UserGroupName = 'Angler Admin' THEN 1 ELSE 0 END FROM rvlfUserGroup             
 WHERE UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId=@bigQueryingUser)            
              
 --Included by Jeyanthi on 03-Aug-2010 to show / hide acknowledge             
 Declare @isPrevileged bit            
             
 SELECT @isPrevileged = COUNT(*) FROM rvlfUserGroupSecurity s            
 INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId            
 WHERE ga.UserId = @bigQueryingUser and ModuleID=4 and OperationTypeId =15            
-- included for Ack/close based on priviledge
 DECLARE @tblAcknowledgeOperation TABLE (UserId int,OperationId int)    
 INSERT INTO @tblAcknowledgeOperation(UserId,OperationId)    
 SELECT ga.UserId,s.OperationTypeId FROM rvlfUserGroupSecurity s                              
 INNER JOIN rvlfUserGroupAssignment ga On s.UserGroupId = ga.UserGroupId                              
 WHERE ga.UserId = @bigQueryingUser and ModuleID=4 and OperationTypeId IN (369,370)    
     
 Declare @isPrevilegedOpr SMALLINT    
 SELECT @isPrevilegedOpr = (CASE WHEN (SELECT COUNT(OperationId) FROM @tblAcknowledgeOperation) = 2 THEN 1     
 WHEN (SELECT 1 FROM @tblAcknowledgeOperation WHERE OperationId=369)=1 THEN 2     
 WHEN (SELECT 1 FROM @tblAcknowledgeOperation WHERE OperationId=370)=1 THEN 3 ELSE 0 END)  
--
 SELECT  @Privelege =  count(ug.UserGroupId) FROM rvlfOperationType op     
 INNER JOIN rvlfUserGroupSecurity  ug ON ug.OperationTypeId = op.OperationTypeId     
 INNER JOIN rvlfUserGroup u ON u.UserGroupId = ug.UserGroupId    
 INNER JOIN rvlfModule m ON M.ModuleID = ug.ModuleId    
 INNER JOIN rvlfUser ur ON ur.OrganizationId = u.OrganizationId    
 INNER JOIN rvlfUserGroupAssignment ga ON ga.UserGroupId = ug.UserGroupId  
 WHERE ga.UserId = @bigQueryingUser and ug.ModuleId = 28                   
 --End            
            
 IF @bigFleetID IS NULL             
 BEGIN            
  -- TODO: include the organization check in future                   
 SELECT @bigFleetID = f.fleetId from rvlfFleet f INNER JOIN rvlfUserPreferences up ON up.DefaultFleetId=FleetId     
 WHERE up.UserId=@bigQueryingUser AND f.OrganizationId = @bigOrganizationID     
 END            
 IF @bitIsAlarmWindow = 1    
 BEGIN            
  DECLARE @cAlarmHtml nvarchar(max)    
 DECLARE @nCount int    
 SET @cAlarmHtml = ''    
 SET @nCount = 0    
     
     IF(@Privelege > 0)  
   BEGIN  
   print @Privelege  
    SELECT @cAlarmHtml=COALESCE(@cAlarmHtml,'')+Java,@nCount=COALESCE(@nCount,'')+1  FROM (select top 25 ('<li id="'+ CAST(a.AlarmId as varchar(15)) +'"><div class=''' +             
    CASE WHEN a.DateTimeAccepted IS null THEN 'yellow-box' ELSE 'green-box' END            
    +'''><span class=''top-'+ Lower(s.AlarmLevelName) + '''></span><p>
	<span class='''+ Lower(s.AlarmLevelName)                 
    +'-alert'' title='''+ s.AlarmLevelName +'''>&nbsp; </span>
	<span class=''yellow-truck'' style="padding-top:3px">'	
	+Md.EquipmentName +'-'+cM.ControllerName+'
	</span>&nbsp;<br /><span>'+            
   dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)    
   +'</span><br />'+             
--    CASE WHEN a.AlarmType IN (5,6) THEN 
--	CASE WHEN LEN(SUBSTRING(dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),
--	CHARINDEX('>',dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),0)+1,150))>30 THEN SUBSTRING (    
-- dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId),0,30)+'...'+''''              
--    ELSE dbo.rvlf_fn_GetScrollingAlarmDetails(a.[Description],a.AlarmType,a.BoxId) END              
--  ELSE '<span>' + CASE WHEN LEN(a.[Description])>30 THEN (case when a.CustomProp is null THEN SUBSTRING(a.[Description],0,30) else SUBSTRING (dbo.rvlf_fn_GetAlarmDetails_New(a.customProp,a.AlarmType,a.BoxId, null, a.DateTimeCreated,@Lang),0,30) END)+'
--...'+''''  ELSE 
(case when a.CustomProp is null then a.[Description] else dbo.rvlf_fn_GetAlarmDetails_New(a.customProp,a.AlarmType,a.BoxId, null, a.DateTimeCreated,@Lang) END)
--END END
 +'</span></p></div></li>' ) as Java   
   -- ELSE '<span>' + CASE WHEN LEN(a.[Description])>30 THEN SUBSTRING(a.[Description],0,30)+'...'+''''  ELSE a.[Description] END END +'</span></p></div></li>' ) as Java    
    FROM rvlfAlarm a            
   -- INNER JOIN rvlfVehicleAssignment va ON va.BoxId = a.BoxId            
   -- INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId   
   inner join rvlfMAKDevices MD on a.boxid=md.boxid   
    INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId =MD.VehicleId    
    INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId    
    INNER JOIN rvlfSeverity s ON s.AlarmLevelId = a.AlarmLevelId
	INNER JOIN adrControllerMaster CM  ON CM.EquipmentId = a.BoxId and CM.ControllerPositionId = a.ControllerID  and (MD.SubTypeId=1 or CM.DCSIMId = a.DCSIM)   
 --OUTER APPLY (SELECT TOP 1 da.* FROM rvlfDriverAssignment da WHERE da.BoxId =  va.BoxId ORDER BY da.AssignmentId desc) DAS  
    --LEFT OUTER JOIN rvlfDriverMaster dm on  dm.DriverId  =  DAS.DriverId           
    WHERE     
    ((@bigFleetID IS NULL OR @bigFleetID='') OR f.FleetId = @bigFleetID) AND           
    ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND            
    (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR            
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND            
    ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND            
    ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND            
    ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND            
    (((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) OR            
    ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.ClosedBy IS NULL)) ) and 
    ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND            
    ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND            
    a.AlarmLevelId in (2,3)   --and AlarmRepeatFlag=1           
    AND MD.OrganizationId = @bigOrganizationID            
    ORDER BY DateTimeCreated DESC) as tbl       
   END      
  ELSE    
   BEGIN    
    SELECT @cAlarmHtml=COALESCE(@cAlarmHtml,'')+Java,@nCount=COALESCE(@nCount,'')+1  FROM (select top 25 ('<li id="'+ CAST(a.AlarmId as varchar(15)) +'"><div class=''' +             
    CASE WHEN a.DateTimeAccepted IS null THEN 'yellow-box' ELSE 'green-box' END            
    +'''><span class=''top-'+ Lower(s.AlarmLevelName) + '''></span><p><span class='''+ Lower(s.AlarmLevelName)                        
    +'-alert'' title='''+ s.AlarmLevelName +'''>&nbsp; </span><span class=''yellow-truck'' style="padding-top:3px">'
	+Md.EquipmentName +'-'+cM.ControllerName +'</span>&nbsp;<br /><span>'+            
   dbo.rvlf_fn_DayLightSavings(a.DateTimeCreated,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,a.DateTimeCreated)    
   +'</span><br />'+             
    case when a.CustomProp is null then a.[Description] else dbo.rvlf_fn_GetAlarmDetails_New(a.customProp,a.AlarmType,a.BoxId, null, a.DateTimeCreated,@Lang) END +'</span></p></div></li>' ) as Java 
    FROM rvlfAlarm a            
    inner join rvlfMAKDevices MD on a.BoxId=md.BoxId    
    INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = MD.VehicleId    
    INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId    
    INNER JOIN rvlfSeverity s ON s.AlarmLevelId = a.AlarmLevelId    
	INNER JOIN adrControllerMaster CM  ON CM.EquipmentId = a.BoxId and CM.ControllerPositionId = a.ControllerID  and (MD.SubTypeId=1 or CM.DCSIMId = a.DCSIM) 
    WHERE     
    ((@bigFleetID IS NULL OR @bigFleetID='') OR f.FleetId = @bigFleetID) AND           
    ((@intBoxID IS NULL OR @intBoxID='') OR a.BoxId = @intBoxID) AND            
    (((@dtStartDate IS NULL OR @dtStartDate='') OR (@dtEndDate IS NULL OR @dtEndDate='')) OR            
    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND            
    ((@bigAcceptedBy IS NULL OR @bigAcceptedBy='') OR a.AcceptedBy = @bigAcceptedBy) AND            
    ((@bigClosedBy IS NULL OR @bigClosedBy='') OR a.ClosedBy = @bigClosedBy ) AND            
    ((@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='') OR a.AlarmType = @tiBoxMsgInType)AND            
    (((@bitIsNew IS NULL OR @bitIsNew='') OR (a.AcceptedBy IS NULL AND a.ClosedBy IS NULL)) OR            
    ((@bitIsAccepted IS NULL OR @bitIsAccepted='') OR (a.ClosedBy IS NULL)) ) and             
    ((@siSeverityLevel IS NULL OR @siSeverityLevel='') OR a.AlarmLevelId = @siSeverityLevel) AND            
    ((@bigAlarmID IS NULL OR @bigAlarmID='') OR a.AlarmId = @bigAlarmID ) AND            
    a.AlarmLevelId in (2,3)       --and AlarmRepeatFlag=1      
    AND MD.OrganizationId = @bigOrganizationID            
    ORDER BY DateTimeCreated DESC) as tbl           
    END    
        

    SELECT @cAlarmHtml as AlarmTemplate,@nCount as AlarmCount      
        
 END            
  
             
  SET NOCOUNT OFF            
END    
  
  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlertsForDashboard]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvlf_sp_GetAlertsForDashboard]  
(  
 @bigOrganizationID bigint,  
    @bigFleetID bigint = null,  
 @dtStartDate datetime = null,   
 @dtEndDate datetime = null,   
 @bigQueryingUser bigint = null,  
 @bigTopNos bigint = 5 --,  
 --@bitIsWarning bit = null,  
 --@bitIsCritical bit = null  
)  
as  
/******************************************************************************/  
-- Name  : rvlf_sp_GetAlertsForDashboard  
-- Description : To get the alerts for the dashboard  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 10-Oct-2009 MJJC Created Intial Version   
/******************************************************************************/                          
Begin  
 --IF @bitIsWarning IS NULL AND @bitIsCritical IS NULL  
 --BEGIN  
  SELECT top (@bigTopNos)   
   SUM(CASE WHEN a.AlarmLevelId = 2 THEN 1 ELSE 0 END) as WarningAlarms,  
   SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) as CriticalAlarms,  
    a.BoxID,v.VehicleDescription,  
    SUBSTRING(v.VehicleDescription,1, 10)   
   + CASE WHEN LEN(v.VehicleDescription)>10 THEN '...' ELSE '' END as VehicleName  
  FROM rvlfAlarm a  
   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  WHERE   
   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND  
   (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) AND   
   ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
     a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)  
  GROUP BY a.BoxId, v.VehicleDescription  
  HAVING  
    SUM(CASE WHEN a.AlarmLevelId = 2 THEN 1 ELSE 0 END) > 0 AND  
     SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) >0  
  ORDER BY   
  --CASE WHEN   
  CriticalAlarms DESC,  
--AND @OrderByDirection = 'D'  
--THEN StateProvinceID END DESC,  
--   CriticalAlarms DESC ,   
   WarningAlarms DESC  
 --END  
  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAlertsForDrillDownDrivingBehavior]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [dbo].[rvlf_sp_GetAlertsForDrillDownDrivingBehavior]    

 @VehicleDesc nvarchar(max) = NULL,    
 @bigOrganizationID bigint = NULL,    
 @bigQueryingUser bigint = NULL,
 @dtStartDate datetime = Null,    
 @dtEndDate datetime = NULL,
 @bigFleetID bigint = null  
 
AS  
/********************************************************************************************************    
-- Name		   : rvlf_sp_GetAlertsForDrillDownDrivingBehavior
-- Description : To get the Speed Alerts details        
-- Author      : Ranjith N        
*********************************************************************************************************/ 
BEGIN    
 SET NOCOUNT ON    


 declare @Lang varchar(50)   
    select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser
 
 DECLARE @tblSpeedAlert TABLE     
  ( TypeAlert Nvarchar(max),TypeAlertCount int,TypeAlert1 Nvarchar(max))
  

  DECLARE @intBoxMsgInTypeId int =(SELECT MIN(BoxMsgInTypeId) FROM rvlfBoxMsgInType where BoxMsgInTypeId in (4,14,15,16,17,24))          
WHILE @intBoxMsgInTypeId IS NOT NULL          
 BEGIN 
	insert into @tblSpeedAlert(TypeAlert,TypeAlertCount,TypeAlert1) 
	select (case when @Lang='LanguageArNew' then ISNULL(BoxMsgInTypeDesc_Ar,BoxMsgInTypeName)  else BoxMsgInTypeName end), COUNT(a.Speed),BoxMsgInTypeName
	from rvlfMsgInHst a
		INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
		INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId 
		inner join rvlfBoxMsgInType bm on bm.BoxMsgInTypeId = a.BoxMsgInTypeId
		where    
		(v.OrganizationId = @bigOrganizationID) AND 
		(fv.FleetId = @bigFleetID) and      
		(case when @Lang='LanguageArNew' then ISNULL(v.VehicleDescription,v.VehicleDescription)  else v.VehicleDescription  end) =@VehicleDesc  and
		(a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
		--month(a.OriginDateTime) between 01 and 02   and year(a.OriginDateTime) = 2015
		and a.BoxMsgInTypeId = @intBoxMsgInTypeId 
		group by BoxMsgInTypeName,BoxMsgInTypeDesc_Ar

  SELECT @intBoxMsgInTypeId = MIN(BoxMsgInTypeId) FROM rvlfBoxMsgInType WHERE BoxMsgInTypeId >@intBoxMsgInTypeId and BoxMsgInTypeId in (4,14,15,16,17,24)            
 END 
 
	

		select * from @tblSpeedAlert order by TypeAlertCount desc

    SET NOCOUNT OFF    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllCategory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Updated by  : VN On 21-Dec-2009 fro getting values order by categoryname 
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetAllCategory] 
	-- Add the parameters for the stored procedure here
	@OrganizationId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT CategoryId, CategoryName, CategoryDescription,
	CASE WHEN EXISTS(SELECT OG.CategoryId FROM rvlfOrganizationGeozone OG WHERE OG.CategoryId = rvlfCategory.CategoryId) 
		THEN 1 ELSE 0 END AS AssignedStatus 
	FROM rvlfCategory WHERE OrganizationId = @OrganizationId ORDER BY CategoryName  

END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllDeviceSensorsOutputs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetAllDeviceSensorsOutputs]	
AS
/**************************************************************************************/
--	Name		:	rvlf_sp_GetAllDeviceSensorsOutputs
--	Description	:	To get assinged and unassinged Sensors and Outputs for the Devices
--	Author		:	S. Jeyanthi
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	23-Oct-2010		Created Intial Version  
/*************************************************************************************/
BEGIN
	SET NOCOUNT ON 
	 
	SELECT SensorId, SensorName, ActionOn, ActionOff FROM rvlfSensor 	
    
    SELECT * FROM rvlfOutput   
      	
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllGeozones]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAllGeozones]        
 @bigOrganizationID bigint=null,        
 @bigCategoryID varchar(5)=null,
 @GeozoneType tinyint=0   
AS        
/******************************************************************************/        
-- Name  : rvlf_sp_GetAllGeozones 6 ,''  
-- Description : To get the all geozones depends on category and organization        
--     Existing procedure have delete functionality so passing argument is        
--     difficult        
-- Author  : V.Narayanasamy        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--    : 16-Nov-2009 VN Created Intial Version         
--    : 21-Dec-2009 VN for getting values order by geozone name      
--   : 24-Jan-2014 For get geozone on toll gate category  
--19-apr-2016 included the geozone type license based       
/******************************************************************************/        
BEGIN 
Declare @GeoType varchar(10)='2'
SELECT @GeoType= coalesce(@GeoType + ', ', '') + case when a.OperationID =414 then '1' when a.OperationID=415 then '3' end
FROM (select OperationID from rvlfOrganizationPackage op inner join rvlfPackageOperations po on op.PackageId=po.PackageId
where po.OperationID in (414,415) and OrganizationID=@bigOrganizationID and IsActive=1) a
      
if(@bigCategoryID='0')      
begin      
select @bigCategoryID=CategoryId from rvlfCategory where CategoryName='Toll gate' and OrganizationId=@bigOrganizationID      
end      
if(@GeozoneType=0)    
begin        
 SELECT GeozoneNo,GeozoneName,GeozoneId,GeozoneType,Radius FROM rvlfOrganizationGeozone               
 WHERE (((@bigOrganizationID IS NULL OR @bigOrganizationID='') OR OrganizationId=@bigOrganizationID ))              
   AND (@bigCategoryID IS NULL OR @bigCategoryID <>0 or @bigCategoryID='' OR CategoryId=@bigCategoryID) 
   AND GeozoneType in ((select * from rvlf_fn_ConvertArrayToTable(@GeoType,',')))      
   ORDER BY GeozoneName               
END    
ELSE    
 begin    
   SELECT a.GeozoneNo,GeozoneName,GeozoneId,GeozoneType,Radius,b.Latitude,b.Longitude,c.CategoryName FROM rvlfOrganizationGeozone a     
   inner join rvlfGeozoneSet b on a.GeozoneNo=b.GeozoneNo    
   left join rvlfCategory c on a.CategoryId=c.CategoryId    
   WHERE (((@bigOrganizationID IS NULL OR @bigOrganizationID='') OR a.OrganizationId=@bigOrganizationID))    
   AND (@bigCategoryID IS NULL OR @bigCategoryID <>0 or @bigCategoryID='' OR a.CategoryId=@bigCategoryID)       
   AND (((@GeozoneType IS NULL OR @GeozoneType=0) OR GeozoneType=@GeozoneType)) 
   AND GeozoneType in ((select * from rvlf_fn_ConvertArrayToTable(@GeoType,',')))   
 ORDER BY GeozoneName     
 end    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllLandmarkCategory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetAllLandmarkCategory]
	-- Add the parameters for the stored procedure here
	@OrganizationId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT LandmarkCategoryId, CategoryName, [Description],ImagePath  FROM rvlfLandmarkCategory where OrganizationId = @OrganizationId
	
	Declare @landmark varchar(max)  
	SET @landmark=''  
	SELECT @landmark += CAST(Latitude AS VARCHAR)+'~#~'+CAST(Longitude AS VARCHAR)+'~#~'+CAST(Radius AS VARCHAR)+'~#~'+CAST(LandmarkName AS VARCHAR)+  
	'~#~'+CAST(StreetAddress AS VARCHAR(max))+'~&~' FROM rvlfLandmark l INNER JOIN rvlfOrganization o ON l.OrganizationId=o.OrganizationId  
	WHERE o.OrganizationId=@OrganizationId  
	SELECT @landmark AS LandmarkEntries   
END

select * from rvlfLandmarkCategory


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllNotificationUsers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAllNotificationUsers]  
  
/******************************************************  
Stored Procedure Name : rvlf_sp_GetAllNotificationUsers 277,null,null,null   
Purpose      : Retrieve both registered and unregistered users for notification settings  
Created by            : Kumuthini. L  
Created date          : 06-Jan-11  
Update History:     
*******************************************************/  
  
@bigOrganizationId bigint = null,  
@vcUserIDsList varchar(max) = null,  
@vcUserName varchar(50) = null,  
@intUserGroupID int = null,
@intUserid int =null      
   
AS  
BEGIN         
   
    DECLARE @tblUserList Table   
 (  
  UserID bigint  
 )  

   declare @usergrp int    
  
   set @usergrp=(SELECT g.UserGroupId FROM rvlfUserGroupAssignment ga         
    INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId        
    WHERE ga.UserId = @intUserid)   
   
 IF @vcUserIDsList IS NOT NULL  
    BEGIN  
      
   SELECT u.UserId, u.UserName, u.DisplayName, dbo.rvlf_fn_GetUserGroupsByUserID(u.UserId) AS GroupBelongsTo,  
      CASE WHEN u.IsLocked= 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,  
   Email, MobileNo, IsRegisteredUser  
   FROM rvlfUser u   
   LEFT OUTER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId  
   LEFT OUTER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId  
   WHERE         
   u.userID IN (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcUserIDsList,',')) AND U.ISDELETE=0 
   AND  u.IsHidden <> (case when @usergrp = 1 and @intUserid <> null then 2 else 1 end)     
   ORDER BY UserName ASC   
     
    END  
    ELSE IF @intUserGroupID IS NOT NULL  
    BEGIN  
      
  IF @vcUserName IS NOT NULL   
  BEGIN  
   INSERT INTO @tblUserList   
      SELECT u.UserId FROM rvlfUser u   
   LEFT OUTER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId  
   LEFT OUTER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId  
      WHERE u.OrganizationId = @bigOrganizationId AND U.ISDELETE=0 AND (IsActive IS NULL OR IsActive = 1) 
	  AND  u.IsHidden <> (case when @usergrp = 1 and @intUserid <> null then 2 else 1 end)      
      AND (@vcUserName IS NULL OR @vcUserName='' OR u.UserName like '%'+ @vcUserName +'%' )  
        
  END  
    
  INSERT INTO @tblUserList   
  SELECT u.UserId FROM rvlfUser u   
   LEFT OUTER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId  
   LEFT OUTER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId  
      WHERE u.OrganizationId = @bigOrganizationId AND U.ISDELETE=0 AND (IsActive IS NULL OR IsActive = 1)  
	  AND  u.IsHidden <> (case when @usergrp = 1 and @intUserid <> null then 2 else 1 end)     
      AND (@intUserGroupID IS NULL OR @intUserGroupID='' OR ga.UserGroupId = @intUserGroupID)  
        
  SELECT u.UserId, u.UserName, u.DisplayName, dbo.rvlf_fn_GetUserGroupsByUserID(u.UserId) AS GroupBelongsTo,  
      CASE WHEN u.IsLocked = 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,  
   Email, MobileNo, IsRegisteredUser  
   FROM rvlfUser u   
   LEFT OUTER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId  
   LEFT OUTER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId  
   WHERE u.OrganizationId = @bigOrganizationId AND U.ISDELETE=0 AND (IsActive IS NULL OR IsActive = 1)  
   AND  u.IsHidden <> (case when @usergrp = 1 and @intUserid <> null then 2 else 1 end)     
   AND u.UserId IN (SELECT UserId FROM @tblUserList)  
   ORDER BY UserName ASC   
      
    END  
    ELSE IF @vcUserName IS NOT NULL   
    BEGIN  
      
   SELECT u.UserId, u.UserName, u.DisplayName, dbo.rvlf_fn_GetUserGroupsByUserID(u.UserId) AS GroupBelongsTo,  
      CASE WHEN u.IsLocked = 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,  
   Email, MobileNo, IsRegisteredUser  
   FROM rvlfUser u   
   LEFT OUTER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId  
   LEFT OUTER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId  
   WHERE u.OrganizationId = @bigOrganizationId AND U.ISDELETE=0 AND (IsActive IS NULL OR IsActive = 1)  
   AND  u.IsHidden <> (case when @usergrp = 1 and @intUserid <> null then 2 else 1 end)     
   AND (@vcUserName IS NULL OR @vcUserName='' OR u.UserName like '%'+ @vcUserName +'%' )   
   ORDER BY UserName ASC   
      
    END  
 ELSE  
 BEGIN  
   
   SELECT u.UserId, u.UserName, u.DisplayName, dbo.rvlf_fn_GetUserGroupsByUserID(u.UserId) AS GroupBelongsTo,  
      CASE WHEN u.IsLocked = 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,  
   Email, MobileNo, IsRegisteredUser  
   FROM rvlfUser u   
   LEFT OUTER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId  
   LEFT OUTER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId  
   WHERE u.OrganizationId = @bigOrganizationId AND U.ISDELETE=0 AND (IsActive IS NULL OR IsActive = 1)  
   AND  u.IsHidden <> (case when @usergrp = 1 and @intUserid <> null then 2 else 1 end)     
   ORDER BY UserName ASC   
      
 END  
        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllROICosts]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetAllROICosts]
@CostId tinyint = null,
@bigOrganizationID bigint = null,
@bigUserId bigint = 0
AS
/***********************************************************************************************************************/          
-- Name   : rvlf_sp_GetAllROICosts 
-- Description : To get the ROI Costs
-- Author  : Sakthi  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : 17-Jun-2013 Sakthi    
/***********************************************************************************************************************/ 
BEGIN
SET NOCOUNT ON
	SELECT Id [CostId],CostName,CostDesc [Description],(CostType-1) AS CostType,CAST(NULL AS DECIMAL(10,2)) AS PlannedCost,
	CASE WHEN CostType=1 THEN 'Operational Cost' WHEN CostType=2 THEN 'Ownership Cost' ELSE 'Other Cost' END AS [TypeOfCost]
	FROM rvlfROICost WHERE (@CostId IS NULL OR @CostId=0 OR Id=@CostId) AND (@bigOrganizationId IS NULL OR @bigOrganizationId = 0 OR OrgId=@bigOrganizationId) 
	AND ISNULL(IsDelete,0)=0
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllScreenRefreshFrequencies]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetAllScreenRefreshFrequencies]
AS
/******************************************************************************/
--	Name		  : rvlf_sp_GetAllScreenRefreshFrequencies
--	Description	  :	To get all the Screen Refresh Frequencies
--	Author		  :	Kumuthini. L
--	Created Date  : 14-July-09
--  Modified Date :
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 
	
	SELECT FrequencyId, RefreshFrequencyValue FROM rvlfScreenRefreshFrequency 
		
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllTimeZones]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetAllTimeZones]
(
	@Type Char(2),
	@bigQueryingUser bigint = 0
)
AS
/******************************************************************************/
--	Name		  : rvlf_sp_GetAllTimeZones
--	Description	  :	To get all the Time Zones or select the particular TimeZone
--                : Details based on the TimeZone Id
--	Author		  :	Kumuthini. L
--	Created Date  : 10-July-09
--  Modified Date : 17-July-09
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 
	
	-- If Type is 'A', then get all the TimeZone Details
	IF(@Type = 'A')
	BEGIN
			SELECT TimeZoneId, TimeZoneName + ' ('+ TimeZoneDesc +')' as TimeZoneName FROM rvlfTimeZones  
	END
    -- If Type is 'UP', then get particular TimeZone Details based on the User Preference by passing the User Id
	ELSE IF(@Type = 'UP')
	BEGIN
	     SELECT tz.HoursToBeAdded, tz.MinToBeAdded, up.Distance
		 FROM rvlfUserPreferences up 
		 INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser
	END
		
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllTitles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetAllTitles]

AS
/******************************************************************************/
--	Name		  : rvlf_sp_GetAllTitles
--	Description	  :	To get all the titles for the users
--	Author		  :	Kumuthini. L
--	Created Date  : 24-Sep-09
--  Modified Date : 
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 

       SELECT TitleId, TitleName FROM rvlfTitle
		
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllUserGroups]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetAllUserGroups]  
(  
   @bigOrganizationId AS BIGINT = null,
   @bigUserID as int =null
)  
  
AS  
/*******************************************************************************/  
-- Name    : rvlf_sp_GetAllUserGroups  6
-- Description   : To get all the User Groups   
-- Author    : Kumuthini. L  
-- Created Date  : 27-July-09  
--  History       : Modified By Kumuthini.L on 20-Nov-09 for getting user groups  
--                  based on Organization  
-- exec rvlf_sp_GetAllUserGroups @bigOrganizationId=N'86',@bigUserID=N'544'
/*******************************************************************************/  
BEGIN  
	--declare @CheckUser int =null,@lastname nvarchar(100),@CheckUGid int 
	--select @CheckUGid=UserGroupId from rvlfUserGroupAssignment where UserId=@bigUserID
	--select @lastname=LastName from rvlfUser where UserId=@bigUserID
	--if((@lastname like '%VXL%' or @lastname like '%trinetra%') or @CheckUGid=1)
	--begin
	--	set @CheckUser=null
	--end
	--else
	--begin
	--	set @CheckUser=1
	--end
    SELECT UG.UserGroupName, UG.UserGroupDesc, UG.UserGroupId, UG.IsDefaultUserGroup,  
    CASE WHEN EXISTS(SELECT UA.UserGroupId FROM rvlfUserGroupAssignment UA WHERE UA.UserGroupId = UG.UserGroupId)  
    THEN 1 ELSE 0 END AssignedStatus,  
    CASE WHEN EXISTS(SELECT P.PackageId FROM rvlfOrganizationPackage P WHERE @bigOrganizationId IS NULL OR @bigOrganizationId='' OR P.OrganizationId = @bigOrganizationId)  
    THEN 1 ELSE 0 END PackageStatus,
	(SELECT COUNT(UserId) FROM rvlfUserGroupAssignment a WHERE a.UserGroupId=UG.UserGroupId) AS UserCount  
    FROM rvlfUserGroup UG   
    WHERE (@bigOrganizationId IS NULL OR @bigOrganizationId='' OR UG.OrganizationId = @bigOrganizationId) --  and ((@CheckUser is Null) or (UG.UserGroupName like '%CUST_%'))
    
    select ISNULL(COUNT(UserGroupId),0) as GeozoneCreated, NoOfUSerGroups as AllowedCount,
	CASE WHEN ISNULL(COUNT(UserGroupId),0) >=(ISNULL(NoOfUSerGroups,0)) THEN '0' ELSE '1' END as IsAllowed
	from rvlfOrganization O inner JOIN rvlfUserGroup UG on O.OrganizationId = UG.OrganizationId 
	where UG.OrganizationId = @bigOrganizationId-- and ((@CheckUser is Null) or (UG.UserGroupName like '%CUST_%'))
	group by O.NoOfUSerGroups
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllUsers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAllUsers]         
/******************************************************        
Stored Procedure Name : rvlf_sp_GetAllUsers    389    
Purpose     : Retrieve all Users        
Created by    : Uma        
Created date   : 11-Jul-09        
Updated by    :         
Updated date   :         
*******************************************************/        
        
@FleetID int  = Null        
        
AS        
        
BEGIN         
         
 SELECT fleet.fleetid, fleet.UserId, usr.UserName  from rvlfFleetUsers fleet        
 join rvlfUser usr on usr.UserId = fleet.UserId  
 --INNER JOIN rvlfUserGroupAssignment ga ON usr.UserId = ga.UserId            
 WHERE         
 ((@FleetID is Null) or (FleetId=@FleetID) or (@FleetID = 0))      --and usr.IsDelete=0  
 ORDER BY usr.UserName ASC   
        
END        
-- rvlf_sp_GetAllUsers Null  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllVehicleMake]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAllVehicleMake]       
/******************************************************      
Stored Procedure Name : rvlf_sp_GetAllVehicleMake
Purpose     : Retrieve all Vehicle Make      
Created by    : Uma      
Created date   : 20-Jul-09      
Updated by    :       
Updated date   :       
*******************************************************/      
      
@VehMakeID int  = Null      
      
AS      
      
BEGIN       
       
 SELECT * from rvlfMake  
 WHERE       
 ((@VehMakeID is Null) or (MakeId  =@VehMakeID) or (@VehMakeID = 0))      
 ORDER BY MakeName ASC 
      
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllVehicleModel]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAllVehicleModel]       
/******************************************************      
Stored Procedure Name : rvlf_sp_GetAllVehicleModel
Purpose     : Retrieve all Vehicle Model      
Created by    : Uma      
Created date   : 20-Jul-09      
Updated by    :       
Updated date   :       
*******************************************************/      
      
@VehModelID int  = Null      
      
AS      
      
BEGIN       
       
 SELECT * from rvlfModel   
 WHERE       
 --((@VehModelID is Null) or (ModelId   =@VehModelID) or (@VehModelID = 0)) 
 ((@VehModelID is Null) or (MakeId   =@VehModelID) or (@VehModelID = 0))       
 ORDER BY ModelName  ASC 
      
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAllVehicles] 
/******************************************************
Stored Procedure Name	: rvlf_sp_GetAllVehicles
Purpose					: Retrieve all vehicle
Created by				: Uma
Created date			: 09-Jul-09
Updated by				: 
Updated date			: 
*******************************************************/

@FleetId	int		= Null

AS

BEGIN	
	
	SELECT fleet.fleetid, fleet.VehicleId, veh.VehicleDescription  from rvlfFleetVehicles fleet
	join rvlfVehicle veh on veh.VehicleId=fleet.VehicleId 
	WHERE 
	((@FleetId is Null) or (FleetId=@FleetId) or (@FleetId = 0))
	ORDER BY veh.VehicleDescription 

END
-- rvlf_sp_GetAllVehicles Null


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAllVehicleType]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAllVehicleType]       
/******************************************************      
Stored Procedure Name : rvlf_sp_GetAllVehicleType      
Purpose     : Retrieve all Vehicle Types      
Created by    : Uma      
Created date   : 20-Jul-09      
Updated by    :       
Updated date   :       
*******************************************************/      
      
@VehTypeID int  = Null      
      
AS      
      
BEGIN       
       
 SELECT * from rvlfVehicleType 
 WHERE       
 ((@VehTypeID is Null) or (VehicleTypeId =@VehTypeID) or (@VehTypeID = 0))      
 ORDER BY VehicleTypeName  ASC 
      
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetandUpdateRFIDStudentSMSTrigger]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetandUpdateRFIDStudentSMSTrigger]   
( 
	@intBoxID		bigint                     
  --@dtOriginDateTime datetime,                       
  --@vcCustomProp varchar(max)=null      
 )                         
AS                                      
/******************************************************************************/                                      
-- Name  : [rvlf_sp_GetandUpdateRFIDStudentSMSTrigger]                                      
-- Description : To get the vehicle expired details based on the current date                                      
-- Author  : K.Kapilraj                                      
-- Company  : Angler Technologies                                      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                      
--    : 26-Sep-2014 VN Created initial version                                        
--    : 19-Feb-Sep-2014 VN Created initial version                                        
--    : 25-Mar-2015 Updated for multiple school scenario                
/******************************************************************************/                                      
BEGIN                                  
                                  
Declare @T1 as table                                  
(ID  int identity (1,1) NOT NULL,BoxId INT,VehicleId INT,RFID varchar(250),GeozoneId int,BoxMsgInTypeId int,        
Origindatetime datetime,StudentId BIGINT,OrgId int,MessageInID nvarchar(150),SchoolGeozoneId int                          
)--Counts int,OrganizationID bigint,DriverId bigint  
             
Declare @DevicePackets as table                            
(BoxId INT,VehicleId INT,RFID varchar(250),GeozoneId int,BoxMsgInTypeId int,  
Origindatetime datetime,OrgId int,MessageInID uniqueidentifier)   
  
INSERT INTO @DevicePackets  
select H.BoxId,V.VehicleId,                            
dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';') as RFID ,   
dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'GeozoneID=',';') as GeozoneID,   
h.BoxMsgInTypeId, H.OriginDateTime,V.OrganizationId , H.MessageInID  
from rvlfMsgInHst H   
INNER JOIN rvlfVehicleAssignment VA on VA.BoxId = H.BoxId   
INNER JOIN rvlfVehicle V on VA.VehicleId = V.VehicleId   
where CONVERT(DATE,OriginDateTime) = CONVERT(date,GETUTCDATE())   
 and h.boxid =@intBoxID  
AND (H.BoxMsgintypeid = 5 OR H.BoxMsgintypeid = 6  or H.BoxMsgInTypeId = 100 or   
(H.BoxMsgInTypeId=114 and  CHARINDEX('GeozoneInOutWithDuration',CustomProp,0)>0))   
                       
INSERT INTO @T1  
  
select H.BoxId,h.VehicleId,h.RFID,h.GeozoneId,h.BoxMsgInTypeId, H.OriginDateTime,M.StudentMasterID,h.OrgId, H.MessageInID   
,SCM.GeozoneId   
from @DevicePackets as h  
LEFT OUTER JOIN rvlfStudentMaster M on M.RFID = h.RFID   
left join rvlfSchoolMaster SCM on M.SchoolID=SCM.SchoolID   
left join rvlf_StudentRFIDSMSMessegeInIDLog SL on H.MessageInID=SL.MessageInID                        
where SL.MessageInID is null and h.VehicleId in (select VehicleId from rvlfStudentVehicleAssignment)  
GROUP BY  H.BoxId,h.VehicleId,h.RFID,h.GeozoneId ,h.BoxMsgInTypeId,h.OriginDateTime,M.StudentMasterID,h.OrgId,H.MessageInID,SCM.GeozoneId  
    
ORDER BY h.OriginDateTime   
  
--select COUNT(H.BoxId),H.BoxId,V.VehicleId,   
--dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';') as RFID ,   
--dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'GeozoneID=',';') as GeozoneID,   
--h.BoxMsgInTypeId, H.OriginDateTime,M.StudentMasterID, B.organizationID,H.MessageInID,bm.DriverId,SCM.GeozoneId ,b.OrganizationId  
--from rvlfMsgInHst H  
--INNER JOIN rvlfboxid B on B.BoxId = H.BoxId  
--INNER JOIN rvlfVehicleAssignment VA on VA.BoxId = H.BoxId  
--INNER JOIN rvlfStudentVehicleAssignment SA on SA.VehicleId = VA.VehicleId  
----INNER JOIN rvlfStudentMaster SM on SM.StudentMasterID = SA.StudentMasterId 2014-09-24 07:19:30.000                                  
--LEFT OUTER JOIN rvlfStudentMaster M on M.RFID = dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';')                              
--left join rvlfSchoolMaster SCM on M.SchoolID=SCM.SchoolID  
--INNER JOIN rvlfVehicle V on VA.VehicleId = V.VehicleId  
--left join rvlfIButtonMapping bm on bm.IButtonKey = dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';')  
--left join rvlfDriverAssignment da on bm.BoxID=da.BoxId   
--left join rvlf_StudentRFIDSMSMessegeInIDLog SL on H.MessageInID=SL.MessageInID                              
--where CONVERT(DATE,OriginDateTime) = CONVERT(date,GETUTCDATE()) and SL.MessageInID is null   
--AND (H.BoxMsgintypeid = 5 OR H.BoxMsgintypeid = 6  or H.BoxMsgInTypeId = 100 or   
--(H.BoxMsgInTypeId=114 and CustomProp like '%GeozoneInOutWithDuration%'))  and H.BoxId=@intBoxID   
--GROUP BY  V.VehicleDescription,H.BoxId,CustomProp,h.OriginDateTime,h.BoxMsgInTypeId,V.VehicleId,B.OrganizationId ,M.StudentMasterID          ,B.organizationID,H.MessageInID ,bm.DriverId ,SCM.GeozoneId   
--ORDER BY h.OriginDateTime   
   
select * from @T1                               
                                  
--update X set X.GeozoneId = C.GeozoneId  from @T1 X INNER JOIN         
--(select GeozoneId,Boxid from @T1 WHERE GeozoneId IS NOT NULL GROUP BY Boxid,GeozoneId)                                  
--as C on C.Boxid = X.Boxid        
--update X set X.GeozoneId = C.GeozoneId  from @T1 X INNER JOIN                               
-- (select a.GeozoneId,Boxid from @T1 as a inner join rvlfSchoolMaster SM on a.geozoneid=SM.GeozoneId and a.OrganizationID=SM.OrganizationID  
--    WHERE a.GeozoneId IS NOT NULL --and SM.OrganizationID=6                          
--    GROUP BY Boxid,a.GeozoneId)                          
--as C on C.Boxid = X.Boxid  and X.GeozoneId is null                          
                                  
DECLARE @T2 as table                                  
(ID int, RFID varchar(100),Boxid int,vehicleId int, GeozoneId int,StudentId int,OrgId int,                                  
BoxMsgInTypeId int,                                  
Origindatetime datetime,                                  
Stat int,                                  
MessageInID nvarchar(150),                                  
EntryTime datetime ,SchoolGeozoneId int                                 
)         
        
DECLARE @ReturnTrip as table                                  
(ID int,                                  
RFID varchar(100),                                  
Boxid int,                                  
vehicleId int,                                  
GeozoneId int,                                  
StudentId int,                                  
OrgId int,                                  
BoxMsgInTypeId int,                                  
Origindatetime datetime,                                  
Stat int,                                  
MessageInID nvarchar(150),                                  
ExitTime datetime ,SchoolGeozoneId int                                 
)                                  
                                  
DECLARE @ID INT, @RFID varchar(50),@BoxID INT,@vehicleID INT,@GeozoneID INT,@StudentID INT,@OrgID INT, @BoxMsgInID INT, @Origindatetime DATETIME,@MessageInID NVARCHAR(maX),@SchoolGeozoneId int                
DECLARE cursorName CURSOR                                   
   FOR                                   
     select ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID,SchoolGeozoneId from @T1  
     OPEN cursorName                                            
    FETCH NEXT FROM cursorName                                   
    INTO @ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID,@SchoolGeozoneId  
    WHILE @@FETCH_STATUS = 0                                  
    BEGIN                                      
     --DECLARE @SchoolGeozone int = (select scm.GeozoneId from rvlfStudentVehicleAssignment SA inner join rvlfStudentMaster SM               
     --on SA.StudentMasterId=SM.StudentMasterID inner join rvlfSchoolMaster SCM on SM.SchoolID=SCM.SchoolID        
     --where VehicleId=@vehicleID group by SCM.SchoolID,scm.GeozoneId )          
      DECLARE @SchoolGeozone NVARCHAR(MAX) = (SELECT STUFF((SELECT distinct ',' +  cast(scm.GeozoneId as varchar) FROM        rvlfStudentVehicleAssignment SA inner join rvlfStudentMaster SM on SA.StudentMasterId=SM.StudentMasterID                
  inner join rvlfSchoolMaster SCM on SM.SchoolID=SCM.SchoolID where VehicleId=@vehicleID                 
  group by SCM.SchoolID,scm.GeozoneId FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,1,'') SchoolGeozone)                
    -- select 'Cursor',@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID ,@SchoolGeozone  
   IF(@BoxMsgInID = 5 and cast(@GeozoneID as varchar)in (select * from rvlf_fn_ConvertArrayToTable(@SchoolGeozone,',')))                         BEGIN                                         
    IF Exists(select * from @T2 where BoxId = @BoxID and vehicleId = @vehicleID and OrgId =@OrgID and Stat is null)        
     BEGIN                
      --IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID  
      --  where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)                           
      --BEGIN                                
      --  Insert into @T2(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)  
      --  VALUES                                  
      --  (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)  
  --END              
      update @T2 set Stat = 1, EntryTime=@Origindatetime,GeozoneId=@GeozoneID where Boxid = @BoxID and OrgId = OrgId and Stat is null  
      and SchoolGeozoneId=@GeozoneID                 
     END                                         
    --ELSE                                         
    -- BEGIN                                        
    --  IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID          
    --    where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)        
        --   begin                                                
    --    Insert into @T2(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)            
    --    VALUES                                  
    --    (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)                  
    --   end                                  
    --  END                                                 
   END                                                 
   ELSE                                              
    BEGIN                     
     IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID  
       where S.OrganizationID = @OrgID and StudentMasterID= @StudentID)-- and s.GeozoneId = @GeozoneID)                 
      begin                                             
        Insert into @T2(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID,SchoolGeozoneId)  
        VALUES                                  
        (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID,@SchoolGeozoneId)                 
      end                           
    END                               
  IF(@BoxMsgInID = 114 and cast(@GeozoneID as varchar) in (select * from rvlf_fn_ConvertArrayToTable(@SchoolGeozone,',')))  
   BEGIN                                              
      Declare @Datetime datetime =(select top 1 OriginDateTime from rvlfMsgInHst where BoxId=@BoxID and BoxMsgInTypeId in (5) and     OriginDateTime<@Origindatetime and dbo.rvlf_fn_GetParamValueWithIndex(customprop,'GeozoneID=',';')=@GeozoneID            
 
      
  order by OriginDateTime desc)                  
    IF(@Origindatetime >=  (select DATEADD(minute, 0, @Datetime)))                                               
     Begin                                 
      IF Exists(select * from @ReturnTrip where BoxId = @BoxID and vehicleId = @vehicleID and OrgId =@OrgID and Stat is null)                       BEGIN                                             
   --     IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on   S.SchoolID = SM.SchoolID                 
   --      where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)                                    
   --      BEGIN                        
   --Insert into @ReturnTrip(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)                 
   --VALUES(@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)        
   --      END                        
        Update @ReturnTrip set Stat = 2, ExitTime=@Origindatetime,GeozoneId=@GeozoneID where Boxid = @BoxID and OrgId = OrgId  and   
        Stat is null and MessageInID not in (select MessageInID from @T2 where EntryTime is not null) and SchoolGeozoneId=@GeozoneID   
       END                                           
  --  ELSE                                          
  --BEGIN                                      
  --      IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID            
  --      where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)                                   
  --      Insert into @ReturnTrip(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)   
  --      VALUES                                  
  --      (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)                 
  --END                                                 
     END                           
    END                        
    ELSE                
    BEGIN                          
     IF(@Origindatetime >=  (select DATEADD(minute, 0, @Datetime)))                           
     begin                                    
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID  
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID)-- and s.GeozoneId = @GeozoneID)          
        Insert into @ReturnTrip(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID,SchoolGeozoneId)  
         VALUES (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID,@SchoolGeozoneId)         
     end                        
    END                                  
    -- select 'OUT'                                                          
    FETCH NEXT FROM cursorName                                  
    INTO @ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID,@SchoolGeozoneId  
  END                                                  
CLOSE cursorName -- close the cursor                                  
DEALLOCATE cursorName -- Dealloc                                  
                                  
--select * from @T2                 
--select * from @ReturnTrip                                  
                                  
  INSERT INTO rvlf_StudentRFIDSMSMessegeInIDLog(StudentID,BoxiD,VehicleID,GeozoneId,OrganizationID,StatusType,EntryExit,RFID,MessageInID)                              
Select distinct StudentId,BoxId,vehicleId,GeozoneId,OrgId,Stat,EntryTime as 'Enty/Exit',RFID,MessageInID from @T2 where StudentId IS NOT NULL and Stat = 1                                  
UNION ALL                                  
Select distinct StudentId,BoxId,vehicleId,GeozoneId,OrgId,Stat,ExitTime,RFID,MessageInID from @ReturnTrip where StudentId IS NOT NULL and Stat = 2                                  
--select 'log',* from rvlf_StudentRFIDSMSMessegeInIDLog                                  
                                  
declare @SMSTbl as Table                                  
(ID INT, StudentID varchar(20),BoxiD BIGINT,VehicleID INT ,GeozoneId INT,OrgId INT,StatusType INT,EntryExit DATETIME,RFID NVARCHAR(50),MessageInID nvarchar(100))                                  
                                  
INSERT INTO @SMSTbl(StudentID,BoxiD,VehicleID,GeozoneId,OrgId,StatusType,EntryExit,RFID)                                  
                                  
Select distinct StudentId,BoxId,vehicleId,GeozoneId,OrgId,Stat,EntryTime as 'Enty/Exit',RFID from @T2 where StudentId IS NOT NULL and Stat = 1                              
UNION ALL                                  
Select distinct StudentId,BoxId,vehicleId,GeozoneId,OrgId,Stat,ExitTime,RFID from @ReturnTrip where StudentId IS NOT NULL and Stat = 2                       
                 
--select * from @SMSTbl                                  
                 
--select S.*,SM.ContactNo,SM.StudentFirstName + + SM.StudentLastName as Name,                                  
--CASE WHEN StatusType =1 THEN ('Dear Parent,\n' + 'Name : '+ SM.StudentFirstName + + SM.StudentLastName + '\n Info:Reached School at : '+ CAST(EntryExit as varchar(20)) +'\n -Trinetra' )                                      
--WHEN StatusType =2 THEN ('Dear Parents,\n' + 'Name : '+ SM.StudentFirstName + + SM.StudentLastName + '\n Info:Started from School at : '+ CAST(EntryExit as varchar(20)) +'\n -Trinetra') end as MessageType               
--from @SMSTbl S inner join rvlfStudentMaster SM on S.StudentID = SM.StudentMasterID                                   
        
--CONVERT(VARCHAR,CAST(DATEADD(n,TZ.MinToBeAdded,DATEADD(hh,TZ.HoursToBeAdded,DATEADD(SECOND,B.Totval,@dtOriginDateTime)))AS TIME),22)                         
  Insert into rvlfRFIDSchoolSMSNotification(StudentID,VehicleID,BoxID,GeozoneID,OrganizationId ,EntryExitTime ,RFID ,StudentName,ContactNo ,  MessageTemplate,MsgType, IsSMSSent)                                 
  
select S.StudentID,S.VehicleID,S.BoxiD,S.GeozoneId,S.OrgId,S.EntryExit,S.RFID,SM.StudentFirstName + + SM.StudentLastName,        
SM.ContactNo,CASE WHEN StatusType =1 THEN ('Dear Parent, \n ' + 'Name: '+ SM.StudentFirstName + + isnull(SM.StudentLastName,'') + ' \n Info: Your child has reached school at '+ CAST((dbo.rvlf_fn_DayLightSavings_Date(EntryExit,O.OrganizationID,        
TZ.HoursToBeAdded,TZ.MinToBeAdded,EntryExit)) as varchar(20))+' \n -Trinetra')          
WHEN StatusType =2 THEN ('Dear Parent, \n ' + 'Name: '+ SM.StudentFirstName + + isnull(SM.StudentLastName,'') + ' \n  Info: Your child has started from school at '+   
CAST((dbo.rvlf_fn_DayLightSavings_Date(EntryExit,O.OrganizationID,TZ.HoursToBeAdded,TZ.MinToBeAdded,EntryExit))    
as varchar(20))+' \n -Trinetra') end as MessageType,StatusType,0         
from @SMSTbl S inner join rvlfStudentMaster SM on S.StudentID = SM.StudentMasterID        
inner join rvlfOrganization O on O.OrganizationId = S.OrgId        
inner join rvlfTimeZones TZ on TZ.TimeZoneID = O.CountryId        
where (S.StatusType=SM.SMSSettings or SM.SMSSettings=3)        
         

-- SMS Head count Notification to Reporting Person  
  
if exists (select * from rvlfBoxId b inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId                            
   inner join rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1                            
   inner join rvlfPackageOperations po on op.PackageId=po.PackageId                            
   inner join rvlfOperationType ot on po.OperationID=ot.OperationTypeId                  
   where b.BoxId=@intBoxID and CHARINDEX('Head count Notification',ot.OperationTypeName,1)>0 and o.ExpiresOn > GETUTCDATE())                
Begin    
	 INSERT INTO rvlfRFIDSchoolSMSNotification(VehicleID,StudentID,BoxID,GeozoneID,OrganizationId,  
												EntryExitTime,ContactNo,MessageTemplate,MsgType,IsSMSSent,HeadCount)      
	            
	 SELECT DISTINCT (S.VehicleID), U.userid, S.BoxiD, S.GeozoneId, S.OrgId, S.EntryExit, U.MobileNo,      
			CASE	WHEN StatusType =1 THEN ('Dear ' + U.Firstname + (CASE WHEN U.LastName IS NULL THEN ', ' WHEN U.LastName='' THEN ', ' ELSE ' ' + U.LastName + ', ' END) +    
					'\n Name: '+ V.VehicleDescription + ' \n  Info: Vehicle has reached ' + SCM.SchoolName + ' at '+       
					CAST((dbo.rvlf_fn_DayLightSavings_Date(EntryExit,O.OrganizationID, TZ.HoursToBeAdded,TZ.MinToBeAdded,EntryExit)) as varchar(20))       
					+ ' with ' + CAST((SELECT COUNT(StudentID) FROM @SMSTbl) as varchar(5)) + ' students' +' \n -Trinetra')      
					WHEN StatusType =2 THEN ('Dear ' + U.Firstname + (CASE WHEN U.LastName IS NULL THEN ', ' WHEN U.LastName='' THEN ', ' ELSE ' ' + U.LastName + ', ' END) +    
					'\n Name: '+ V.VehicleDescription + ' \n  Info: Vehicle has started from ' + SCM.SchoolName + ' at '+       
					CAST((dbo.rvlf_fn_DayLightSavings_Date(EntryExit,O.OrganizationID,TZ.HoursToBeAdded,TZ.MinToBeAdded,EntryExit)) as varchar(20))       
					+ ' with ' + CAST((SELECT COUNT(StudentID) FROM @SMSTbl) as varchar(5)) + ' students' + ' \n -Trinetra') end as MessageTemplate, 7, 0,
					(SELECT COUNT(StudentID) FROM @SMSTbl)      
	 FROM @SMSTbl S       
	 INNER JOIN rvlfStudentMaster SM ON S.StudentID = SM.StudentMasterID      
	 INNER JOIN rvlfOrganization O ON O.OrganizationId = S.OrgId      
	 INNER JOIN rvlfTimeZones TZ ON TZ.TimeZoneID = O.CountryId      
	 INNER JOIN rvlfSchoolMaster SCM ON SM.SchoolID = SCM.SchoolID      
	 INNER JOIN rvlfUser U ON SCM.ReportingPerson = U.UserId      
	 INNER JOIN rvlfVehicle V ON S.VehicleID = V.VehicleId      
	 --WHERE (S.StatusType=SM.SMSSettings or SM.SMSSettings=3)      
End  
         
--select Sno,VehicleID,GeozoneID,OrganizationId,MessageTemplate from rvlfRFIDSchoolSMSNotification where IsSMSSent = 0          
--select Sno,StudentID,VehicleID,BoxID,GeozoneID,OrganizationId,EntryExit from rvlfRFIDSchoolSMSNotification where IsSMSSent = 0  
--select * from rvlfStudentMaster where StudentMasterID in(1,2)                                          
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetandUpdateRFIDStudentSMSTrigger_oldmar15]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetandUpdateRFIDStudentSMSTrigger_oldmar15]        
AS                    
/******************************************************************************/                    
-- Name  : [rvlf_sp_GetandUpdateRFIDStudentSMSTrigger]                    
-- Description : To get the vehicle expired details based on the current date                    
-- Author  : K.Kapilraj                    
-- Company  : Angler Technologies                    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                    
--    : 26-Sep-2014 VN Created initial version                      
--    : 19-Feb-Sep-2014 VN Created initial version                      
/******************************************************************************/                    
BEGIN                
                
Declare @T1 as table                
(ID  int identity (1,1) NOT NULL,                
Counts int,                
BoxId INT,                
VehicleId INT,        
RFID varchar(250),                
GeozoneId int,                
BoxMsgInTypeId int,                
Origindatetime datetime,                
StudentId BIGINT,                
OrgId int,                
MessageInID nvarchar(150),            
DriverId bigint,SchoolGeozoneId int,        
OrganizationID bigint        
)                
                
Insert into @T1                
                
select COUNT(H.BoxId),H.BoxId,V.VehicleId,                
dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';') as RFID ,                
dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'GeozoneID=',';') as GeozoneID,                
h.BoxMsgInTypeId,                
H.OriginDateTime,                
M.StudentMasterID,                
B.organizationID,                
H.MessageInID,            
bm.DriverId,        
SCM.GeozoneId ,b.OrganizationId        
--M.StudentFirstName +  + M.StudentLastName,                
--M.ContactNo                
from rvlfMsgInHst H                 
INNER JOIN rvlfboxid B on B.BoxId = H.BoxId                 
INNER JOIN rvlfVehicleAssignment VA on VA.BoxId = H.BoxId                
INNER JOIN rvlfStudentVehicleAssignment SA on SA.VehicleId = VA.VehicleId                
--INNER JOIN rvlfStudentMaster SM on SM.StudentMasterID = SA.StudentMasterId 2014-09-24 07:19:30.000                
LEFT OUTER JOIN rvlfStudentMaster M on M.RFID = dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';')            
left join rvlfSchoolMaster SCM on M.SchoolID=SCM.SchoolID        
INNER JOIN rvlfVehicle V on VA.VehicleId = V.VehicleId                
left join rvlfIButtonMapping bm on bm.IButtonKey = dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';')             
left join rvlfDriverAssignment da on bm.BoxID=da.BoxId              
left join rvlf_StudentRFIDSMSMessegeInIDLog SL on H.MessageInID=SL.MessageInID            
where CONVERT(DATE,OriginDateTime) = CONVERT(date,GETUTCDATE())    and SL.MessageInID is null            
--where OriginDateTime between dateadd(MINUTE,-330,'2015-02-12 04:37:22 PM') and         
--dateadd(MINUTE,-330,'2015-02-12 05:28:00 PM')   and SL.MessageInID is null        
--AND h.BoxId = 999983        
AND (H.BoxMsgintypeid = 5 OR H.BoxMsgintypeid = 6  or H.BoxMsgInTypeId = 100 or       
(H.BoxMsgInTypeId=114 and CustomProp like '%GeozoneInOutWithDuration%'))                
GROUP BY  V.VehicleDescription,H.BoxId,CustomProp,h.OriginDateTime,h.BoxMsgInTypeId,V.VehicleId,B.OrganizationId ,M.StudentMasterID               
,B.organizationID,H.MessageInID ,bm.DriverId ,SCM.GeozoneId        
ORDER BY h.OriginDateTime                
      
select * from @T1             
                
--update X set X.GeozoneId = C.GeozoneId  from @T1 X INNER JOIN                 
--(select GeozoneId,Boxid from @T1 WHERE GeozoneId IS NOT NULL GROUP BY Boxid,GeozoneId)                
--as C on C.Boxid = X.Boxid                
update X set X.GeozoneId = C.GeozoneId  from @T1 X INNER JOIN             
 (select a.GeozoneId,Boxid from @T1 as a inner join rvlfSchoolMaster SM on a.geozoneid=SM.GeozoneId and a.OrganizationID=SM.OrganizationID        
    WHERE a.GeozoneId IS NOT NULL --and SM.OrganizationID=6        
    GROUP BY Boxid,a.GeozoneId)        
as C on C.Boxid = X.Boxid  and X.GeozoneId is null        
                
DECLARE @T2 as table                
(ID int,                
RFID varchar(100),                
Boxid int,                
vehicleId int,                
GeozoneId int,                
StudentId int,                
OrgId int,                
BoxMsgInTypeId int,                
Origindatetime datetime,                
Stat int,                
MessageInID nvarchar(150),                
EntryTime datetime                
)                
                
DECLARE @ReturnTrip as table                
(ID int,                
RFID varchar(100),                
Boxid int,                
vehicleId int,                
GeozoneId int,                
StudentId int,                
OrgId int,                
BoxMsgInTypeId int,                
Origindatetime datetime,                
Stat int,                
MessageInID nvarchar(150),                
ExitTime datetime                
)                
                
--Insert into @T2                
                
--select DISTINCT RFID,Boxid,vehicleID,GeozoneId,studentid,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID from @T1 ORDER BY OriginDateTime-- where StudentId IS NOT NULL                
--union all                
--select  DISTINCT RFID,'999987',33,2,studentid,1,BoxMsgInTypeId,Origindatetime from @T1 ORDER BY OriginDateTime-- where StudentId IS NOT NULL                
                
--select * from @T2                
                
DECLARE @ID INT, @RFID varchar(50),@BoxID INT,@vehicleID INT,@GeozoneID INT,@StudentID INT,@OrgID INT, @BoxMsgInID INT, @Origindatetime DATETIME,@MessageInID NVARCHAR(maX)                
DECLARE cursorName CURSOR                 
   FOR                 
     select ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID from @T1                     
     OPEN cursorName                          
    FETCH NEXT FROM cursorName                 
    INTO @ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID                
    WHILE @@FETCH_STATUS = 0                
    BEGIN                    
     DECLARE @SchoolGeozone int = (select scm.GeozoneId from rvlfStudentVehicleAssignment SA inner join rvlfStudentMaster SM         
     on SA.StudentMasterId=SM.StudentMasterID inner join rvlfSchoolMaster SCM on SM.SchoolID=SCM.SchoolID         
     where VehicleId=@vehicleID group by SCM.SchoolID,scm.GeozoneId )       
     select 'Cursor',@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID ,@SchoolGeozone        
    IF(@BoxMsgInID = 5 and @GeozoneID=@SchoolGeozone)            
    BEGIN                              
    IF Exists(select * from @T2 where BoxId = @BoxID and vehicleId = @vehicleID and OrgId =@OrgID and Stat is null)                 
       BEGIN                           
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID                          
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)         
        BEGIN                          
        Insert into @T2(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)                
        VALUES                
        (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)                    
        END        
         update @T2 set Stat = 1, EntryTime=@Origindatetime  where Boxid = @BoxID and OrgId = OrgId and Stat is null                     
       END                       
       ELSE                       
       BEGIN                       
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID                      
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)                                  
        Insert into @T2(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)                
        VALUES                
        (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)                
       END                               
    END                               
    ELSE                            
    BEGIN             
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID                        
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)                          
        Insert into @T2(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)                
        VALUES                
        (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)                
                        
   --Insert into @ReturnTrip(RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)                
        --VALUES                
        --(@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)                
                    
    END             
    IF(@BoxMsgInID = 114 and @GeozoneID=@SchoolGeozone)        
    BEGIN                          
    Declare @timeHrs int                            
      declare @Datetime datetime =(select top 1 OriginDateTime from rvlfMsgInHst where BoxId=@BoxID and BoxMsgInTypeId in (5) and   OriginDateTime<@Origindatetime and dbo.rvlf_fn_GetParamValueWithIndex(customprop,'GeozoneID=',';')=43 order by OriginDateTime desc)         
    set  @timeHrs = (select ISNULL(WaitingTime,0) from rvlfSchoolMaster S                     
    where S.OrganizationID = @OrgID  and GeozoneId = @GeozoneID)                  
                    
    IF(@Origindatetime >=  (select DATEADD(minute, 0, @Datetime)))                
    --select 'IN'                
     begin               
    IF Exists(select * from @ReturnTrip where BoxId = @BoxID and vehicleId = @vehicleID and OrgId =@OrgID and Stat is null)                 
    BEGIN                           
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on   S.SchoolID = SM.SchoolID                          
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)                  
        BEGIN      
   Insert into @ReturnTrip(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)                
   VALUES(@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)         
        END      
         Update @ReturnTrip set Stat = 2, ExitTime=@Origindatetime where Boxid = @BoxID and OrgId = OrgId  and Stat is null                
         and MessageInID not in (select MessageInID from @T2 where EntryTime is not null)        
    END                         
    ELSE                        
 BEGIN                       
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID                      
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)                         
        Insert into @ReturnTrip(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)                
        VALUES                
        (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)                                
    END                               
    END         
    END      
    ELSE                
   -- select 'ELSE'     
    BEGIN        
     IF(@Origindatetime >=  (select DATEADD(minute, 0, @Datetime)))         
     begin                   
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID                        
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)                        
        Insert into @ReturnTrip(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)                
        VALUES                
        (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)                            
     end      
    END                
    -- select 'OUT'                                        
    FETCH NEXT FROM cursorName                
    INTO @ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID                     
  END                              
                                
CLOSE cursorName -- close the cursor                
DEALLOCATE cursorName -- Dealloc                
                
--select * from @T2                
--select MessageInID from @T2 where Stat is null                
--select * from @ReturnTrip                
--select 'R',* from @ReturnTrip where MessageInID  IN(select MessageInID from @T2 where Stat is null)                
                
INSERT INTO rvlf_StudentRFIDSMSMessegeInIDLog(StudentID,BoxiD,VehicleID,GeozoneId,OrganizationID,StatusType,EntryExit,RFID,MessageInID)            
Select distinct StudentId,BoxId,vehicleId,GeozoneId,OrgId,Stat,EntryTime as 'Enty/Exit',RFID,MessageInID from @T2 where StudentId IS NOT NULL and Stat = 1                
UNION ALL                
Select distinct StudentId,BoxId,vehicleId,GeozoneId,OrgId,Stat,ExitTime,RFID,MessageInID from @ReturnTrip where StudentId IS NOT NULL and Stat = 2                
--select 'log',* from rvlf_StudentRFIDSMSMessegeInIDLog                
                
declare @SMSTbl as Table                
(ID INT, StudentID varchar(20),BoxiD BIGINT,VehicleID INT ,GeozoneId INT,OrgId INT,StatusType INT,EntryExit DATETIME,RFID NVARCHAR(50),MessageInID nvarchar(100))                
                
INSERT INTO @SMSTbl(StudentID,BoxiD,VehicleID,GeozoneId,OrgId,StatusType,EntryExit,RFID)                
                
Select distinct StudentId,BoxId,vehicleId,GeozoneId,OrgId,Stat,EntryTime as 'Enty/Exit',RFID from @T2 where StudentId IS NOT NULL and Stat = 1                
UNION ALL                
Select distinct StudentId,BoxId,vehicleId,GeozoneId,OrgId,Stat,ExitTime,RFID from @ReturnTrip where StudentId IS NOT NULL and Stat = 2                
           
select * from @SMSTbl                
                
select S.*,SM.ContactNo,SM.StudentFirstName + + SM.StudentLastName as Name,                
CASE WHEN StatusType =1 THEN ('Dear Parents,\n' + 'Name : '+ SM.StudentFirstName + + SM.StudentLastName + '\n Info:Reached School at : '+ CAST(EntryExit as varchar(20)) +'-Trinetra' )                    
WHEN StatusType =2 THEN ('Dear Parents,\n' + 'Name : '+ SM.StudentFirstName + + SM.StudentLastName + '\n Info:Started from School at : '+ CAST(EntryExit as varchar(20)) +'-Trinetra') end as MessageType                     
from @SMSTbl S inner join rvlfStudentMaster SM on S.StudentID = SM.StudentMasterID                 
                
Insert into rvlfRFIDSchoolSMSNotification(StudentID,VehicleID,BoxID,GeozoneID,OrganizationId ,EntryExitTime ,RFID ,StudentName,ContactNo ,  MessageTemplate,MsgType, IsSMSSent)               
              
select S.StudentID,S.VehicleID,S.BoxiD,S.GeozoneId,S.OrgId,S.EntryExit,S.RFID,SM.StudentFirstName + + SM.StudentLastName,            
 SM.ContactNo,        CASE WHEN StatusType =1 THEN ('Dear Parents,\n' + 'Name : '+ SM.StudentFirstName + + SM.StudentLastName + '\n Info: Reached School at : '+ CAST((dbo.rvlf_fn_DayLightSavings_Date(EntryExit,O.OrganizationID,            
 TZ.HoursToBeAdded,TZ.MinToBeAdded,EntryExit))               
 as varchar(20))+'-Trinetra')              
WHEN StatusType =2 THEN ('Dear Parents,\n' + 'Name : '+ SM.StudentFirstName + + SM.StudentLastName + '\n Info: Started from School at : '+ CAST((dbo.rvlf_fn_DayLightSavings_Date(EntryExit,O.OrganizationID,TZ.HoursToBeAdded,TZ.MinToBeAdded,EntryExit) )   
           
 as varchar(20))+'-Trinetra') end as MessageType,                    
StatusType,0              
from @SMSTbl S inner join rvlfStudentMaster SM on S.StudentID = SM.StudentMasterID                    
inner join rvlfOrganization O on O.OrganizationId = S.OrgId                     
inner join rvlfTimeZones TZ on TZ.TimeZoneID = O.CountryId                 
where (S.StatusType=SM.SMSSettings or SM.SMSSettings=3)              
              
--select Sno,VehicleID,GeozoneID,OrganizationId,MessageTemplate from rvlfRFIDSchoolSMSNotification where IsSMSSent = 0              
--select Sno,StudentID,VehicleID,BoxID,GeozoneID,OrganizationId,EntryExit from rvlfRFIDSchoolSMSNotification where IsSMSSent = 0              
--select * from rvlfStudentMaster where StudentMasterID in(1,2)                        
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetandUpdateRFIDStudentSMSTrigger-Kapil_bkp]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
      
CREATE Procedure [dbo].[rvlf_sp_GetandUpdateRFIDStudentSMSTrigger-Kapil_bkp]             
AS            
/******************************************************************************/            
-- Name  : [rvlf_sp_GetandUpdateRFIDStudentSMSTrigger]            
-- Description : To get the vehicle expired details based on the current date            
-- Author  : K.Kapilraj            
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--    : 26-Sep-2014 VN Created initial version              
/******************************************************************************/            
BEGIN        
        
Declare @T1 as table        
(ID  int identity (1,1) NOT NULL,        
Counts int,        
BoxId INT,        
VehicleId INT,        
RFID varchar(250),        
GeozoneId int,        
BoxMsgInTypeId int,        
Origindatetime datetime,        
StudentId BIGINT,        
OrgId int,        
MessageInID nvarchar(150)        
)        
        
        
Insert into @T1        
select COUNT(H.BoxId),H.BoxId,V.VehicleId,        
dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';') as RFID ,        
dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'GeozoneID=',';') as GeozoneID,        
h.BoxMsgInTypeId,        
H.OriginDateTime,        
M.StudentMasterID,        
B.organizationID,        
H.MessageInID        
--M.StudentFirstName +  + M.StudentLastName,        
--M.ContactNo        
from rvlfMsgInHst H         
INNER JOIN rvlfboxid B on B.BoxId = H.BoxId         
INNER JOIN rvlfVehicleAssignment VA on VA.BoxId = H.BoxId        
INNER JOIN rvlfStudentVehicleAssignment SA on SA.VehicleId = VA.VehicleId        
--INNER JOIN rvlfStudentMaster SM on SM.StudentMasterID = SA.StudentMasterId 2014-09-24 07:19:30.000        
LEFT OUTER JOIN rvlfStudentMaster M on M.RFID = dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';')        
INNER JOIN rvlfVehicle V on VA.VehicleId = V.VehicleId        
where CONVERT(DATE,OriginDateTime) = CONVERT(date,GETUTCDATE())        
--AND h.BoxId = 999986        
and H.BoxMsgInTypeId IN(100) or (H.BoxMsgInTypeId=114 and H.CustomProp like '%GeozoneInOutWithDuration:%')        
AND (H.BoxMsgintypeid = 5 OR H.BoxMsgintypeid = 6  or H.BoxMsgInTypeId = 100 or H.BoxMsgInTypeId=114)         
AND H.MessageInID NOT IN(select MessageInID from rvlf_StudentRFIDSMSMessegeInIDLog)        
--AND M.StudentMasterID IS NOT NULL        
--and RFID is not null        
GROUP BY  V.VehicleDescription,H.BoxId,CustomProp,h.OriginDateTime,h.BoxMsgInTypeId,V.VehicleId,B.OrganizationId ,M.StudentMasterID         
,B.organizationID,H.MessageInID        
ORDER BY h.OriginDateTime        
select * from @T1        
        
update X set X.GeozoneId = C.GeozoneId  from @T1 X INNER JOIN         
(select GeozoneId,Boxid from @T1 WHERE GeozoneId IS NOT NULL GROUP BY Boxid,GeozoneId)        
as C on C.Boxid = X.Boxid        
        
DECLARE @T2 as table        
(ID int,        
RFID varchar(100),        
Boxid int,        
vehicleId int,        
GeozoneId int,        
StudentId int,        
OrgId int,        
BoxMsgInTypeId int,        
Origindatetime datetime,        
Stat int,        
MessageInID nvarchar(150),        
EntryTime datetime        
)        
        
DECLARE @ReturnTrip as table        
(ID int,        
RFID varchar(100),        
Boxid int,        
vehicleId int,        
GeozoneId int,        
StudentId int,        
OrgId int,        
BoxMsgInTypeId int,        
Origindatetime datetime,        
Stat int,        
MessageInID nvarchar(150),        
ExitTime datetime        
)        
        
--Insert into @T2        
        
--select DISTINCT RFID,Boxid,vehicleID,GeozoneId,studentid,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID from @T1 ORDER BY OriginDateTime-- where StudentId IS NOT NULL        
--union all        
--select  DISTINCT RFID,'999987',33,2,studentid,1,BoxMsgInTypeId,Origindatetime from @T1 ORDER BY OriginDateTime-- where StudentId IS NOT NULL        
        
--select * from @T2        
        
DECLARE @ID INT, @RFID varchar(50),@BoxID INT,@vehicleID INT,@GeozoneID INT,@StudentID INT,@OrgID INT, @BoxMsgInID INT, @Origindatetime DATETIME,@MessageInID NVARCHAR(maX)        
DECLARE cursorName CURSOR         
   FOR         
     select ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID from @T1 where GeozoneId is not null            
     OPEN cursorName                  
    FETCH NEXT FROM cursorName         
    INTO @ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID        
    WHILE @@FETCH_STATUS = 0        
    BEGIN            
    --DECLARE             
            
    IF(@BoxMsgInID = 5)          
    BEGIN                      
    IF Exists(select * from @T2 where BoxId = @BoxID and vehicleId = @vehicleID and OrgId =@OrgID and Stat is null)         
       BEGIN                   
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID                  
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)                   
        Insert into @T2(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)        
        VALUES        
        (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)            
         update @T2 set Stat = 1, EntryTime=@Origindatetime  where Boxid = @BoxID and OrgId = OrgId and Stat is null             
       END             
               
       ELSE        
               
       BEGIN        
               
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID              
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)          
                
        Insert into @T2(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)        
        VALUES        
        (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)        
       END        
               
    END            
            
    ELSE        
            
    BEGIN             
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID                
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)                  
        Insert into @T2(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)        
        VALUES        
        (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)        
                
        --Insert into @ReturnTrip(RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)        
        --VALUES        
        --(@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)        
            
    END        
            
    IF(@BoxMsgInID = 114)           
             
    BEGIN        
                 
    Declare @timeHrs int        
    set  @timeHrs = (select ISNULL(WaitingTime,0) from rvlfSchoolMaster S                 
    where S.OrganizationID = @OrgID  and GeozoneId = @GeozoneID)        
            
    --select WaitingTime from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolMID = SM.SchoolCode                  
    --where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and GeozoneId = @GeozoneID        
            
   -- select @timeHrs        
   -- select @Origindatetime        
            
    IF(@Origindatetime >=  (select DATEADD(minute, -@timeHrs, @Origindatetime)))        
    --select 'IN'        
            
    IF Exists(select * from @ReturnTrip where BoxId = @BoxID and vehicleId = @vehicleID and OrgId =@OrgID and Stat is null)         
       BEGIN                   
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on   S.SchoolID = SM.SchoolID                  
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)          
                                
        Insert into @ReturnTrip(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)        
   VALUES        
        (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)                            
         update @ReturnTrip set Stat = 2, ExitTime=@Origindatetime where Boxid = @BoxID and OrgId = OrgId  and Stat is null        
       END             
               
       ELSE        
               
       BEGIN        
        
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID              
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)                 
        Insert into @ReturnTrip(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)        
        VALUES        
        (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)        
                
       END        
               
    END            
            
    ELSE        
   -- select 'ELSE'        
    BEGIN             
        IF EXISTS(select * from rvlfSchoolMaster S INNER JOIN rvlfStudentMaster SM on  S.SchoolID = SM.SchoolID                
        where S.OrganizationID = @OrgID and StudentMasterID= @StudentID and s.GeozoneId = @GeozoneID)                  
        --Insert into @ReturnTrip(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime)        
        --VALUES        
        --(@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime)        
                
        Insert into @ReturnTrip(ID,RFID,BoxId,vehicleId,GeozoneId,StudentId,OrgId,BoxMsgInTypeId,Origindatetime,MessageInID)        
        VALUES        
        (@ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID)        
            
    END          
    -- select 'OUT'        
                      
    FETCH NEXT FROM cursorName        
    INTO @ID,@RFID,@BoxID,@vehicleID,@GeozoneID,@StudentID,@OrgID,@BoxMsgInID,@Origindatetime,@MessageInID             
                END                       
                        
    CLOSE cursorName -- close the cursor        
DEALLOCATE cursorName -- Dealloc        
        
--select * from @T2        
--select MessageInID from @T2 where Stat is null        
--select * from @ReturnTrip        
--select 'R',* from @ReturnTrip where MessageInID  IN(select MessageInID from @T2 where Stat is null)        
        
INSERT INTO rvlf_StudentRFIDSMSMessegeInIDLog(StudentID,BoxiD,VehicleID,GeozoneId,OrganizationID,StatusType,EntryExit,RFID,MessageInID)        
        
Select distinct StudentId,BoxId,vehicleId,GeozoneId,OrgId,Stat,EntryTime as 'Enty/Exit',RFID,MessageInID from @T2 where StudentId IS NOT NULL and Stat = 1        
UNION ALL        
Select distinct StudentId,BoxId,vehicleId,GeozoneId,OrgId,Stat,ExitTime,RFID,MessageInID from @ReturnTrip where StudentId IS NOT NULL and Stat = 2        
--select 'log',* from rvlf_StudentRFIDSMSMessegeInIDLog        
        
declare @SMSTbl as Table        
(ID INT, StudentID varchar(20),BoxiD BIGINT,VehicleID INT ,GeozoneId INT,OrgId INT,StatusType INT,EntryExit DATETIME,RFID NVARCHAR(50),MessageInID nvarchar(100))        
        
INSERT INTO @SMSTbl(StudentID,BoxiD,VehicleID,GeozoneId,OrgId,StatusType,EntryExit,RFID)        
        
Select distinct StudentId,BoxId,vehicleId,GeozoneId,OrgId,Stat,EntryTime as 'Enty/Exit',RFID from @T2 where StudentId IS NOT NULL and Stat = 1        
UNION ALL        
Select distinct StudentId,BoxId,vehicleId,GeozoneId,OrgId,Stat,ExitTime,RFID from @ReturnTrip where StudentId IS NOT NULL and Stat = 2        
        
--select * from @SMSTbl        
        
select S.*,SM.ContactNo,SM.StudentFirstName + + SM.StudentLastName as Name,        
CASE WHEN StatusType =1 THEN ('Your Children\n' + 'Name : '+ SM.StudentFirstName + + SM.StudentLastName + '\nReached School at : '+ CAST(EntryExit as varchar(20)))            
WHEN StatusType =2 THEN ('Your Children\n' + 'Name : '+ SM.StudentFirstName + + SM.StudentLastName + '\nStarted from School at : '+ CAST(EntryExit as varchar(20))) end as MessageType,             
TZ.HoursToBeAdded,TZ.MinToBeAdded,        
dbo.rvlf_fn_DayLightSavings_Date(EntryExit,O.OrganizationID,TZ.HoursToBeAdded,TZ.MinToBeAdded,EntryExit)        
from @SMSTbl S inner join rvlfStudentMaster SM on S.StudentID = SM.StudentMasterID         
inner join rvlfOrganization O on O.OrganizationId = S.OrgId         
inner join rvlfTimeZones TZ on TZ.TimeZoneID = O.CountryId         
        
select S.StudentID,S.VehicleID,S.BoxiD,S.GeozoneId,S.OrgId,S.EntryExit,S.RFID,SM.StudentFirstName + + SM.StudentLastName,     SM.ContactNo,        
CASE WHEN StatusType =1 THEN ('Your Children\n' + 'Name : '+ SM.StudentFirstName + + SM.StudentLastName + '\nReached School at : '+ CAST((dbo.rvlf_fn_DayLightSavings_Date(EntryExit,O.OrganizationID,TZ.HoursToBeAdded,TZ.MinToBeAdded,EntryExit)) as varchar
(  
    
      
20)))            
WHEN StatusType =2 THEN ('Your Children\n' + 'Name : '+ SM.StudentFirstName + + SM.StudentLastName + '\nStarted from School at : '+ CAST((dbo.rvlf_fn_DayLightSavings_Date(EntryExit,O.OrganizationID,TZ.HoursToBeAdded,TZ.MinToBeAdded,EntryExit) ) as varchar
  
    
      
(20))) end as MessageType,        
StatusType,0            
from @SMSTbl S inner join rvlfStudentMaster SM on S.StudentID = SM.StudentMasterID        
inner join rvlfOrganization O on O.OrganizationId = S.OrgId         
inner join rvlfTimeZones TZ on TZ.TimeZoneID = O.CountryId         
        
insert into rvlfRFIDSchoolSMSNotification(StudentID,VehicleID,BoxID,GeozoneID,OrganizationId ,EntryExitTime ,RFID ,StudentName,ContactNo ,        
MessageTemplate,MsgType, IsSMSSent)        
        
select S.StudentID,S.VehicleID,S.BoxiD,S.GeozoneId,S.OrgId,S.EntryExit,S.RFID,SM.StudentFirstName + + SM.StudentLastName,        
 SM.ContactNo,        
CASE WHEN StatusType =1 THEN ('Msg:Your Children\n' + 'Name : '+ SM.StudentFirstName + + SM.StudentLastName + '\n Info: Reached School at : '+ CAST((dbo.rvlf_fn_DayLightSavings_Date(EntryExit,O.OrganizationID,TZ.HoursToBeAdded,TZ.MinToBeAdded,EntryExit)) 
  
+'-Trinetra' as varchar(    
      
20)))            
WHEN StatusType =2 THEN ('Msg:Your Children\n' + 'Name : '+ SM.StudentFirstName + + SM.StudentLastName + '\n Info: Started from School at : '+ CAST((dbo.rvlf_fn_DayLightSavings_Date(EntryExit,O.OrganizationID,TZ.HoursToBeAdded,TZ.MinToBeAdded,EntryExit) )
  
+'-Trinetra' as varchar    
      
(20))) end as MessageType,        
StatusType,0            
from @SMSTbl S inner join rvlfStudentMaster SM on S.StudentID = SM.StudentMasterID        
inner join rvlfOrganization O on O.OrganizationId = S.OrgId         
inner join rvlfTimeZones TZ on TZ.TimeZoneID = O.CountryId         
        
        
--select Sno,VehicleID,GeozoneID,OrganizationId,MessageTemplate from rvlfRFIDSchoolSMSNotification where IsSMSSent = 0        
--select Sno,StudentID,VehicleID,BoxID,GeozoneID,OrganizationId,EntryExit from rvlfRFIDSchoolSMSNotification where IsSMSSent = 0        
        
--select * from rvlfStudentMaster where StudentMasterID in(1,2)        
        
--(CASE WHEN sta=1 THEN ('Vehicle : '+DisplayName+ '\nInsurance Expiry Date : '+ExpiredDate + '\nDue : '+Remainingdays)            
-- WHEN ExpType=2 THEN ('Vehicle : '+DisplayName+ '\nPermit Expiry Date : '+ExpiredDate + '\nDue : '+Remainingdays)            
        
--where Origindatetime <         
--(select Origindatetime from @T1 where BoxMsgInTypeId =5)         
--and BoxMsgInTypeId =100 INNER JOIN @T1 as T2          
        
-- order by         
          
        
--declare @Trip int=0            
        
--while @Trip is not null           
                         
--begin                            
        
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetassignedVehiclesRoute]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
                  
CREATE Procedure [dbo].[rvlf_sp_GetassignedVehiclesRoute]    
(    
 @bigVehicleId BIGINT = 0,     
 @bigRouteId BIGINT = 0,    
 @dtFromDateTime DATETIME = NULL,                  
 @dtToDateTime DATETIME = NULL,                  
 @bigOrganizationId BIGINT = 0,                  
 @bigQueryingUser BIGINT = 0                  
)                  
AS                  
/**************************************************************************************/                  
-- Name : rvlf_sp_GetassignedVehiclesRoute    
-- Description : To get the assigned vehicle from the particular Route                  
-- Author : Gopal.R                  
-- Company : Angler Technologies                  
-- History : 27-Apr-2015  Created Intial Version     
/**************************************************************************************/                  
BEGIN                  
SET NOCOUNT ON                   
  declare @Lang varchar(50)         
  select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser      
                 
 DECLARE @HoursToBeAdded INT = 0                  
 DECLARE @MinsToBeAdded INT = 0                  
                   
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded                  
 FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz                  
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser                  
                  
 SET @dtFromDateTime = DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtFromDateTime))                  
 SET @dtToDateTime = DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtToDateTime))                  
                     
SELECT AssignmentId FROM rvlfRouteVehicleAssignment WHERE (FromDateTime BETWEEN @dtFromDateTime AND @dtToDateTime OR               
ToDateTime BETWEEN @dtFromDateTime AND @dtToDateTime ) and VehicleId=@bigVehicleId  and Isdelete !=1  
                      
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAssignRFIDDrivers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetAssignRFIDDrivers]  
@bigVehicleID BIGINT  = NULL,  
@bigOrganizationID INT = NULL,  
@bitIsAssigned BIT = NULL  
AS  
/******************************************************************************/          
-- Proc. Name : rvlf_sp_GetAssignRFIDDrivers  
-- Description : To get assigned / unassigned RFID driver to the vehicles  
-- Author   : SAKTHI GOPINATH S  
-- Company  : Trinetra Wireless (P) Ltd  
-- History   : <<Date(dd-MON-yyyy)>> Initial Reason  
--      : 12-Sep-2014  Created Intial Version  
/******************************************************************************/       
BEGIN  
SET NOCOUNT ON  
 IF @bitIsAssigned = 1  
 BEGIN  
  SELECT IB.IButtonId,IB.IButtonKey,IButtonKeyName,DM.DriverId,ISNULL(DM.DriverName,'-') AS DriverName FROM dbo.rvlfIButtonMapping IB  
  INNER JOIN dbo.rvlfVehicleRFIDs VR ON VR.IButtonID=IB.IButtonId  
  INNER JOIN dbo.rvlfVehicle V ON V.VehicleId=VR.VehicleId  
  LEFT OUTER JOIN dbo.rvlfDriverMaster DM ON DM.DriverId=IB.DriverId  
  WHERE IB.KeyType=3 AND V.VehicleId = @bigVehicleID AND V.OrganizationId=@bigOrganizationID  
 END  
 ELSE IF @bitIsAssigned = 0  
 BEGIN  
  SELECT IB.IButtonId,IB.IButtonKey,IButtonKeyName,DM.DriverId,ISNULL(DM.DriverName,'-') AS DriverName FROM dbo.rvlfIButtonMapping IB  
  LEFT OUTER JOIN dbo.rvlfDriverMaster DM ON DM.DriverId=IB.DriverId  
  WHERE IB.KeyType=3 AND IB.IButtonId NOT IN (SELECT IButtonId FROM dbo.rvlfVehicleRFIDs VR INNER JOIN dbo.rvlfVehicle V ON V.VehicleId=VR.VehicleId  
  WHERE V.VehicleId = @bigVehicleID AND V.OrganizationId=@bigOrganizationID)  
 END  
SET NOCOUNT OFF  
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetAxleLocation]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetAxleLocation]
@bigOrganizationId bigint = Null
AS
/******************************************************************************/
--	Name		  : rvlf_sp_GetAxleLocation 6
--	Description	  :	To get all the Axle and Location Details  
--	Author		  :	Kapil
--	Created Date  : 22-Feb-2014
--  Modified Date : 
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 
	SET ANSI_WARNINGS OFF;
       --SELECT  VendorId,VendorName FROM rvlfTyreVendorMaster where IsDelete =0 and IsActive =1 and OrganizationId= @bigOrganizationId
 
 
	select A.AxleID,A.AxleName from rvlfTyreAxleMaster A 
	
    select A.AxleID,L.TyreLocationID,L.TyreLocation from rvlfTyreAxleMaster A inner join rvlfTyreLocationMaster L on L.AxleID = A.AxleId  
    --WHERE A.AxleID not in(5)      
    
  --   select TyreName,TyreMappingId,Travelled,LifeTimeKM 
	 --from rvlfTyreVehicleMapping where OrganizationId = @bigOrganizationId
	 --and ISNULL(Category,0) = 2  and isnull(Travelled,0) < isnull(LifeTimeKM,0) and IsDelete = 0 and IsActive =1
    		
	select distinct TyreName,TyreMappingId,Travelled,LifeTimeKM 
		from rvlfTyreVehicleMapping where OrganizationId = @bigOrganizationId
		and ISNULL(Category,0) = 2  and isnull(Travelled,0) < isnull(LifeTimeKM,0) and IsDelete = 0 and IsActive =1		 
		and TyreName NOT IN (select TyreName from rvlfTyreVehicleMapping where Category is null AND OrganizationId = 1 AND IsDelete = 0 AND IsActive = 1)
		and TyreMappingId in 
		(
		select Max(TyreMappingId) from rvlfTyreVehicleMapping
		where OrganizationId = @bigOrganizationId
		and ISNULL(Category,0) = 2  and isnull(Travelled,0) < isnull(LifeTimeKM,0) and IsDelete = 0 and IsActive =1				
	 	and Category IS NOT NULL and ISNULL(IsRethread,0) <> 2
		--AND ISNULL(IsRethread,0) = 0
		--AND ISNULL(IsRethread,0) = 1
		group by TyreName  
		)
    	
  	SET NOCOUNT OFF
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetBestDriverDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetBestDriverDetails]
@bigFleetID bigint = NULL,
@intBoxID varchar(max) = NULL, 
@dtStartDate datetime = NULL,
@dtEndDate datetime = NULL,
@bitTripStatus bit = 1,
@bigOrganizationID bigint = NULL,
@bigQueryingUser bigint = NULL,
@vcBoxMsgTypeIDs nvarchar(50) = null
AS
/***********************************************************************************************************************
Procedure Name  : rvlf_sp_GetBestDriverDetails 222,NULL,'2012-11-01 04:00:00.000','2012-11-02 23:00:00.000',1,138,303
Description		: Get the best driver details based on their trip
Created By		: Sakthi Gopinath S
Created Date	: 15-Sep-2012
************************************************************************************************************************/        
BEGIN
SET NOCOUNT ON

	DECLARE @Lang varchar(50)         
	SELECT @Lang=isnull(Lang,'LanguageEn') from dbo.rvlfUserPreferences where UserId = @bigQueryingUser      
	DECLARE @dtFDate datetime =@dtStartDate      
	DECLARE @dtEDate datetime =@dtEndDate      
	DECLARE @HoursToBeAdded INT = 0        
	DECLARE @MinsToBeAdded INT = 0        
	DECLARE @ConversionFactor numeric (10,2) = 1.0        
	DECLARE @DistanceCaptionPrefix nvarchar(15)        
	DECLARE @SpeedCaptionPrefix nvarchar(15)      
	DECLARE @DisplayName nvarchar(30)
	DECLARE @FleetName varchar(50)
	DECLARE @DefaultDateFormat INT = 0;          	

	IF @bigFleetID IS NULL        
	BEGIN        
		SELECT @bigFleetID=FleetID from dbo.rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1        
	END        
	
	SELECT @FleetName= Fleetname FROM dbo.rvlfFleet WHERE OrganizationId=@bigOrganizationID AND FleetId=@bigFleetID
    
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@DisplayName = U.UserName,     
    @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,          
    @DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Km)' END,        
    @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END,
    @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)        
    FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser
	INNER JOIN dbo.rvlfUser U on U.UserId = up.UserId
         
	SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))        
	SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))        
         
	CREATE TABLE #tblMessageForProcessingTrip(  
	BoxId int null,  
	[OriginDateTime] [datetime] NOT NULL,        
	[BoxMsgInTypeId] [tinyint] NULL,        
	[CustomProp] [varchar](600) NULL,          
	[Speed] int NULL,        
	[Ignition] bit null,          
	[Address] nvarchar(300) null,        
	[OdoMeter] bigint null,        
	Lat numeric(10,6),        
	Long numeric(10,6)      
	)        
        
	DECLARE @tblBoxes TABLE (BoxID int unique)        
          
	INSERT INTO @tblBoxes(BoxID) 
	SELECT va.BoxID FROM dbo.rvlfVehicleAssignment va INNER JOIN dbo.rvlfVehicle v ON va.VehicleId = v.VehicleId        
    INNER JOIN dbo.rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId WHERE fv.FleetId = @bigFleetID AND 
    (@intBoxID IS NULL OR @intBoxID='' or BoxId in (SELECT FieldValue FROM rvlf_fn_ConvertArrayToTable(@intBoxID,','))) 
    AND V.OrganizationId=@bigOrganizationID ORDER BY BoxId
        
	DECLARE @intBoxLooping varchar(max)        
         
	SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes        
	WHILE @intBoxLooping IS NOT NULL        
	BEGIN         
		-- GET THE MSGS FOR THE BOXID        
		INSERT INTO #tblMessageForProcessingTrip(BoxId,OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,OdoMeter,Lat,Long)        
		SELECT h.BoxId,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((case when @Lang='LanguageArNew' then isnull(H.StreetAddress_Ar,H.StreetAddress) else H.StreetAddress end),(dbo.rvlf_fn_GetKeyMessages(@Lang,'Address is not resolved'))) ,'''','\''') 
		ELSE L.LandmarkName END, CASE WHEN CustomProp LIKE '%Odometer=%' THEN h.Odometer ELSE 0 END,H.Latitude,H.Longitude FROM dbo.rvlfMsgInHst H        
        LEFT OUTER JOIN dbo.rvlfLandmark L ON L.LandmarkID=H.LandMarkID WHERE h.BoxID = @intBoxLooping AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate  
        ORDER BY h.origindatetime ASC         
                
	    SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping        
	END     

	SELECT DISTINCT TOP 50 T.BoxId,v.VehicleDescription,'-' AS DriverCode,DM.DisplayName,ISNULL(DM.MobileNo,'-') AS MobileNo,
	(T.SP+T.HB+T.EB+T.HA+T.EA) AS ViolationCount,CASE WHEN T.SP = 0 THEN '-' ELSE CAST(T.SP AS CHAR(3)) END AS SP,
	CASE WHEN T.HB = 0 THEN '-' ELSE CAST(T.HB AS CHAR(3)) END AS HB,
	CASE WHEN T.EB = 0 THEN '-' ELSE CAST(T.EB AS CHAR(3)) END AS EB,
	CASE WHEN T.HA = 0 THEN '-' ELSE CAST(T.HA AS CHAR(3)) END AS HA,
	CASE WHEN T.EA = 0 THEN '-' ELSE CAST(T.EA AS CHAR(3)) END AS EA,
	T.SP AS SP_Cnt,	T.HB AS HB_Cnt,	T.EB AS EB_Cnt,	T.HA AS HA_Cnt,	T.EA AS EA_Cnt,
	DENSE_RANK()OVER(ORDER BY (T.SP+T.HB+T.EB+T.HA+T.EA)) AS [Rank],o.OrganizationName,@FleetName AS FleetName,
	CONVERT(VARCHAR,@dtFDate,@DefaultDateFormat)+ ' ' + CONVERT(VARCHAR,cast(@dtFDate AS TIME),22) AS PasStartDate,
	CONVERT(VARCHAR,@dtEDate,@DefaultDateFormat)+ ' ' + CONVERT(VARCHAR,cast(@dtEDate AS TIME),22) AS PasEndDate,
	@DisplayName + ' - '+CONVERT(VARCHAR,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ CONVERT(VARCHAR,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) AS TIME),22) AS PasGenerateddate         
	FROM  (SELECT pt.BoxId,COUNT(pt.BoxMsgInTypeId) As ViolationCount,
	SUM(CASE WHEN pt.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END) AS SP,
	SUM(CASE WHEN pt.BoxMsgInTypeId = 14 THEN 1 ELSE 0 END) AS HB,
	SUM(CASE WHEN pt.BoxMsgInTypeId = 15 THEN 1 ELSE 0 END) AS EB,
	SUM(CASE WHEN pt.BoxMsgInTypeId = 16 THEN 1 ELSE 0 END) AS HA,
	SUM(CASE WHEN pt.BoxMsgInTypeId = 17 THEN 1 ELSE 0 END) AS EA
	FROM #tblMessageForProcessingTrip pt --WHERE pt.BoxMsgInTypeId IN (4,14,15,16,17) 
	GROUP BY pt.BoxId) T INNER JOIN dbo.rvlfVehicleAssignment va ON va.BoxId=T.BoxId
	INNER JOIN dbo.rvlfVehicle v ON v.VehicleId=va.VehicleId
	INNER JOIN dbo.rvlfDriverAssignment DA ON DA.BoxId=T.BoxId
	INNER JOIN dbo.rvlfDriverMaster DM ON DM.DriverId=DA.DriverId
	INNER JOIN dbo.rvlfOrganization O ON O.OrganizationId=v.OrganizationId 
	WHERE V.OrganizationId=@bigOrganizationID ORDER BY 6,4 ASC
	
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetBoxCommInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetBoxCommInfo]    
 @intBoxID varchar(100) = null,    
 @bigVehicleID bigint = null    
AS    
/******************************************************************************/    
-- Name  : [rvlf_sp_GetBoxCommInfo]    
-- Description : To get the communication information of the device    
-- Author  : M. Jebamalai Jaya Chitra.    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 26-May-2009 MJJC Created Intial Version     
--    : 11-Oct-09 TSK Included the Vehicle Name    
--   : 11-Jun-11 Including vehicleId  
/******************************************************************************/    
BEGIN    
SET NOCOUNT ON     
     
 IF @bigVehicleID = 0    
 BEGIN    
  SET @bigVehicleID = NULL    
 END    
     
 SELECT c.BoxID, c.CommAddressTypeID, c.CommAddressValue, s.ServiceID ,s.SystemInstalled, p.BoxProtocolTypeName,V.VehicleId,V.VehicleDescription 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     
 (@intBoxID IS NULL OR @intBoxID='' OR c.BoxId = @intBoxID) AND    
 (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID)    
SET NOCOUNT OFF    
END    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetBoxMessages]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetBoxMessages]    
 @bitIsViolations bit = null,    
 @bitCanSeveritySet bit = null,    
 @tiBoxMsgInTypeId tinyint = null,    
 @cBoxMsgInTypeCode char (1) = null,    
 @tiBoxProtocolTypeId tinyint = null,    
 @siDefaultAlarmLevel smallint = null,    
 @bigQueryingUser bigint = null    
AS    
/******************************************************************************/    
-- Name  : rvlf_sp_GetBoxMessages    
-- Description : To get the box messages based on the criteria    
-- Author  : M. Jebamalai Jaya Chitra.    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 05-Aug-2009 MJJC Created Intial Version     
--    : 11-Dec-2009 MJJC Included the message restriction    
/******************************************************************************/    
BEGIN    
 SET NOCOUNT ON     
     
  SELECT m.BoxMsgInTypeId, m.BoxMsgInTypeDesc, m.CanSeveritySet, m.Isviolation, m.VisibleWeb,     
   m.BoxMsgInTypeDesc, p.BoxProtocolTypeName, p.MaxGeozones, mp.DefaultAlarmLevel,    
   mp.MsgInTypeLen, mp.Rules, s.AlarmLevelName, s.CanSendNotification, s.CreateAlarm    
   FROM rvlfBoxMsgInType m     
   INNER JOIN rvlfBoxProtocolMsgInType mp ON m.BoxMsgInTypeId = mp.BoxMsgInTypeId    
   INNER JOIN rvlfBoxProtocolType p ON mp.BoxProtocolTypeId = p.BoxProtocolTypeId    
   INNER JOIN rvlfSeverity s ON mp.DefaultAlarmLevel = s.AlarmLevelId    
  WHERE    
   (@bitIsViolations IS NULL OR @bitIsViolations='' OR m.Isviolation = @bitIsViolations)     
   AND (@bitCanSeveritySet IS NULL OR @bitCanSeveritySet='' OR m.CanSeveritySet = @bitCanSeveritySet )    
   AND (@tiBoxMsgInTypeId IS NULL OR @tiBoxMsgInTypeId='' OR m.BoxMsgInTypeId = @tiBoxMsgInTypeId)    
   AND (@cBoxMsgInTypeCode IS NULL OR @cBoxMsgInTypeCode='' OR m.BoxMsgInTypeCode = @cBoxMsgInTypeCode)    
   AND (@tiBoxProtocolTypeId IS NULL OR @tiBoxProtocolTypeId='' OR p.BoxProtocolTypeId = @tiBoxProtocolTypeId )    
   AND (@siDefaultAlarmLevel IS NULL OR @siDefaultAlarmLevel='' OR mp.DefaultAlarmLevel = @siDefaultAlarmLevel)    
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s     
   WHERE s.ModuleId = 26 and s.UserGroupId IN     
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))    
       
 SET NOCOUNT OFF    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetBoxOutputs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetBoxOutputs]  
 @bigFleetID bigint = null,  
 @intBoxID int = null,  
 @bigVehicleID bigint = null,  
 @bigOrganizationID bigint = null  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetBoxOutputs 1,999080  
-- Description : To get the box outputs settings  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 27-Jul-2009 MJJC Created Intial Version   
--              :   21-Feb-2010 MJJC Included defalut checking instead of name  
/******************************************************************************/  
BEGIN  
 IF @bigFleetID IS NULL   
 BEGIN  
  SELECT @bigFleetID = FleetID FROM rvlfFleet WHERE IsDefault=1 AND  
  (@bigOrganizationID IS NULL OR OrganizationId = @bigOrganizationID);  
 END  
 SET NOCOUNT ON   
  select v.VehicleId,v.VehicleDescription,   
  --SUBSTRING(OutputAction ,1, CHARINDEX('/',OutputAction,1)-1) AS OutputOn,  
  --SUBSTRING(OutputAction ,CHARINDEX('/',OutputAction,1)+1, LEN(OutputAction)) AS OutputOff,  
  ms.ActionOn AS OutputOn, ms.ActionOff AS OutputOff,  
  va.BoxId,m.OutputId, ms.OutputName from rvlfVehicleAssignment va   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
   INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
   INNER JOIN rvlfBoxOutputsCfg ms ON va.BoxId= ms.BoxId  
   INNER JOIN rvlfOutput m ON ms.OutputId = m.OutputId  
  WHERE (@intBoxID IS NULL OR @intBoxID='' OR va.BoxId = @intBoxID) AND  
     (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID) AND  
     (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND  
     (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID )    
 SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetBoxSensorSeverity]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetBoxSensorSeverity]    
 @bigFleetID bigint = null,    
 @intBoxID int = null,    
 @bigVehicleID bigint = null,    
 @bigOrganizationID bigint = null,
 @bigQueryingUser BIGINT = NULL 
AS    
/******************************************************************************/    
-- Name  : rvlf_sp_GetBoxSensorSeverity 389,0,null,6,18   
-- Description : To get the box sensor secerity settings    
-- Author  : M. Jebamalai Jaya Chitra.    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 27-Jul-2009 MJJC Created Intial Version     
--              :   21-Feb-2010 MJJC Included defalut checking instead of name    
-- : 09-Dec-2013  kapil Added Mulitlingual for Alarm and sensor.
/******************************************************************************/    
BEGIN    

DECLARE @Lang varchar(50)   
SELECT @Lang = isnull(Lang,'LanguageEn') FROM DBO.rvlfUserPreferences WHERE UserId = @bigQueryingUser  
   
 IF @bigFleetID IS NULL OR @bigFleetID=''  
 BEGIN    
  SELECT @bigFleetID = FleetID FROM rvlfFleet WHERE     
  (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId = @bigOrganizationID)    
   AND IsDefault=1    
 END    
 SET NOCOUNT ON     
  select distinct v.VehicleId,v.VehicleDescription,  
   (CASE WHEN @Lang='LanguageArNew' THEN ISNULL(m.ActionOn_Ar,m.ActionOn) WHEN @Lang='LanguageHindi' THEN ISNULL(m.ActionOn_Hin,m.ActionOn) else m.ActionOn END ) 
  as DefaultActionOn,   
   (CASE WHEN @Lang='LanguageArNew' THEN ISNULL(m.ActionOff_Ar,m.ActionOff) WHEN @Lang='LanguageHindi' THEN ISNULL(m.ActionOff_Hin,m.ActionOff) else m.ActionOff END ) 
  as DefaultActionOff,
   ms.AlarmLevelOn,ms.AlarmLevelOff ,   
  (CASE WHEN @Lang='LanguageArNew' THEN ISNULL(s.AlarmLevelName_Ar,s.AlarmLevelName) WHEN @Lang='LanguageHindi' THEN ISNULL(s.AlarmLevelName_Hin,s.AlarmLevelName) else s.AlarmLevelName END ) as AlarmLevelForOff, 
  (CASE WHEN @Lang='LanguageArNew' THEN ISNULL(ss.AlarmLevelName_Ar,ss.AlarmLevelName) WHEN @Lang='LanguageHindi' THEN ISNULL(ss.AlarmLevelName_Hin,ss.AlarmLevelName) else ss.AlarmLevelName END ) as AlarmLevelForON,  
  (CASE WHEN @Lang='LanguageArNew' THEN ISNULL(m.ActionOn_Ar,m.ActionOn) WHEN @Lang='LanguageHindi' THEN ISNULL(m.ActionOn_Hin,m.ActionOn) else m.ActionOn END ) 
  as ActionOn,
  (CASE WHEN @Lang='LanguageArNew' THEN ISNULL(m.ActionOff_Ar,m.ActionOff) WHEN @Lang='LanguageHindi' THEN ISNULL(m.ActionOff_Hin,m.ActionOff) else m.ActionOff END ) 
  as ActionOff,
  CASE WHEN @Lang='LanguageArNew' THEN ISNULL(m.SensorName_Ar,m.SensorName) WHEN @Lang='LanguageHindi' THEN ISNULL(m.SensorName_Hin,m.SensorName) ELSE m.SensorName END as SensorName,  
  va.BoxId,m.SensorId, CASE WHEN @Lang='LanguageArNew' THEN ISNULL(m.SensorName_Ar,m.SensorName) WHEN @Lang='LanguageHindi' THEN ISNULL(m.SensorName_Hin,m.SensorName) ELSE m.SensorName END AS DefaultSensorName from rvlfVehicleAssignment va   
   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId    
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId    
   INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId    
   INNER JOIN rvlfBoxSensorsCfg ms ON va.BoxId= ms.BoxId    
   INNER JOIN rvlfSensor m ON ms.SensorId = m.SensorId    
   INNER JOIN rvlfSeverity s ON ms.AlarmLevelOff = s.AlarmLevelId    
   INNER JOIN rvlfSeverity ss ON ms.AlarmLevelOn = ss.AlarmLevelId    
  WHERE (@intBoxID IS NULL OR @intBoxID='' OR va.BoxId = @intBoxID) AND    
     (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID) AND    
     (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND    
     (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID )    
  -- Don't Changed the order as this is used in the command sending window    
  ORDER BY m.SensorId ASC    
    
 SET NOCOUNT OFF    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetBoxSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetBoxSettings]    
@BoxId varchar(15) = null    
AS    
/******************************************************      
Stored Procedure Name : rvlf_sp_GetBoxSettings 34    
Purpose     : Retrieve the service for vehicle    
Created by    : Sakthi Gopinath S    
Created date   : 14-Jun-11    
*******************************************************/     
BEGIN    
SET NOCOUNT ON    
 SELECT BS.BoxId,CM.CommModeName FROM rvlfBoxSettings BS    
 INNER JOIN rvlfCommMode CM ON BS.CommModeId = CM.CommModeId    
 WHERE (@BoxId IS NULL OR @BoxId='' OR (BS.BoxId=@BoxId))    
SET NOCOUNT OFF    
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetBoxSeverity]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetBoxSeverity]    
 @bigFleetID bigint = null,    
 @intBoxID int = null,    
 @bigVehicleID bigint = null,    
 @bigOrganizationID bigint = null,
 @bigQueryingUser BIGINT = NULL 
     
AS    
/******************************************************************************/    
-- Name  : rvlf_sp_GetBoxSeverity null,999980,null,6,18
-- Description : To get the box message secerity settings    
-- Author  : M. Jebamalai Jaya Chitra.    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 25-Jul-2009 MJJC Created Intial Version     
--              :   21-Feb-2010 MJJC Included defalut checking instead of name    
/******************************************************************************/    
BEGIN    
 SET NOCOUNT ON  
  
 DECLARE @Lang varchar(50)   
 SELECT @Lang = isnull(Lang,'LanguageEn') FROM DBO.rvlfUserPreferences WHERE UserId = @bigQueryingUser  
       
 IF @bigFleetID IS NULL OR @bigFleetID=''    
 BEGIN    
  SELECT @bigFleetID = FleetID FROM rvlfFleet WHERE     
  (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId = @bigOrganizationID) AND isDefault = 1    
 END    
 --IF @intBoxID =0 BEGIN  SET @intBoxID=null END
 --IF @intBoxID IS NOT NULL    
 --BEGIN    
 -- select v.VehicleId,v.VehicleDescription, ms.AlarmLevelID, s.AlarmLevelName,     
 -- va.BoxId, m.BoxMsgInTypeName, m.BoxMsgInTypeId, m.IsDefaultAlarm,    
 --  m.BoxMsgInTypeDesc from rvlfVehicleAssignment va     
 --  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId    
 --  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId    
 --  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId    
 --  INNER JOIN rvlfBoxMsgSeverity ms ON va.BoxId= ms.BoxId    
 --  INNER JOIN rvlfBoxMsgInType m ON ms.BoxMsgInTypeId = m.BoxMsgInTypeId    
 --  INNER JOIN rvlfSeverity s ON ms.AlarmLevelID = s.AlarmLevelId    
 -- WHERE (@intBoxID IS NULL OR @intBoxID='' OR va.BoxId = @intBoxID) AND    
 --    (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID) AND    
 --    (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND    
 --    (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID )    
 --    AND CanSeveritySet=1 AND m.OperationTypeID IS NOT NULL    
 -- Order by m.BoxMsgInTypeDesc ASC    
 --END    
 IF @intBoxID = 0  
 BEGIN  
	 SELECT AB.BoxMsgInTypeId,AB.BoxMsgInTypeDesc,AB.BoxMsgInTypeName,AB.IsDefaultAlarm,AB.AlarmLevelId,(CASE WHEN @Lang='LanguageArNew' THEN ISNULL(s.AlarmLevelName_Ar,s.AlarmLevelName) WHEN @Lang='LanguageHindi' THEN ISNULL(s.AlarmLevelName_Hin,s.AlarmLevelName) else s.AlarmLevelName END ) as AlarmLevelName  FROM   
	(SELECT b.BoxMsgInTypeId, 
	(CASE WHEN @Lang='LanguageArNew' THEN ISNULL(b.BoxMsgInTypeDesc_Ar,b.BoxMsgInTypeDesc) WHEN @Lang='LanguageHindi' THEN ISNULL(b.BoxMsgInTypeDesc_Hin,b.BoxMsgInTypeDesc)  ELSE b.BoxMsgInTypeDesc END) as BoxMsgInTypeDesc
	,b.BoxMsgInTypeName, b.IsDefaultAlarm,   
	--(SELECT TOP 1 AlarmLevelID FROM rvlfBoxMsgSeverity  
	--WHERE BoxId IN (SELECT BoxId FROM rvlfBoxId WHERE OrganizationId=@bigOrganizationID) AND BoxMsgInTypeId=b.BoxMsgInTypeId  
	--GROUP BY AlarmLevelID,BoxMsgInTypeId ORDER BY COUNT(AlarmLevelId) DESC) AS AlarmLevelId  
	(SELECT TOP 1 bms.AlarmLevelID from rvlfBoxMsgSeverity BMS 
      inner join rvlfVehicleAssignment va on va.boxid = BMS.BoxId
      inner join rvlfFleetVehicles fv on fv.VehicleId =va.VehicleId
      where bms.BoxMsgInTypeId=b.BoxMsgInTypeId and fv.FleetId = @bigFleetID group by bms.AlarmLevelID ORDER BY COUNT(bms.AlarmLevelId) DESC) AS AlarmLevelId
	FROM rvlfBoxMsgInType b WHERE b.VisibleWeb=1  AND  CanSeveritySet=1 AND b.OperationTypeID IS NOT NULL AND b.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 b.OperationTypeID IS NOT NULL) AB INNER JOIN rvlfSeverity s ON s.AlarmLevelId=AB.AlarmLevelId  
	Order by AB.BoxMsgInTypeDesc ASC  
 END            
 ELSE IF @intBoxID IS NOT NULL    
 BEGIN    
  select v.VehicleId,v.VehicleDescription, ms.AlarmLevelID,(CASE WHEN @Lang='LanguageArNew' THEN ISNULL(s.AlarmLevelName_Ar,s.AlarmLevelName) WHEN @Lang='LanguageHindi' THEN ISNULL(s.AlarmLevelName_Hin,s.AlarmLevelName) else s.AlarmLevelName END ) as AlarmLevelName,              
   va.BoxId, m.BoxMsgInTypeName, m.BoxMsgInTypeId, m.IsDefaultAlarm,   
   --(CASE WHEN @Lang='LanguageArNew' THEN ISNULL(b.BoxMsgInTypeDesc_Ar,b.BoxMsgInTypeDesc) WHEN @Lang='LanguageHindi' THEN ISNULL(b.BoxMsgInTypeDesc_Hin,b.BoxMsgInTypeDesc)  ELSE b.BoxMsgInTypeDesc END) as BoxMsgInTypeDesc
   CASE WHEN @Lang='LanguageArNew' THEN ISNULL(m.BoxMsgInTypeDesc_Ar,m.BoxMsgInTypeDesc) WHEN @Lang='LanguageHindi' THEN ISNULL(m.BoxMsgInTypeDesc_Hin,m.BoxMsgInTypeDesc) else m.BoxMsgInTypeDesc END as BoxMsgInTypeDesc  
   from rvlfVehicleAssignment va     
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId    
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId    
   INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId    
   INNER JOIN rvlfBoxMsgSeverity ms ON va.BoxId= ms.BoxId    
   INNER JOIN rvlfBoxMsgInType m ON ms.BoxMsgInTypeId = m.BoxMsgInTypeId    
   INNER JOIN rvlfSeverity s ON ms.AlarmLevelID = s.AlarmLevelId    
  WHERE (@intBoxID IS NULL OR @intBoxID='' OR va.BoxId = @intBoxID) AND    
     (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID) AND    
     (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND    
     (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID )    
     AND CanSeveritySet=1 AND m.OperationTypeID IS NOT NULL    
  Order by m.BoxMsgInTypeDesc ASC    
 END    
 ELSE    
 BEGIN    
  SELECT b.BoxMsgInTypeId,
  	(CASE WHEN @Lang='LanguageArNew' THEN ISNULL(b.BoxMsgInTypeDesc_Ar,b.BoxMsgInTypeDesc) WHEN @Lang='LanguageHindi' THEN ISNULL(b.BoxMsgInTypeDesc_Hin,b.BoxMsgInTypeDesc)  ELSE b.BoxMsgInTypeDesc END) as BoxMsgInTypeDesc,
   b.BoxMsgInTypeName, b.IsDefaultAlarm FROM rvlfBoxMsgInType b    
   WHERE b.VisibleWeb=1     
  --and b.BoxMsgInTypeId    
   --NOT IN     
   -- (SELECT m.BoxMsgInTypeId FROM rvlfBoxMsgSeverity m WHERE m.BoxId = @intBoxID )    
  AND     
  CanSeveritySet=1 AND b.OperationTypeID IS NOT NULL    
  AND b.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 b.OperationTypeID IS NOT NULL    
  Order by b.BoxMsgInTypeDesc ASC    
 END    
     
 SET NOCOUNT OFF    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetBrandModelsTyreMapping]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetBrandModelsTyreMapping]
@bigOrganizationId bigint = Null,
@VendorId int = null
AS
/******************************************************************************/
--	Name		  : rvlf_sp_GetBrandModelsTyreMapping 1,44
--	Description	  :	To get all the VehicleNames
--	Author		  :	Kapil
--	Created Date  : 12-Mar-2014
--  Modified Date : 
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 
	
	SET ANSI_WARNINGS OFF;
	
	  --select distinct B.BrandID,B.BrandName,M.ModelID,M.ModelName,M.Remarks from 
	  --rvlfTyreMaster TM 
	  --inner join rvlfTyreMake B on B.BrandID = TM.BrandID 
	  --inner join rvlfTyreModel M on M.BrandID = TM.BrandID
	  --where TM.VendorId = @VendorId and TM.OrganizationId = @bigOrganizationId  
	  
	  select distinct B.BrandID,B.BrandName from   rvlfTyreMaster TM
	  inner join rvlfTyreMake B on B.BrandID = TM.BrandID	
	  where TM.VendorId = @VendorId and TM.OrganizationId = @bigOrganizationId
	    
	  select distinct M.BrandID,M.ModelID,M.ModelName,M.Remarks from 
	  rvlfTyreMaster TM
	  --inner join rvlfTyreMake B on B.BrandID = TM.BrandID
	 inner join rvlfTyreModel M on M.BrandID = TM.BrandID
	  where TM.VendorId = @VendorId and TM.OrganizationId = @bigOrganizationId
	  	  	  
	  select * from rvlfTyreMake where OrganizationId = @bigOrganizationId
	    	  	  
	  select M.BrandID,M.ModelID,M.ModelName,M.Remarks from rvlfTyreModel
	  M  left join rvlfTyreMake B on B.BrandID = M.BrandID 	  	  
	  where B.OrganizationId = @bigOrganizationId
	    
		
	SET NOCOUNT OFF
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetCarMakeandModel]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
      
      
      
CREATE Procedure [dbo].[rvlf_sp_GetCarMakeandModel]      
      
      
 @CarID int=null,      
 @IsDeleteMake bit=null,      
 @bitOpeation bit=null,      
 @VehicleTypeId int=null      
       
 /******************************************************************************/      
-- Name  : [rvlf_sp_GetCarMakeandModel]      
-- Description : To get the Car Make and Model details.      
-- Author  : V.MuthuKumaraVadivel      
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--    : 24-Feb-2011 VN Created Intial Version       
/******************************************************************************/      
      
AS      
      
BEGIN      
      
 IF(@bitOpeation =1)      
  BEGIN      
        
   SELECT MakeId,MakeName      
   FROM rvlfMake Make WHERE (@CarID IS NULL OR @CarID ='' OR Make.MakeId = @CarID) ORDER BY MakeName ASC       
         
         
   SELECT Model.ModelId,Model.ModelName,Make.MakeName,Make.MakeId,MakeType.VehicleTypeId,MakeType.VehicleTypeName  FROM rvlfModel Model INNER JOIN rvlfMake Make on Make.MakeId = Model.MakeId inner join rvlfVehicleType MakeType on Model.VehicleTypeId=MakeType.VehicleTypeId  WHERE (@CarID IS NULL OR @CarID ='' OR Model.ModelId=@CarID)       
         
   SELECT ModelId,MakeId  FROM rvlfModel WHERE (@CarID IS NULL OR @CarID ='' OR MakeId=@CarID)      
         
   SELECT VehicleTypeId,VehicleTypeName FROM rvlfVehicleType  WHERE (@CarID IS NULL OR @CarID ='' OR VehicleTypeId=@CarID)      
        
  END      
 ELSE      
  BEGIN      
        
  IF(@IsDeleteMake=0)      
  BEGIN      
        
   DELETE rvlfMake WHERE MakeId=@CarID      
         
   DELETE rvlfModel WHERE MakeId=@CarID      
  END      
  ELSE      
  BEGIN      
   DELETE rvlfModel WHERE ModelId=@CarID      
  END       
         
  END      
END      
      

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetCategoryServiceAssignments]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetCategoryServiceAssignments]
	@bigOrganizationID bigint,
	@bigServiceCategoryId bigint = NULL
AS
/**************************************************************************************/
--	Name		:	rvlf_sp_GetCategoryServiceAssignments
--	Description	:	To get the service category assignment details
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	29-Jun-2010		Created Intial Version 
/**************************************************************************************/
BEGIN
SET NOCOUNT ON 
		
	SELECT ms.ServiceId, ms.ServiceName, ms.Description, 
		dbo.rvlf_fn_GetMaintenanceServices(2, @bigServiceCategoryId, null) AS AssignedServices
	FROM rvlfMaintenanceService ms 
	WHERE OrganizationId = @bigOrganizationID
	
	SELECT ms.ServiceId, ms.ServiceName 
	FROM rvlfMaintenanceService ms 
	INNER JOIN rvlfMaintenanceCategoryService mc ON mc.ServiceId = ms.ServiceId
	WHERE mc.ServiceCategoryId = @bigServiceCategoryId
    
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetCommandResponse_ws]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetCommandResponse_ws]
@nUserId INT = NULL,
@cBoxIds VARCHAR(MAX) = NULL,
@cCmdType VARCHAR(3) = NULL
AS
/******************************************************************************/                                                  
-- Name			: rvlf_sp_GetCommandResponse_ws 94,'999981','?'
-- Description	: Get the command response 
-- Author		: Sakthi Gopinath S
-- Company		: Trinetra wireless (p) ltd
-- History		: <<Date(dd-MON-yyyy)>> Initial Reason          
-- Created Date	: 21-Oct-2016
/******************************************************************************/  
BEGIN
SET NOCOUNT ON


	DECLARE @HoursToBeAdded INT = 0              
	DECLARE @MinsToBeAdded INT = 0              
	DECLARE @DefaultDateFormat INT = 0;            
    DECLARE @nBoxCmdTypeId TINYINT = NULL
	    
	SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
	@DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)              
	FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz              
	ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @nUserId  

	SELECT @nBoxCmdTypeId=BoxCmdOutTypeId FROM rvlfBoxCmdOutType WHERE CAST(BoxCmdOutTypeCode AS VARBINARY) = CAST(@cCmdType AS VARBINARY)

	;WITH cteCommandTable AS
	(
		SELECT ROW_NUMBER() OVER (PARTITION BY oh.BoxId ORDER BY oh.SentDateTime DESC) AS Sno,oh.*,v.VehicleId,v.VehicleDescription
		from rvlfMsgOutHst oh INNER JOIN rvlfVehicleAssignment va ON va.BoxId=oh.BoxId
		INNER JOIN rvlfVehicle v ON v.VehicleId= va.VehicleId
		WHERE va.BoxId IN (SELECT FieldValue FROM rvlf_fn_ConvertArrayToTable(@cBoxIds,',')) AND 
		oh.BoxCmdOutTypeId = @nBoxCmdTypeId AND oh.BoxCmdOutTypeId IN (5,17) AND CONVERT(DATE,oh.SentDateTime) = CONVERT(DATE,GETUTCDATE())
	)

	SELECT BoxId,VehicleId,VehicleDescription,BoxCmdOutTypeId,ISNULL(Acknowledged,0) AS Acknowledged,
	CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,SentDateTime)),@DefaultDateFormat) + 
	' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,SentDateTime)) AS TIME),22) AS SentDateTime,
	(CASE WHEN ISNULL(Acknowledged,0) = 0 THEN 'Failed / Timeout' ELSE 'Success' END) AS AckStatus 
	FROM cteCommandTable WHERE Sno = 1

SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[RVLF_SP_GetCommands]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLF_SP_GetCommands]
	@bigCommandType bigint = null,
	@bigUserID AS bigint = null,
	@bigModuleID as bigint = 22,
	@bitIsNonAnglerAdmin AS bit = 0,
	@bigOrganizationID AS bigint = NULL
AS
/**************** **************************************************************/
--	Name		:	[RVLF_SP_GetCommands] null,29,22,0,1
--	Description	:	To get the command types
--	Author		:	V.Narayanasamy.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	30-Nov-2009	VN	Created Intial Version 
--				:	29-Dec-2009	MJJC Included the restriction for operation type id in order to restrict the ACK
/******************************************************************************/
BEGIN

	IF @bitIsNonAnglerAdmin = 1
	
		SELECT *  FROM rvlfBoxCmdOutType WHERE OperationTypeId IS NOT NULL order by BoxcmdTypeDesc asc --AND BoxCmdOutTypeId <> 22
	
	ELSE IF(@bitIsNonAnglerAdmin = 0)
	    BEGIN
			SELECT ct.*			 
				FROM rvlfBoxCmdOutType ct
				INNER JOIN rvlfOperationType ot ON ot.OperationTypeId = ct.OperationTypeId
				INNER JOIN rvlfModule m ON ot.ModuleID = m.ModuleID			
				INNER JOIN rvlfUserGroupSecurity up ON up.OperationTypeId = ot.OperationTypeId AND up.UserGroupId = 
					(SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigUserID)
			WHERE ot.ModuleID = 22 AND ct.OperationTypeId IS NOT NULL AND BoxCmdOutTypeId <> 22
			order by BoxcmdTypeDesc asc
		END	 
END






GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetCommandsandMessages]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvlf_sp_GetCommandsandMessages]
 @bigUserID AS bigint = null
-- @bitIsNonAnglerAdmin AS bit = 0 
 AS
BEGIN
--IF @bitIsNonAnglerAdmin = 1 
--BEGIN
-- SELECT *  FROM rvlfBoxMsgInType WHERE OperationTypeId IS NOT NULL  order by BoxMsgInTypeDesc asc 
-- SELECT *  FROM rvlfBoxMsgInType WHERE OperationTypeId IS NOT NULL  order by BoxMsgInTypeDesc asc 
-- END
--ELSE IF(@bitIsNonAnglerAdmin=0)
--BEGIN
-----Get the BoxmsgTypeName in boxmsgintype table-------
SELECT ct.BoxMsgInTypeId,ct.BoxMsgInTypeName,ct.BoxMsgInTypeCode,ct.BoxMsgInTypeDesc
    FROM rvlfBoxMsgInType ct  
    INNER JOIN rvlfOperationType ot ON ot.OperationTypeId = ct.OperationTypeId  
    INNER JOIN rvlfModule m ON ot.ModuleID = m.ModuleID     
    INNER JOIN rvlfUserGroupSecurity up ON up.OperationTypeId = ot.OperationTypeId AND up.UserGroupId =   
     (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigUserID)  
   order by BoxMsgInTypeDesc asc 
---End---------------
-----Get the boxcmdtypename in boxcmdouttype table-----
     SELECT ct.BoxCmdOutTypeId,ct.BoxCmdOutTypeName,ct.BoxCmdOutTypeCode,ct.BoxcmdTypeDesc      
    FROM rvlfBoxCmdOutType ct  
    INNER JOIN rvlfOperationType ot ON ot.OperationTypeId = ct.OperationTypeId  
    INNER JOIN rvlfModule m ON ot.ModuleID = m.ModuleID     
    INNER JOIN rvlfUserGroupSecurity up ON up.OperationTypeId = ot.OperationTypeId AND up.UserGroupId =   
     (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigUserID)  
   WHERE ot.ModuleID = 22 order by BoxcmdTypeDesc asc 
   --END
------END---------
 END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetCommMode]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetCommMode]  
AS  
/****************************************************************************************/    
-- Name    : [rvlf_sp_GetCommMode]    
-- Description   : To get all the data of Command Mode table  
-- Author    : Sakthi Gopinath S  
-- Created Date  : 11-Jun-2011  
-- Modified Date :    
/***************************************************************************************/    
BEGIN  
SET NOCOUNT ON  
 select CommModeId,CommModeName,CommModeDesc from rvlfCommMode  
SET NOCOUNT OFF  
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetCompactorDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetCompactorDetails]
(
 @VehicleId VARCHAR(50) = NULL
)
AS 
BEGIN
    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,VFantype, 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 
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetCompleteVehicleSummary]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetCompleteVehicleSummary]  
@FleetID BIGINT = NULL,  
@bigQueryingUser bigint = NULL,  
@VehicleId bigint = NULL,  
@bigOrganizationID bigint =NULL,  
@Top SMALLINT = NULL  
AS  
/***********************************************************************************************/          
-- Name   : rvlf_sp_GetCompleteVehicleSummary 301,303,1678,170,24  
-- Description : Get the complete vehicle summary and display the values in history page  
-- Author   : Sakthi          
-- Company  : Angler Technologies          
-- History   : <<Date(dd-MON-yyyy)>> Initial Reason          
--      : 02-Apr-2014 Sakthi Created Intial Version         
/***********************************************************************************************/      
BEGIN
SET NOCOUNT ON
 DECLARE @Lang varchar(50),  @LangSetting varchar(20)
 select @Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings from dbo.rvlfUserPreferences up
 inner join rvlfUser u on u.UserId = up.UserId
 inner join rvlfOrganization o on o.OrganizationId = u.OrganizationId
 where up.UserId = @bigQueryingUser
 
 DECLARE @HoursToBeAdded INT = 0                
 DECLARE @MinsToBeAdded INT = 0                
 DECLARE @ConversionFactor numeric (10,2) = 1.0                
 DECLARE @DistanceCaptionPrefix varchar(15)                
 DECLARE @SpeedCaptionPrefix varchar(15)              
 DECLARE @DefaultDateFormat INT = 0;              
 DECLARE @Hours varchar(max) = 0        
 DECLARE @Minutes INT = 0        
 DECLARE @Sign char =0        
 DECLARE @ToDate Datetime = NULL         
 DECLARE @FromDate Datetime = NULL        
 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,@DefaultDateFormat=(case when  isnull(up. DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)                
 FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz                
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser      
   
 DECLARE @tblTripDetailsForTD TABLE(                
   [TripId] [bigint]IDENTITY(1,1) NOT NULL,                
   [BoxId] [int] NOT NULL,                
   [StartDate] [datetime] NOT NULL,                
   [EndDate] [datetime] NULL,                
   [OdometerStart] [bigint] NOT NULL,                
   [OdometerEnd] [bigint] NULL,                
   [IsTripClosed] [bit] NULL,                
   [IdlingDuration] [int] NULL,              
   [StopTime] [int] NULL,                
   [StartAddress] nvarchar(300) NULL,                
   [EndAddress] nvarchar(300) NULL,                
   [Speed] int NULL,                
   [RunningTime] int null,                
   StartLat numeric(10,6),                
   StartLong numeric(10,6),                
   StopLat numeric(10,6),          
   StopLong numeric(10,6)                
 )                
   
 DECLARE @tblMessageForProcessingTrip TABLE (  
   MessageInId Uniqueidentifier NOT NULL,  
   [BoxId] bigint NOT NULL,             
   [OriginDateTime] [datetime] NOT NULL,                
   [BoxMsgInTypeId] [tinyint] NULL,                
   [CustomProp] [varchar](600) NULL,                  
   [Speed] int NULL,                
   [Ignition] bit null,                  
   [Address] nvarchar(300) null,  
   [OdoMeter] bigint null,                
   Lat numeric(10,6),                
   Long numeric(10,6),  
   LandmarkId int NULL,  
   LandmarkName VARCHAR(150) NULL  
 )                
  
 DECLARE @TBLSTART TABLE                
 (                
   Processid bigint identity(1,1),                
   Boxid int,                
   StartTime datetime,                
   OdoStart bigint,             
   StartAddress nvarchar(300),                
   Running int,                
   idling int,             
   Speed int,                
   StopInterval int,                
   tripId int,                
   Lat numeric(10,6),                
   Long numeric(10,6)                
 )                
                 
 DECLARE @TBLSTOP TABLE                
 (                
   Boxid int,                
   StopTime datetime,                
   OdoEnd bigint,                
   EndAddress nvarchar(300),                
   tripId int,                
   Lat numeric(10,6),                
   Long numeric(10,6),                
   IsTripCompleted bit                
 )                 
  
 DECLARE @dtStartDate DATETIME = DATEADD(HOUR,(-1*@Top),GETUTCDATE())  
 DECLARE @dtEndDate DATETIME = GETUTCDATE()  
  
    DELETE FROM @tblMessageForProcessingTrip   
 INSERT INTO @tblMessageForProcessingTrip(MessageInId,BoxId,OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,  
 Address,OdoMeter,Lat,Long,LandmarkId,LandmarkName)  
 SELECT h.MessageInID,h.BoxId,h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,  
 CAST(SUBSTRING(sensormask,6,1) as bit),                         
 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'),'''','\''') ,    
 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,H.LandMarkID,L.LandmarkName   
 FROM rvlfMsgInHst h INNER JOIN rvlfVehicleAssignment va ON va.BoxId=h.BoxId  
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId =va.VehicleId   
 LEFT OUTER JOIN dbo.rvlfLandmark L ON L.LandmarkID=H.LandMarkID  
 WHERE fv.FleetId = @FleetID AND va.VehicleId=@VehicleId AND h.OriginDateTime BETWEEN   
 @dtStartDate AND @dtEndDate  
  
 -- GET THE IGNITION ON DETAILS                
 DELETE FROM @TBLSTART                     
 INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                
 SELECT BoxId,OriginDateTime,OdoMeter,Address,Lat,Long                 
 FROM @tblMessageForProcessingTrip                       
 WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate  AND BoxMsgInTypeId IN(2)                
 AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
 WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
 AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
 WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)  
 AND Ignition=1 AND CustomProp LIKE '%SENSOR_NUM=3;%'                
                     
 --GET THE IGNITION OFF DETAILS                   
 DELETE FROM @TBLSTOP                 
 INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)                
 SELECT BoxId,OriginDateTime,OdoMeter,Address,Lat,Long FROM @tblMessageForProcessingTrip                  
 WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND  
 BoxMsgInTypeId IN(3) AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip   
 WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
 AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
 WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)  
 AND CustomProp LIKE '%SENSOR_NUM=3;%'  
                    
    --CHECK THE ONGOING TRIPS                 
    IF ((SELECT TOP 1 BoxMsgInTypeId FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3)   
    ORDER BY OriginDateTime DESC)=2)                
     BEGIN                
      INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                
       SELECT TOP 1 BoxId,OriginDateTime,OdoMeter,Address,Lat,Long                 
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3;%'   
        ORDER BY OriginDateTime DESC                     
     IF EXISTS(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                
        AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3;%'   
        ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC)                        
      BEGIN                        
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long,IsTripCompleted)              
        SELECT TOP 1 BoxId,OriginDateTime,OdoMeter,Address,Lat,Long,0                 
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                
         AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                
         FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3;%'   
         ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC                
      END                 
     ELSE                
      BEGIN                
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)                
        SELECT TOP 1 BoxId,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0               FROM @tblMessageForProcessingTrip          
      END                  
     END                
                         
    --PREPARE THE TRIPS AND DETAILS                    
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )                 
    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 @TBLSTART WHERE Processid >=@LOOP AND   
      (@DTEND IS NULL OR StartTime >@DTEND)                    
                      
      IF @DTSTOPSTART IS NOT NULL                         
       UPDATE top(1) @TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART                 
                      
      SET @DTSTOPSTART=@DTSTART                 
      SET @DTEND=NULL                
      SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART                 
                      
      UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART                 
      UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND                  
      UPDATE top(1) @TBLSTART SET Speed =(SELECT MAX(SPEED) FROM @tblMessageForProcessingTrip WHERE   
      OriginDateTime BETWEEN @DTSTART AND @DTEND),  
      idling=(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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND BoxMsgInTypeId =9                 
      AND CustomProp NOT LIKE '%Idling:0;%'),                
      Running=DATEDIFF(S,@DTSTART,@DTEND)                
      WHERE tripId=@INC AND StartTime=@DTSTART      
  
   SET @INC =@INC +1                
                      
      SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART                
                      
     END                 
  
 --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME                
    UPDATE @TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN   
    (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END                 
    WHERE Running IS NOT NULL                
                    
    --INSERT THE DETAILS IN THE MASTER TABLE                
    INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,                
     OdometerEnd,IdlingDuration,Speed, IsTripClosed,StopTime,RunningTime,StartLat,StartLong,StopLat,StopLong)                 
    SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,S.idling,                
     S.Speed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running,S.Lat,S.Long,ST.Lat,ST.Long                
      FROM @TBLSTART S  INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId                          
                     
   UPDATE @tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,  
   CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=  
   (SELECT MAX(TripId) FROM @tblTripDetailsForTD)             
   
 DECLARE @LastTollGate VARCHAR(75),@LastVisitedGeozone varchar(100)       
 DECLARE @VistedCount int = 0   ,@VisitedGeozoneCnt int=0 
   
 SELECT TOP 1 @LastTollGate= A.GeoName FROM  
 (SELECT pt.OriginDateTime,pt.BoxMsgInTypeId, (SELECT og.GeozoneName FROM rvlfOrganizationGeozone og   
 INNER JOIN rvlfCategory c ON c.CategoryId=og.CategoryId AND c.OrganizationId=og.OrganizationId  
 WHERE og.OrganizationId=@bigOrganizationID AND og.GeozoneId=  
 CAST(SUBSTRING(pt.CustomProp,CHARINDEX('GeozoneID=',pt.CustomProp,0)+10,  
 ((CHARINDEX(';Odometer=',pt.CustomProp,0))-(CHARINDEX('GeozoneID=',pt.CustomProp,0)+10))) AS INT) AND   
 c.CategoryName='Toll Gate')  AS GeoName, (SELECT 1 FROM rvlfOrganizationGeozone og   
 INNER JOIN rvlfCategory c ON c.CategoryId=og.CategoryId AND c.OrganizationId=og.OrganizationId  
 WHERE og.OrganizationId=@bigOrganizationID AND og.GeozoneId=  
 CAST(SUBSTRING(pt.CustomProp,CHARINDEX('GeozoneID=',pt.CustomProp,0)+10,  
 ((CHARINDEX(';Odometer=',pt.CustomProp,0))-(CHARINDEX('GeozoneID=',pt.CustomProp,0)+10))) AS INT) AND   
 c.CategoryName='Toll Gate') AS IsTollGate FROM @tblMessageForProcessingTrip pt WHERE BoxMsgInTypeId=5) A  
 WHERE A.IsTollGate=1 ORDER BY A.OriginDateTime DESC  
   
   SELECT TOP 1 @LastVisitedGeozone= og.GeozoneName  
 FROM @tblMessageForProcessingTrip pt inner join rvlfOrganizationGeozone og on CAST(dbo.rvlf_fn_GetParamValueWithIndex(pt.CustomProp,'GeozoneID=',';') AS INT)=og.GeozoneId and og.OrganizationId=@bigOrganizationID  
 inner join rvlfCategory c on og.CategoryId=c.CategoryId and c.CategoryName<>'Toll Gate' WHERE BoxMsgInTypeId=5  
  ORDER BY pt.OriginDateTime DESC 
  
 SELECT @VistedCount = SUM(ISNULL(IsEnable,0)) FROM  
 (SELECT 1 AS IsEnable FROM rvlfOrganizationGeozone og  INNER JOIN rvlfCategory c 
 ON c.CategoryId=og.CategoryId AND c.OrganizationId=og.OrganizationId
 INNER JOIN @tblMessageForProcessingTrip pt ON  pt.BoxMsgInTypeId=5 AND 
 og.GeozoneId=CAST(SUBSTRING(pt.CustomProp,CHARINDEX('GeozoneID=',pt.CustomProp,0)+10,
 ((CHARINDEX(';Odometer=',pt.CustomProp,0))-(CHARINDEX('GeozoneID=',pt.CustomProp,0)+10))) AS INT)
 WHERE og.OrganizationId=@bigOrganizationID AND  c.CategoryName='Toll Gate') A 
   
 SELECT @VisitedGeozoneCnt = SUM(ISNULL(IsEnable,0)) FROM
 (SELECT 1 AS IsEnable FROM rvlfOrganizationGeozone og  INNER JOIN rvlfCategory c
 ON c.CategoryId=og.CategoryId AND c.OrganizationId=og.OrganizationId
 INNER JOIN @tblMessageForProcessingTrip pt ON  pt.BoxMsgInTypeId=5 AND
 og.GeozoneId=CAST(dbo.rvlf_fn_GetParamValueWithIndex(pt.CustomProp,'GeozoneID=',';') AS INT)
 WHERE og.OrganizationId=@bigOrganizationID AND  c.CategoryName <> 'Toll Gate') A
 
 DECLARE @vcDriverName VARCHAR(75)  
 DECLARE @vcDriverNumber VARCHAR(13)  
 DECLARE @vcMapVal VARCHAR(500)  
 SELECT @vcDriverName = DM.DisplayName,@vcDriverNumber=DM.MobileNo,  
 @vcMapVal = ( CAST(ISNULL(CAST(h.Latitude AS VARCHAR),'') AS VARCHAR)           
     + '~#~' + CAST(ISNULL(CAST(h.Longitude AS VARCHAR),'') AS VARCHAR)           
     + '~#~' + REPLACE(ISNULL(h.StreetAddress,'Address is not resolved'),'''','\''')           
     + '~#~' + CAST(CAST((h.Speed * @ConversionFactor) as int)  AS VARCHAR) + ' ' + CAST(@SpeedCaptionPrefix AS VARCHAR)           
     + '~#~' + CAST((CASE WHEN h.Speed = 0 THEN -1 ELSE h.Heading END) AS VARCHAR)  
     + '~#~' + (case when @Lang='LanguageArNew' then isnull(rv.VehicleDescription,rv.VehicleDescription) else rv.VehicleDescription end)       
     + '~#~' + 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 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 VARCHAR)      
     + '~#~' + (dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId, h.MessageInID, h.OriginDateTime))           
     + '~#~' + ISNULL(L.LandmarkName,'-')            
     + '~#~' + ISNULL((case when @Lang='LanguageArNew' then isnull(dm.DisplayNameAr,dm.DisplayName) else DM.DisplayName end),'-')           
     + '~#~' + CAST(ISNULL(DM.Photo,'') AS VARCHAR(200))           
     + '~#~' + CAST(case when dm.MobileNo is null then isnull(dm.PhoneNo,'-') else dm.mobileno end  AS VARCHAR)      
     + '~#~' + 'Contact') --AS MAPVAL            
    FROM rvlfBoxId B           
     INNER JOIN rvlfMsgInHst h ON h.BoxId = B.BoxId  
     INNER JOIN rvlfVehicleAssignment RVA ON RVA.BoxId = B.BoxId           
     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           
    WHERE h.MessageInID = (SELECT TOP 1 MessageInId FROM @tblMessageForProcessingTrip ORDER BY OriginDateTime DESC)  
  
 SELECT V.VehicleId,V.LicensePlate,V.VehicleDescription,AB.*,  
 ISNULL(@vcDriverName,'-') AS DriverName,ISNULL(@vcDriverNumber,'-') AS DriverNo,  
 ISNULL(@LastTollGate,'-') AS LastVisitedTollGate,
 ISNULL(@LastVisitedGeozone,'-') AS LastVisitedGeozone  
 FROM rvlfVehicle V INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId  
 INNER JOIN (SELECT td.BoxId,dbo.rvlf_fn_GetTimeFromSeconds(SUM(ISNULL(RunningTime,0))) AS RunningHours,  
 dbo.rvlf_fn_GetTimeFromSeconds(SUM(ISNULL(IdlingDuration,0))) AS IdlingHours,  
 dbo.rvlf_fn_GetTimeFromSeconds(SUM(ISNULL(StopTime,0))) AS StopHours,  
 (SUM(OdometerEnd -OdometerStart) * @ConversionFactor) AS DistanceTravelled,@DistanceCaptionPrefix AS DistanceUnits,  
 ISNULL((SELECT TOP 1 CASE WHEN Speed = 0 THEN '-' ELSE CAST(Speed AS VARCHAR) END  
 FROM @tblMessageForProcessingTrip ORDER BY OriginDateTime DESC),'-') AS CurrentSpeed,  
 @SpeedCaptionPrefix AS SpeedUnits,  
 (SELECT TOP 1 Convert(varchar,DATEADD(MINUTE,@MinsToBeAdded,  
 DATEADD(HOUR,@HoursToBeAdded,OriginDateTime)),@DefaultDateFormat) + ' ' +   
 Convert(varchar,cast(DATEADD(MINUTE,@MinsToBeAdded,  
 DATEADD(HOUR,@HoursToBeAdded,OriginDateTime)) as time),22)   
 FROM @tblMessageForProcessingTrip  ORDER BY OriginDateTime DESC) AS LastUpdatedTime,  
 (SELECT TOP 1 Address FROM @tblMessageForProcessingTrip ORDER BY OriginDateTime DESC) AS CurrentAddress,  
 (SELECT CASE WHEN COUNT(BoxID) = 0 THEN '-' ELSE CAST(COUNT(BoxID) AS VARCHAR) END  
 FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId=4) AS SpeedCount,  
 (CASE WHEN @VistedCount IS NULL OR @VistedCount = 0 THEN '-' ELSE CAST(@VistedCount AS VARCHAR) END) AS TGVisitedCount,  
 (CASE WHEN @VisitedGeozoneCnt IS NULL OR @VisitedGeozoneCnt = 0 THEN '-' ELSE CAST(@VisitedGeozoneCnt AS VARCHAR) END) AS GVisitedCount,  
 (SELECT CASE WHEN COUNT(BoxID) = 0 THEN '-' ELSE CAST(COUNT(BoxID) AS VARCHAR) END 
 FROM rvlfAlarm WHERE BoxId=td.BoxId AND DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)
 AS AlarmCount,ISNULL((SELECT TOP 1 LandmarkName FROM @tblMessageForProcessingTrip WHERE
 LandmarkId IS NOT NULL ORDER BY OriginDateTime DESC),'-') AS LastLandmarkName,  
 @vcMapVal AS MapItValues  
 FROM @tblTripDetailsForTD td WHERE IsTripClosed=1  
 GROUP BY td.BoxID) AB ON AB.BoxId=va.BoxId  
   
SET NOCOUNT OFF  
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetCompleteVehicleSummary_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetCompleteVehicleSummary_PhoneGap]
@FleetID BIGINT = NULL,
@bigQueryingUser bigint = NULL,
@VehicleId bigint = NULL,
@bigOrganizationID bigint =NULL,
@Top SMALLINT = NULL
AS
/***********************************************************************************************/        
-- Name			: rvlf_sp_GetCompleteVehicleSummary_PhoneGap 61,19,646,40,24
-- Description	: Get the complete vehicle summary and display the values in history page
-- Author			: Sakthi        
-- Company		: Angler Technologies        
-- History			: <<Date(dd-MON-yyyy)>> Initial Reason        
--						: 02-Apr-2014 Sakthi Created Intial Version       
/***********************************************************************************************/    
BEGIN
SET NOCOUNT ON
	DECLARE @Lang varchar(50),  @LangSetting varchar(20)           
	select @Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings from dbo.rvlfUserPreferences up 
	inner join rvlfUser u on u.UserId = up.UserId
	inner join rvlfOrganization o on o.OrganizationId = u.OrganizationId 
	where up.UserId = @bigQueryingUser     
  
    DECLARE @HoursToBeAdded INT = 0              
	DECLARE @MinsToBeAdded INT = 0              
	DECLARE @ConversionFactor numeric (10,2) = 1.0              
	DECLARE @DistanceCaptionPrefix varchar(15)              
	DECLARE @SpeedCaptionPrefix varchar(15)            
	DECLARE @DefaultDateFormat INT = 0;            
	DECLARE @Hours varchar(max) = 0      
	DECLARE @Minutes INT = 0      
	DECLARE @Sign char =0      
	DECLARE @ToDate Datetime = NULL       
	DECLARE @FromDate Datetime = NULL      
    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,@DefaultDateFormat=(case when  isnull(up.	DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)              
	FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz              
	ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser    
 
	DECLARE @tblTripDetailsForTD TABLE(              
	  [TripId] [bigint]IDENTITY(1,1) NOT NULL,              
	  [BoxId] [int] NOT NULL,              
	  [StartDate] [datetime] NOT NULL,              
	  [EndDate] [datetime] NULL,              
	  [OdometerStart] [bigint] NOT NULL,              
	  [OdometerEnd] [bigint] NULL,              
	  [IsTripClosed] [bit] NULL,              
	  [IdlingDuration] [int] NULL,            
	  [StopTime] [int] NULL,              
	  [StartAddress] nvarchar(300) NULL,              
	  [EndAddress] nvarchar(300) NULL,              
	  [Speed] int NULL,              
	  [RunningTime] int null,              
	  StartLat numeric(10,6),              
	  StartLong numeric(10,6),              
	  StopLat numeric(10,6),        
	  StopLong numeric(10,6)              
	)              
 
	DECLARE @tblMessageForProcessingTrip TABLE (
	  MessageInId Uniqueidentifier NOT NULL,
	  [BoxId] bigint NOT NULL,           
	  [OriginDateTime] [datetime] NOT NULL,              
	  [BoxMsgInTypeId] [tinyint] NULL,              
	  [CustomProp] [varchar](600) NULL,                
	  [Speed] int NULL,              
	  [Ignition] bit null,                
	  [Address] nvarchar(300) null,
	  [OdoMeter] bigint null,              
	  Lat numeric(10,6),              
	  Long numeric(10,6),
	  LandmarkId int NULL,
	  LandmarkName VARCHAR(150) NULL
	)              

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

	DECLARE @dtStartDate DATETIME = DATEADD(HOUR,(-1*@Top),GETUTCDATE())
	DECLARE @dtEndDate DATETIME = GETUTCDATE()

    DELETE FROM @tblMessageForProcessingTrip 
	INSERT INTO @tblMessageForProcessingTrip(MessageInId,BoxId,OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,
	Address,OdoMeter,Lat,Long,LandmarkId,LandmarkName)
	SELECT h.MessageInID,h.BoxId,h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,
	CAST(SUBSTRING(sensormask,6,1) as bit),                       
	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'),'''','\''') ,  
	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,H.LandMarkID,L.LandmarkName 
	FROM rvlfMsgInHst h INNER JOIN rvlfVehicleAssignment va ON va.BoxId=h.BoxId
	INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId =va.VehicleId 
	LEFT OUTER JOIN dbo.rvlfLandmark L ON L.LandmarkID=H.LandMarkID
	WHERE fv.FleetId = @FleetID AND va.VehicleId=@VehicleId AND h.OriginDateTime BETWEEN 
	@dtStartDate AND @dtEndDate

	-- GET THE IGNITION ON DETAILS              
	DELETE FROM @TBLSTART                   
	INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)              
	SELECT BoxId,OriginDateTime,OdoMeter,Address,Lat,Long               
	FROM @tblMessageForProcessingTrip                     
	WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate  AND BoxMsgInTypeId IN(2)              
	AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip               
	WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)              
	AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip               
	WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)
	AND Ignition=1 AND CustomProp LIKE '%SENSOR_NUM=3;%'              
                   
	--GET THE IGNITION OFF DETAILS                 
	DELETE FROM @TBLSTOP               
	INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)              
	SELECT BoxId,OriginDateTime,OdoMeter,Address,Lat,Long FROM @tblMessageForProcessingTrip                
	WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND
	BoxMsgInTypeId IN(3) AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip 
	WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)              
	AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip               
	WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)
	AND CustomProp LIKE '%SENSOR_NUM=3;%'
                  
    --CHECK THE ONGOING TRIPS               
    IF ((SELECT TOP 1 BoxMsgInTypeId FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) 
    ORDER BY OriginDateTime DESC)=2)              
     BEGIN              
      INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)              
       SELECT TOP 1 BoxId,OriginDateTime,OdoMeter,Address,Lat,Long               
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3;%' 
        ORDER BY OriginDateTime DESC                   
     IF EXISTS(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)              
        AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime              
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3;%' 
        ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC)                      
      BEGIN                      
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long,IsTripCompleted)            
        SELECT TOP 1 BoxId,OriginDateTime,OdoMeter,Address,Lat,Long,0               
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)              
         AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime              
         FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3;%' 
         ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC              
      END               
     ELSE              
      BEGIN              
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)              
        SELECT TOP 1 BoxId,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0               FROM @tblMessageForProcessingTrip        
      END                
     END              
                       
    --PREPARE THE TRIPS AND DETAILS                  
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )               
    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 @TBLSTART WHERE Processid >=@LOOP AND 
      (@DTEND IS NULL OR StartTime >@DTEND)                  
                    
      IF @DTSTOPSTART IS NOT NULL                       
       UPDATE top(1) @TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART               
                    
      SET @DTSTOPSTART=@DTSTART               
      SET @DTEND=NULL              
      SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART               
                    
      UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART               
      UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND                
      UPDATE top(1) @TBLSTART SET Speed =(SELECT MAX(SPEED) FROM @tblMessageForProcessingTrip WHERE 
      OriginDateTime BETWEEN @DTSTART AND @DTEND),
      idling=(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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND BoxMsgInTypeId =9               
      AND CustomProp NOT LIKE '%Idling:0;%'),              
      Running=DATEDIFF(S,@DTSTART,@DTEND)              
      WHERE tripId=@INC AND StartTime=@DTSTART    

	  SET @INC =@INC +1              
                    
      SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART              
                    
     END               

 --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME              
    UPDATE @TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN 
    (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END               
    WHERE Running IS NOT NULL              
                  
    --INSERT THE DETAILS IN THE MASTER TABLE              
    INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,              
     OdometerEnd,IdlingDuration,Speed, IsTripClosed,StopTime,RunningTime,StartLat,StartLong,StopLat,StopLong)               
    SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,S.idling,              
     S.Speed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running,S.Lat,S.Long,ST.Lat,ST.Long              
      FROM @TBLSTART S  INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId                        
                   
   UPDATE @tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,
   CASE WHEN	GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=
   (SELECT MAX(TripId) FROM @tblTripDetailsForTD)           
 
	DECLARE @LastTollGate VARCHAR(75)   
	DECLARE @VistedCount int = 0
	SELECT TOP 1 @LastTollGate= A.GeoName FROM
	(SELECT pt.OriginDateTime,pt.BoxMsgInTypeId, (SELECT og.GeozoneName FROM rvlfOrganizationGeozone og 
	INNER JOIN rvlfCategory c ON c.CategoryId=og.CategoryId AND c.OrganizationId=og.OrganizationId
	WHERE og.OrganizationId=@bigOrganizationID AND og.GeozoneId=
	CAST(SUBSTRING(pt.CustomProp,CHARINDEX('GeozoneID=',pt.CustomProp,0)+10,
	((CHARINDEX(';Odometer=',pt.CustomProp,0))-(CHARINDEX('GeozoneID=',pt.CustomProp,0)+10))) AS INT) AND 
	c.CategoryName='Toll Gate')  AS GeoName, (SELECT 1 FROM rvlfOrganizationGeozone og 
	INNER JOIN rvlfCategory c ON c.CategoryId=og.CategoryId AND c.OrganizationId=og.OrganizationId
	WHERE og.OrganizationId=@bigOrganizationID AND og.GeozoneId=
	CAST(SUBSTRING(pt.CustomProp,CHARINDEX('GeozoneID=',pt.CustomProp,0)+10,
	((CHARINDEX(';Odometer=',pt.CustomProp,0))-(CHARINDEX('GeozoneID=',pt.CustomProp,0)+10))) AS INT) AND 
	c.CategoryName='Toll Gate') AS IsTollGate FROM @tblMessageForProcessingTrip pt WHERE BoxMsgInTypeId=5) A
	WHERE A.IsTollGate=1 ORDER BY A.OriginDateTime DESC
	
	SELECT @VistedCount = SUM(ISNULL(IsEnable,0)) FROM
	(SELECT 1 AS IsEnable FROM rvlfOrganizationGeozone og  INNER JOIN rvlfCategory c 
	ON c.CategoryId=og.CategoryId AND c.OrganizationId=og.OrganizationId
	INNER JOIN @tblMessageForProcessingTrip pt ON  pt.BoxMsgInTypeId=5 AND
	og.GeozoneId=CAST(SUBSTRING(pt.CustomProp,CHARINDEX('GeozoneID=',pt.CustomProp,0)+10,
	((CHARINDEX(';Odometer=',pt.CustomProp,0))-(CHARINDEX('GeozoneID=',pt.CustomProp,0)+10))) AS INT)
	WHERE og.OrganizationId=@bigOrganizationID AND  c.CategoryName='Toll Gate') A
	
	DECLARE @vcDriverName VARCHAR(75)
	DECLARE @vcDriverNumber VARCHAR(13)
	DECLARE @vcMapVal VARCHAR(500)
	SELECT @vcDriverName = DM.DisplayName,@vcDriverNumber=DM.MobileNo,
	@vcMapVal = ( CAST(ISNULL(CAST(h.Latitude AS VARCHAR),'') AS VARCHAR)         
     + '~#~' + CAST(ISNULL(CAST(h.Longitude AS VARCHAR),'') AS VARCHAR)         
     + '~#~' + REPLACE(ISNULL(h.StreetAddress,'Address is not resolved'),'''','\''')         
     + '~#~' + CAST(CAST((h.Speed * @ConversionFactor) as int)  AS VARCHAR) + ' ' + CAST(@SpeedCaptionPrefix AS VARCHAR)         
     + '~#~' + CAST((CASE WHEN h.Speed = 0 THEN -1 ELSE h.Heading END) AS VARCHAR)
     + '~#~' + (case when @Lang='LanguageArNew' then isnull(rv.VehicleDescription,rv.VehicleDescription) else rv.VehicleDescription end)     
     + '~#~' + 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 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 VARCHAR)    
     + '~#~' + (dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId, h.MessageInID, h.OriginDateTime))         
     + '~#~' + ISNULL(L.LandmarkName,'-')          
     + '~#~' + ISNULL((case when @Lang='LanguageArNew' then isnull(dm.DisplayNameAr,dm.DisplayName) else DM.DisplayName end),'-')         
     + '~#~' + CAST(ISNULL(DM.Photo,'') AS VARCHAR(200))         
     + '~#~' + CAST(case when dm.MobileNo is null then isnull(dm.PhoneNo,'-') else dm.mobileno end  AS VARCHAR)    
     + '~#~' + 'Contact') --AS MAPVAL          
    FROM rvlfBoxId B         
     INNER JOIN rvlfMsgInHst h ON h.BoxId = B.BoxId
     INNER JOIN rvlfVehicleAssignment RVA ON RVA.BoxId = B.BoxId         
     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         
    WHERE h.MessageInID = (SELECT TOP 1 MessageInId FROM @tblMessageForProcessingTrip ORDER BY OriginDateTime DESC)

	SELECT V.VehicleId,V.LicensePlate,V.VehicleDescription,AB.*,
	ISNULL(@vcDriverName,'-') AS DriverName,ISNULL(@vcDriverNumber,'-') AS DriverNo,
	ISNULL(@LastTollGate,'-') AS LastVisitedTollGate
	FROM rvlfVehicle V INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId
	INNER JOIN (SELECT td.BoxId,dbo.rvlf_fn_GetTimeFromSeconds(SUM(ISNULL(RunningTime,0))) AS RunningHours,
	dbo.rvlf_fn_GetTimeFromSeconds(SUM(ISNULL(IdlingDuration,0))) AS IdlingHours,
	dbo.rvlf_fn_GetTimeFromSeconds(SUM(ISNULL(StopTime,0))) AS StopHours,
	(SUM(OdometerEnd -OdometerStart) * @ConversionFactor) AS DistanceTravelled,@DistanceCaptionPrefix AS DistanceUnits,
	ISNULL((SELECT TOP 1 CASE WHEN Speed = 0 THEN '-' ELSE CAST(Speed AS VARCHAR) END
	FROM @tblMessageForProcessingTrip ORDER BY OriginDateTime DESC),'-') AS CurrentSpeed,
	@SpeedCaptionPrefix AS SpeedUnits,
	(SELECT TOP 1 Convert(varchar,DATEADD(MINUTE,@MinsToBeAdded,
	DATEADD(HOUR,@HoursToBeAdded,OriginDateTime)),@DefaultDateFormat) + ' ' + 
	Convert(varchar,cast(DATEADD(MINUTE,@MinsToBeAdded,
	DATEADD(HOUR,@HoursToBeAdded,OriginDateTime)) as time),22) 
	FROM @tblMessageForProcessingTrip 	ORDER BY OriginDateTime DESC) AS LastUpdatedTime,
	(SELECT TOP 1 Address FROM @tblMessageForProcessingTrip ORDER BY OriginDateTime DESC) AS CurrentAddress,
	(SELECT CASE WHEN COUNT(BoxID) = 0 THEN '-' ELSE CAST(COUNT(BoxID) AS VARCHAR) END
	FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId=4) AS SpeedCount,
	(CASE WHEN @VistedCount IS NULL OR @VistedCount = 0  
	THEN '-' ELSE CAST(@VistedCount AS VARCHAR) END) AS TGVisitedCount,
	(SELECT CASE WHEN COUNT(BoxID) = 0 THEN '-' ELSE CAST(COUNT(BoxID) AS VARCHAR) END 
	FROM rvlfAlarm WHERE BoxId=td.BoxId AND DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) 
	AS AlarmCount,ISNULL((SELECT TOP 1 LandmarkName FROM @tblMessageForProcessingTrip WHERE 
	LandmarkId IS NOT NULL ORDER BY OriginDateTime DESC),'-') AS LastLandmarkName,
	@vcMapVal AS MapItValues
	FROM @tblTripDetailsForTD td WHERE IsTripClosed=1
	GROUP BY td.BoxID) AB ON AB.BoxId=va.BoxId
	
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetCountries]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetCountries]

AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetCountries
--	Description	:	To gets the list of countries
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	12-Nov-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 
		SELECT * FROM rvlfCountry
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetCustomerAssignment]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetCustomerAssignment]
@OrganizationId INT = NULL
AS
/*************************************************************************************      
Procedure Name		  : rvlf_sp_GetCustomerAssignment 
Purpose               : Retrieve the list of Customer Assignment details
Created by            : T Kanimozhi    
Created date          : 07-June-18
History			      : TK Created initial version   
**************************************************************************************/   
BEGIN
SET NOCOUNT ON

	SELECT AssignmentId, REPLACE(CONVERT(VARCHAR(20), FromDate, 106),' ','-') as FromDate , 
	REPLACE(CONVERT(VARCHAR(20), ToDate, 106),' ','-') as ToDate,
	CONVERT(VARCHAR(20), FromDate, 101) AS FDate, CONVERT(VARCHAR(20), ToDate, 101) AS TDate,
	 c.CustomerId, c.CustomerName, v.VehicleId, v.VehicleDescription as VehicleName
	FROM rvlfCustomerAssignment ca 
	inner join rvlfCustomers c on ca.CustomerId = c.CustomerId
	inner join rvlfVehicle v on ca.VehicleId = v.VehicleId
	WHERE ca.OrgId = @OrganizationId AND ca.IsDelete=0 

SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetCustomerlist]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetCustomerlist]         
/******************************************************        
Stored Procedure Name : rvlf_sp_GetAllUsers    389    
Purpose     : Retrieve all Users        
Created by    : Uma        
Created date   : 11-Jul-09        
Updated by    :         
Updated date   :         
*******************************************************/        
        
@CustomerID nchar(20)  = Null,
@OrgId nchar(20)  = Null         
        
AS        
        
BEGIN         
         
 SELECT UserName,UserId from rvlfUser         
        
 WHERE CustomerID=  @CustomerID AND OrganizationId= @OrgId     
  
 ORDER BY UserName ASC   
        
END        
-- rvlf_sp_GetAllUsers Null  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDashboardChartPosition]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create Procedure [dbo].[rvlf_sp_GetDashboardChartPosition]      
(      
  @bigOrganizationId bigint=null,         
  @bigUserId bigint = null       
)
AS      
/****************************************************************************************/      
-- Name    : [rvlf_sp_GetDashboardChartPosition] 0,18      
-- Description   : To get Dashboard Chart Details
-- Author    : Kapil 
-- Created Date  : 29-April-2014
--  Modified Date :      
/***************************************************************************************/      
BEGIN      
 SET NOCOUNT ON        
     
  select chartposition from rvlfUserPreferences where UserId = @bigUserId --and OrganizationId = @bigOrganizationId 
              
 SET NOCOUNT OFF 
      
END 

--select * from rvlfNews where Type='Tips' and Convert(Date,TipsShownDate)=CONVERT(Date,GetDate())  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDashboardOverview_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Asanraj
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetDashboardOverview_PhoneGap] 
	@bigOrganizationID bigint,            
    @bigFleetID bigint = null,            
    @dtStartDate datetime =null,            
    @dtEndDate datetime=null,            
    @bigQueryingUser bigint,  
    @bigVehicleTypeID bigint = null,  
    @bigVehicleID bigint = null 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
 SET NOCOUNT ON;

 DECLARE @HoursToBeAdded INT = 0              
 DECLARE @MinsToBeAdded INT = 0              
 DECLARE @ConversionFactor numeric (10,2) = 1.0              
 DECLARE @CaptionPrefix varchar(10)              
 DECLARE @DefaultDateFormat INT = 0     
 DECLARE @VarUserPreferedChart  varchar(20) = null  
 DECLARE @UserLang  varchar(20) = NULL  
 Declare @bigTopNos bigint   = 10         
 
 
 SET @dtStartDate = DATEADD(DAY, DATEDIFF(DAY, 0, GETUTCDATE()),0)
 SET @dtEndDate = GETUTCDATE() 
              
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,              
 @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,              
 @CaptionPrefix = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'kms' END,            
 @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                       
  
  IF @bigFleetID IS NULL              
  SELECT @bigFleetID = FleetID FROM rvlfFleet where OrganizationId = @bigOrganizationID and  IsDefault=1 

   SELECT SUM(D.Infomation) AS InfoCnt, SUM(D.ETrip) AS ETripCnt, SUM(D.[Shutdown]) AS ShutdownCnt, SUM(D.CtrShutdown) AS CtrShutdown,
          SUM(D.Warning) AS WarningCnt,SUM(D.Warning) AS WarningCnt,SUM(D.[Offline]) AS OfflineCnt, SUM(D.Running) AS RunningCnt,SUM(D.Engine) AS EngineCnt  FROM (
    SELECT 
	CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) >= 480  THEN 1 ELSE 0 END AS [Offline],
	CASE WHEN 
	  (Vt.VehicleTypeId=1 AND B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND (SUBSTRING(ISNULL(h.Digital_OP,'0000000000000000'),10,1)='1')) OR ( (Vt.VehicleTypeId=2 AND B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND 
			  (SUBSTRING(ISNULL(hh.Digital_IP,'0000000000000000'),9,1)='1' OR SUBSTRING(isnull(hh.Digital_IP,'0000000000000000'),8,1) ='1'))) THEN 1 ELSE 0 END AS Running,
	CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND b.DeviceStatus =1 THEN 1 ELSE 0 END AS Infomation,
	CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND b.DeviceStatus=2 THEN 1 ELSE 0 END AS Warning,
	CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND b.DeviceStatus=3 THEN 1 ELSE 0 END AS ETrip,
	CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND b.DeviceStatus=4 THEN 1 ELSE 0 END AS [Shutdown],
	CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND b.DeviceStatus=5 THEN 1 ELSE 0 END AS CtrShutdown, 
	CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND b.DeviceStatus=6 THEN 1 ELSE 0 END AS Engine,	   	
    b.LastStatusDateTime,b.ControllerID
    FROM rvlfBoxId b   
      INNER JOIN rvlfVehicleAssignment va on va.BoxId =b.BoxId  
      INNER JOIN rvlfVehicle v on v.VehicleId =va.VehicleId  
      INNER JOIN rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
      INNER JOIN rvlffleet f on f.FleetId=fv.Fleetid
      INNER JOIN rvlfVehicleType vt on vt.VehicleTypeId =v.VehicleTypeId  
      INNER JOIN rvlfMAKDevices md on md.VehicleId=v.VehicleId  
	  LEFT OUTER JOIN rvlfMsgInHst_Techno h ON h.MessageInID = B.MessageInID
	  LEFT OUTER JOIN rvlfMsgInHst_Techno_355 hh ON hh.MessageInID =B.MessageInId
   WHERE b.OrganizationId= @bigOrganizationID and fv.FleetId IN  (@bigFleetID)   
    AND  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR v.VehicleTypeId = @bigVehicleTypeID)   
    AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID) 
    And (md.IsDelete = 0))D
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDaywiseFareDetailsRpt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_GetDaywiseFareDetailsRpt]                          
--@bigFleetID bigint = null,                          
 @bigVendorID bigint = null,                                    
 @intBoxID varchar(max) = null,                                    
 @dtStartDate datetime = null,                                    
 @dtEndDate datetime = null,                                    
                           
 @bigOrganizationID bigint = null,                                    
 @bigQueryingUser bigint = 0                            
as                            
-- =============================================                                              
-- Name   : rvlf_sp_GetDaywiseFareDetailsRpt   1,null,'11-21-2013 08:00:00.000 AM','11-25-2013 08:00:00.000 PM',6,12                                           
-- Author  : Gopal.R                                              
-- Create date : 28-Oct-2013                                              
-- Description :  GetDaywiseFareDetailsRpt                                              
-- Company  : Angler Technologies                                              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                              
-- =============================================                            
begin                           
 Declare @VendordutyHrs int                          
 Declare @fxKmperMonth int                          
 Declare @dtFDate datetime =@dtStartDate                                  
 Declare @dtEDate datetime =@dtEndDate                             
 DECLARE @HoursToBeAdded INT = 0                                    
 DECLARE @MinsToBeAdded INT = 0                                    
 DECLARE @ConversionFactor numeric (10,2) = 1.0                                    
 DECLARE @DistanceCaptionPrefix varchar(15)                                    
 DECLARE @SpeedCaptionPrefix varchar(15)                                  
 DECLARE @DefaultDateFormat INT = 0;                                  
 DECLARE @Hours varchar(max) = 0                            
 DECLARE @Minutes INT = 0                            
 DECLARE @Sign char =0                            
 DECLARE @ToDate Datetime = NULL                             
 DECLARE @FromDate Datetime = NULL                            
 Declare @VendorContractFrom datetime      
Declare @venodrContractTo datetime      
                            
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                            
-- @Hours= HOURS,@ToDate = ToDate,@FromDate = FromDate,                            
 --@Sign = SUBSTRING(Hours,1,1),@Minutes = SUBSTRING(Hours,5,2),                            
 @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,                        
 @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)                                    
 FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz                                    
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser                                   
                             
 set @VendordutyHrs =(CASE WHEN (SELECT DutyHourType FROM rvlfVendors WHERE VendorId=@bigVendorID)=24 THEN 1440 ELSE 720 END )                          
 set @fxKmperMonth = (select FxKMPerMonth from rvlfVendors ve where ve.VendorId=@bigVendorID)                            
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                                    
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))        
                           
                           
declare  @DayWiseDutyHrs table (Boxid bigint,Startdate date,DutyHrsMin int,DutySeconds bigint,distanceKM bigint)     
declare @TripAddress table (TripID bigint,StartAddr varchar(250),EndAddr varchar(250))        
      
if(@bigVendorID is not null or @bigVendorID <> '')                  
begin      
select @VendorContractFrom=ContractFrom,@venodrContractTo=ContractTo from rvlfVendors where VendorId=@bigVendorID      
end      
      
set @VendorContractFrom =DATEADD(HOUR,(23),DATEADD(MINUTE,(58),@VendorContractFrom))                          
set @venodrContractTo =DATEADD(HOUR,(23),DATEADD(MINUTE,(58),@venodrContractTo))      
                        
                          
insert into @DayWiseDutyHrs                            
select a.BoxId, StrtDate, sum(mint) as HrsPerDay,SUM(seconds) as seconds,SUM(distanceKM) as distanceKM from (select b.TripId,b.BoxId,cast(b.StartDate as date) as StrtDate,DATEDIFF(MINUTE,b.StartDate,b.EndDate) as mint,                        
DATEDIFF(SECOND,b.StartDate,b.EndDate) as seconds,(b.OdometerEnd-OdometerStart) as distanceKM from rvlfTripDetails_AFC b where b.IsTripClosed=1) as a                            
inner join rvlfTripFareDetails trpf on a.TripId=trpf.TripId                            
inner join rvlfVehicleAssignment va on a.BoxId=va.BoxId                            
inner join rvlfVehicle veh on va.VehicleId=veh.VehicleId                            
inner join rvlfVendorVehicles vv on veh.VehicleId=vv.VehicleId and vv.VendorId=@bigVendorID                          
inner join rvlfVendors ven on vv.VendorId=ven.VendorId                            
group by StrtDate,a.BoxId  order by StrtDate                  
                         
                          
insert into @TripAddress                          
select TripId, case when trp.StartMessageInID IN (select MessageInId from rvlfMsgInHst) then  
isnull((select a.GeozoneName from rvlfOrganizationGeozone a where a.OrganizationId=@bigOrganizationId and a.GeozoneId = cast((select SUBSTRING(SUBSTRING(CustomProp,CHARINDEX('GeozoneID=',CustomProp)+10,LEN(CustomProp)-CHARINDEX('GeozoneID=',CustomProp)),0,
  CHARINDEX(';',SUBSTRING(CustomProp,CHARINDEX('GeozoneID=',CustomProp)+10,LEN(CustomProp)-CHARINDEX('GeozoneID=',CustomProp))))
  from rvlfMsgInHst h where MessageInID=trp.StartMessageInID and CustomProp like '%GeozoneID=%') as int))
,(select isnull(L.LandmarkName,isnull(MH.StreetAddress,'N/A')) from rvlfMsgInHst MH LEFT join rvlfLandmark L on MH.LandMarkID=L.LandmarkID where MessageInID=trp.StartMessageInID )) else 'N/A' end as StartAddr,                        

case  when trp.EndMessageInID  IN (select MessageInId from rvlfMsgInHst) then 
isnull((select a.GeozoneName from rvlfOrganizationGeozone a where a.OrganizationId=@bigOrganizationId and a.GeozoneId = cast((select SUBSTRING(SUBSTRING(CustomProp,CHARINDEX('GeozoneID=',CustomProp)+10,LEN(CustomProp)-CHARINDEX('GeozoneID=',CustomProp)),0,
  CHARINDEX(';',SUBSTRING(CustomProp,CHARINDEX('GeozoneID=',CustomProp)+10,LEN(CustomProp)-CHARINDEX('GeozoneID=',CustomProp))))
  from rvlfMsgInHst h where MessageInID=trp.EndMessageInID and CustomProp like '%GeozoneID=%') as int))
 ,                      
(select isnull(L.LandmarkName,isnull(MH.StreetAddress,'N/A')) from rvlfMsgInHst MH LEFT join rvlfLandmark L on MH.LandMarkID=L.LandmarkID where MessageInID=trp.EndMessageInID)) else 'N/A' end as EndDAddr                       
from rvlfTripDetails_AFC trp                          
      
if (@dtStartDate between @VendorContractFrom and @venodrContractTo) --check start date and end date between contract period      
begin      
  if(@dtEndDate >= @VendorContractFrom and @dtEndDate > @venodrContractTo)      
  begin      
  set @dtEndDate =@venodrContractTo      
  end      
                            
  select trpf.TripId,ven.WorkOrder,ven.VendorName,veh.VehicleDescription,(veh.VehicleDescription + ' & ' + veh.LicensePlate) as LicensePlate,veh.vin,isnull(trpf.PackageLocation,'-') as PackageLocation,isnull(trpf.UsersDepartment,'-') as UsersDepartment  
  
     
        
   ,Convert(varchar,dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,106,trp.StartDate),106) as Tripdate                  
  ,StartDate=Convert(varchar(11),dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,trp.StartDate),106)                  
  ,EndDate=dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,trp.EndDate)                      
  ,cast((trp.OdometerStart * @ConversionFactor) as Int) as OdometerStart,cast((trp.OdometerEnd * @ConversionFactor) as Int) as OdometerEnd,                  
  cast(((trp.OdometerEnd-trp.OdometerStart) * @ConversionFactor) as Int) as TotKm                            
  ,isnull(cast(cast((trpf.UwDistance * @ConversionFactor)as Int) as varchar(10)),'-')as UwDistance,isnull(cast(trpf.FuelHike as varchar(10)),'-')as FuelHike,trpf.TollCharge ,         
  --,(dwd.distanceKM * @ConversionFactor) as distanceKM                  
  --isnull(cast(ven.ExCostPerHr as varchar(10)),'-')as ExCostPerHr,                  
  -- isnull(cast(ven.ExCostPerKm as varchar(10)),'-')as ExCostPerKm,                  
  -- isnull(cast(ven.FxCostPerMonth as varchar(10)),'-')as FxCostPerMonth, dwd.DutyHrsMin,          
   cast(CONVERT (time,dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,trp.StartDate)) as varchar(8)) as Starttime,                  
   cast(CONVERT(time,dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,trp.EndDate)) as varchar(8)) as closetime,                       
  dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SECOND,trp.StartDate,trp.EndDate)) as tripminutes,                            
                    
  dbo.rvlf_fn_GetTimeFromSeconds((select dwd.DutySeconds from @DayWiseDutyHrs dwd where dwd.Boxid=trp.Boxid and dwd.Startdate = CAST(trp.StartDate as DATE)) ) as DutyHrsSeconds,                          
  --PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtEDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()),            
  --,Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+                              
   --' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate ,                          
   dbo.rvlf_fn_GetTimeFromSeconds((CASE WHEN @VendordutyHrs> (select dwd.DutyHrsMin from @DayWiseDutyHrs dwd where dwd.Boxid=trp.Boxid and                 
   dwd.Startdate = CAST(trp.StartDate as DATE))                  
    then 0 else ((select dwd.DutyHrsMin from @DayWiseDutyHrs dwd where dwd.Boxid=trp.Boxid and dwd.Startdate = CAST(trp.StartDate as DATE)) - @VendordutyHrs) end)                
    *60) as totalExtraHrs ,                         
   isnull(Tadr.StartAddr,'N/A') as StartAddr,isnull(Tadr.EndAddr,'N/A') as EndAddr          
   ,Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+              
   ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate           
                     
   --case when dwd.distanceKM >@fxKmperMonth then ((dwd.distanceKM - @fxKmperMonth)*(ven.ExCostPerKm)) else 0.00 end as ExtraCostPerKm                    
     --( replace(CONVERT(varchar(5),dbo.rvlf_fn_GetTimeFromSeconds((CASE WHEN @VendordutyHrs> dwd.DutyHrsMin then 0 else (dwd.DutyHrsMin - @VendordutyHrs) end)*60)),':','.') *                    
    -- (Ven.ExCostPerHr))  as ExtraCostPerHr                          
                            
  from rvlfTripDetails_AFC trp                             
  inner join rvlfTripFareDetails trpf on trp.TripId=trpf.TripId                            
  inner join rvlfVehicleAssignment va on trp.BoxId=va.BoxId                            
  inner join rvlfVehicle veh on va.VehicleId=veh.VehicleId                            
  inner join rvlfVendorVehicles vv on veh.VehicleId=vv.VehicleId                            
  inner join rvlfVendors ven on vv.VendorId=ven.VendorId                            
  --inner join @DayWiseDutyHrs dwd on dwd.Startdate = CAST(trp.StartDate as DATE)                   
  inner join @TripAddress Tadr on trp.TripId=Tadr.TripID                          
  where (@dtStartDate is null or @dtStartDate = '' or trp.StartDate >= @dtStartDate ) and                         
  (@dtEndDate is null or @dtEndDate ='' or trp.EndDate <=@dtEndDate) and                  
  --(@dtStartDate is null or @dtStartDate = '' or trp.StartDate=@dtStartDate) and                         
  --(@dtEndDate is null or @dtEndDate ='' or trp.EndDate=@dtEndDate) and                
  (@intBoxID IS NULL or @intBoxID='' or va.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))and                 
  --(@intBoxID is null or @intBoxID ='' or va.BoxId=@intBoxID) and                        
  (@bigVendorID is null or @bigVendorID ='' or ven.VendorId=@bigVendorID) and                        
  (@bigOrganizationID is null or @bigOrganizationID ='' or ven.OrganizationId=@bigOrganizationID)                          
    and trp.IsTripClosed=1                   
   group by                             
    trpf.TripId,trpf.PackageLocation,trpf.UsersDepartment,trp.StartDate,trp.EndDate,trp.OdometerStart,trp.OdometerEnd,(trp.OdometerEnd-trp.OdometerStart)                          
  ,trpf.UwDistance,veh.VehicleDescription,veh.Vin,veh.LicensePlate,Tadr.StartAddr,Tadr.EndAddr,ven.WorkOrder,ven.VendorName,trpf.FuelHike                        
   ,trpf.TollCharge,trp.Boxid--ven.ExCostPerHr,ven.ExCostPerKm,ven.FxCostPerMonth,                  
  order by StartDate desc                            
 end                     
 end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDaywiseTripSummary]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetDaywiseTripSummary]                
 @bigFleetID bigint = null,                
 @intBoxID varchar(max) = null,                
 @dtStartDate datetime = null,                
 @dtEndDate datetime = null,                
 @bitTripStatus bit = 1,              
 @bigOrganizationID bigint = null,                
 @bigQueryingUser bigint = 0                
AS              
/********************************************************************************************************************          
Procedure Name :rvlf_sp_GetDaywiseTripSummary 186,null,'2013/09/27 08:00:00 AM','2013/09/28 08:00:00 PM',1,121,303           
Created by    : Sakthi Gopinath           
Create Date    : 01-Nov-2011          
      : 30-Nov-2011 Sakthi Distance calculation based on organization  
      : 28-09-2011 Remove round off function for distance in 2nd qry          
*********************************************************************************************************************/          
BEGIN          
          
SET NOCOUNT ON          
             
 Declare @dtFDate datetime =@dtStartDate              
 Declare @dtEDate datetime =@dtEndDate              
 IF @bigFleetID IS NULL                
 BEGIN                
   SELECT @bigFleetID=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)              
 DECLARE @DefaultDateFormat INT = 0;   
 DECLARE @Lang varchar(50),@LangSetting varchar(20)                   
           
 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,@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                
                 
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                
                 
 DECLARE @tblTripDetailsForTD TABLE(                
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,                
  [BoxId] [int] NOT NULL,                
  [StartDate] [datetime] NOT NULL,                
  [EndDate] [datetime] NULL,                
  [OdometerStart] [bigint] NOT NULL,                
  [OdometerEnd] [bigint] NULL,                
  [IsTripClosed] [bit] NULL,                
  [IdlingDuration] [int] NULL,                
  [StopTime] [int] NULL,                
  [StartAddress] nvarchar(300) NULL,                
  [EndAddress] nvarchar(300) NULL,                
  [Speed] int NULL,                
  [RunningTime] int null,                
  StartLat numeric(10,6),                
  StartLong numeric(10,6),                
  StopLat numeric(10,6),                
  StopLong numeric(10,6)                
                  
 )                
                 
 DECLARE @TBLSTART TABLE                
 (                
  Processid bigint identity(1,1),                
  Boxid int,                
  StartTime datetime,                
  OdoStart bigint,                
  StartAddress nvarchar(300),                
  Running int,                
  idling int,                
  Speed int,                
  StopInterval int,                
  tripId int,                
  Lat numeric(10,6),                
  Long numeric(10,6)                
 )                
                 
 DECLARE @TBLSTOP TABLE                
 (                
  Boxid int,                
  StopTime datetime,                
  OdoEnd bigint,                
  EndAddress nvarchar(300),                
  tripId int,                
  Lat numeric(10,6),            
  Long numeric(10,6),                
  IsTripCompleted bit                
 )                 
                
 DECLARE @intDuration int                
 DECLARE @dtOriginDateTime datetime               
 DECLARE @bigOdoMeterReading int                
 DECLARE @bitIgnitionStatus bit                
 DECLARE @vcStreetAddress nvarchar(250)                
 DECLARE @tiBoxMsgInTypeId tinyint                
 DECLARE @bigTripID bigint                
 DECLARE @intIterator int                
 DECLARE @canShowFuelMessage bit = 0                
                 
 IF EXISTS (SELECT * FROM rvlfPackageOperations r INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId                
   INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId                
      WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)                
 BEGIN                
    SET @canShowFuelMessage = 1                
 END                
                
 DECLARE @tblMessageForProcessingTrip TABLE (                
  [OriginDateTime] [datetime] NOT NULL,                
  [BoxMsgInTypeId] [tinyint] NULL,                
  [CustomProp] [varchar](600) NULL,                  
  [Speed] int NULL,                
  [Ignition] bit null,                  
  [Address] nvarchar(300) null,                
  [OdoMeter] bigint null,                
  Lat numeric(10,6),                
  Long numeric(10,6)                
 )                
                
 DECLARE @tblBoxes TABLE (BoxID int)                
                  
 INSERT INTO @tblBoxes (BoxID)           
 SELECT va.BoxID FROM rvlfVehicleAssignment va INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                
 WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' or BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID                
 ORDER BY BoxId                 
                
 DECLARE @intBoxLooping int                
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes                
           
 WHILE @intBoxLooping IS NOT NULL                
   BEGIN                 
      -- GET THE MSGS FOR THE BOXID                
      DELETE FROM @tblMessageForProcessingTrip                     
      INSERT INTO @tblMessageForProcessingTrip(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 (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 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.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                     
      AND h.BoxID = @intBoxLooping                          
      ORDER BY h.origindatetime ASC                 
                          
      -- GET THE IGNITION ON DETAILS                
      DELETE FROM @TBLSTART                     
      INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                
      SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long FROM @tblMessageForProcessingTrip                       
      WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                 
      AND BoxMsgInTypeId IN(2) AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
      WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
      WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                  
      AND Ignition=1 AND CustomProp LIKE '%SENSOR_NUM=3%'          
                         
                       
      --GET THE IGNITION OFF DETAILS                   
      DELETE FROM @TBLSTOP                 
      INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)                
      SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long FROM @tblMessageForProcessingTrip                  
      WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate         
      AND BoxMsgInTypeId IN(3) AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
      WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
      WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                  
      AND CustomProp LIKE '%SENSOR_NUM=3%'                
                      
      --CHECK THE ONGOING TRIPS                 
      IF ((SELECT TOP 1 BoxMsgInTypeId FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) ORDER BY OriginDateTime DESC)=2)                
       BEGIN                
        INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                
        SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                 
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC                     
                 
       IF EXISTS(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                
          AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                
          FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC )           
          ORDER BY OriginDateTime DESC)                        
        BEGIN             
         INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long,IsTripCompleted)                
          --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,OdoMeter,Address,Lat,Long,0                 
          SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long,0                 
          FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19) AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                
          FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC )           
          ORDER BY OriginDateTime DESC                
        END                 
       ELSE                
        BEGIN                
         INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)       
          --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                         
          SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                         
        END                  
   END                
                         
    --PREPARE THE TRIPS AND DETAILS                    
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )                 
    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 @TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                    
    
       IF @DTSTOPSTART IS NOT NULL                         
        UPDATE top(1) @TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART                 
                       
       SET @DTSTOPSTART=@DTSTART                 
       SET @DTEND=NULL                
       SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART                 
                       
       UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART                 
       UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND                  
       UPDATE top(1) @TBLSTART SET Speed =(SELECT MAX(SPEED) FROM @tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),                
       idling=(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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9                 
         AND CustomProp NOT LIKE '%Idling:0;%'),                
        --Running=(SELECT ISNULL(SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,                
        --(CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60,0)                             
        --FROM @tblMessageForProcessingTrip                 
        --WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =3)                
        Running=DATEDIFF(S,@DTSTART,@DTEND)                
        WHERE tripId=@INC AND StartTime=@DTSTART                 
                        
       SET @INC =@INC +1                
                       
       SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART                
     END                 
                           
    --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME                
    UPDATE @TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END                 
     WHERE Running IS NOT NULL                
                    
    --INSERT THE DETAILS IN THE MASTER TABLE                
    INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,                
     OdometerEnd,IdlingDuration,Speed, IsTripClosed,StopTime,RunningTime,StartLat,StartLong,StopLat,StopLong)                 
    SELECT S.Boxid,          
    S.StartTime,ST.StopTime,          
    S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,S.idling,                
     S.Speed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running,S.Lat,S.Long,ST.Lat,ST.Long                
      FROM @TBLSTART S                
       INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId                          
                     
   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping                
                   
   UPDATE @tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM @tblTripDetailsForTD)           
  
    
      
       
                   
   END                 
                
               
   DECLARE @TBLSUMMARY TABLE                
   (                
  Boxid int,             
  RunningTime int,                
  IdlingTime int,                
  StopTime int              
   )                
   INSERT INTO @TBLSUMMARY (Boxid,RunningTime,IdlingTime,StopTime)                   
   SELECT BoxId,SUM(ISNULL(RunningTime,0)),SUM(ISNULL(IdlingDuration,0)),SUM(ISNULL(StopTime,0))           
   FROM @tblTripDetailsForTD AS A GROUP BY BoxId          
             
   --SELECT * FROM @tblTripDetailsForTD          
             
   SELECT A.BoxId,CONVERT(varchar,StartDateSort,103) as OriginDate,dbo.rvlf_fn_getTimeFromSeconds(SUM(ISNULL(TripDuration,0))) as Duration,          
   (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,SUM(ISNULL(A.Distance,0)))) as Distance,          
   Count(TripId) as NoOfTrips,MIN(StartDateSort) as StartDate,MAX(EndDateSort) as EndDate,          
   Max(CASE WHEN Speed = '-' THEN 0 ELSE CAST(Speed as int) END) as MaximumSpeed, dbo.rvlf_fn_getTimeFromSeconds(SUM(ISNULL(A.StopTime,0))) as StopTime,          
   dbo.rvlf_fn_getTimeFromSeconds(SUM(ISNULL(A.IdlingDuration,0))) as IdlingDuration,          
   (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(MIN(A.OdometerStart) * @ConversionFactor))) as OdometerStart,          
   (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(MAX(A.OdometerEnd) * @ConversionFactor))) AS OdometerEnd,VIN,LicensePlate,VehicleDescription,MakeName,ModelName,ModelYear,          
 --TS.STARTADD AS StartAddress,TS.ENDADD AS EndAddress,          
   dbo.rvlf_fn_getTimeFromSeconds(TS.IdlingTime) AS IdlingSummary,                
   dbo.rvlf_fn_getTimeFromSeconds(TS.RunningTime) as RunningSummary,                
   dbo.rvlf_fn_getTimeFromSeconds(Ts.StopTime) as StopSummary,          
   @DistanceCaptionPrefix As DistanceCaption,          
   @SpeedCaptionPrefix AS SpeedCaption,          
   Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+          
   ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,          
 --  (SELECT A.StartAddress  FROM @tblTripDetailsForTD AS A  WHERE A.Boxid=TS.Boxid AND A.StartDate=(SELECT MIN(StartDate) FROM @tblTripDetailsForTD WHERE Boxid=TS.Boxid AND CONVERT(varchar,StartDate,103) = CONVERT(varchar,StartDateSort,103))) AS StartAddress,          
  -- (SELECT CASE WHEN CONVERT(varchar,A.StartDate,103)=CONVERT(varchar,A.EndDate,103) THEN A.EndAddress ELSE A.StartAddress END  FROM @tblTripDetailsForTD AS A  WHERE A.Boxid=TS.Boxid AND A.StartDate =(SELECT MAX(StartDate) FROM @tblTripDetailsForTD WHERE Boxid=TS.Boxid AND CONVERT(varchar,StartDate,103) = CONVERT(varchar,StartDateSort,103))) AS EndAddress          
  isnull((SELECT A.StartAddress  FROM @tblTripDetailsForTD AS A  WHERE A.Boxid=TS.Boxid AND A.StartDate=(SELECT MIN(StartDate) FROM @tblTripDetailsForTD WHERE Boxid=TS.Boxid AND CONVERT(varchar,StartDate,103) = CONVERT(varchar,StartDateSort,103))),'N/A') 
  
    
      
AS StartAddress,          
   isnull((SELECT CASE WHEN CONVERT(varchar,A.StartDate,103)=CONVERT(varchar,A.EndDate,103) THEN A.EndAddress ELSE A.StartAddress END  FROM @tblTripDetailsForTD AS A  WHERE A.Boxid=TS.Boxid AND A.StartDate =(SELECT MAX(StartDate) FROM @tblTripDetailsForTD
  
    
      
 WHERE Boxid=TS.Boxid AND CONVERT(varchar,StartDate,103) = CONVERT(varchar,StartDateSort,103))),'N/A') AS EndAddress          
   --(SELECT MIN(StartDate) FROM @tblTripDetailsForTD WHERE Boxid=TS.Boxid AND CONVERT(varchar,StartDate,103)=CONVERT(varchar,StartDateSort,103))          
             
   FROM (SELECT t.TripId,                
   CASE WHEN CEILING(CAST((ABS(ISNULL((T.OdometerEnd-T.OdometerStart), 0)) * @ConversionFactor) as varchar(20))) > 0 AND T.Speed =0 THEN '-' ELSE CONVERT(VARCHAR,T.Speed) END Speed,                
   t.BoxId,CONVERT(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,T.StartDate)),@DefaultDateFormat)+ ' ' + CONVERT(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,T.StartDate)) as time),22)  as StartDate,               
   Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,T.EndDate)),@DefaultDateFormat)+ ' ' + Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,T.EndDate)) as time),22) as EndDate,                
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,T.StartDate))  as StartDateSort,               
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,T.EndDate)) as EndDateSort,                   
   CASE WHEN T.IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,                
   dbo.rvlf_fn_getTimeFromSeconds(T.RunningTime) as Duration,                
   T.RunningTime as TripDuration,                 
   --CEILING(CAST((ABS(ISNULL((T.OdometerEnd-T.OdometerStart), 0)) * @ConversionFactor) as varchar(20)))as Distance,                 
   --CEILING(CAST(ROUND(ROUND((ISNULL((T.OdometerEnd-T.OdometerStart), 0) * @ConversionFactor),1),0) as varchar(20))) as Distance,                 
   CEILING(CAST(ROUND(ROUND((ISNULL(case when T.OdometerEnd = 0 Then 1 else T.OdometerEnd END -  T.OdometerStart, 0) * @ConversionFactor),1),0) as varchar(20))) as Distance,                 
   StartAddress ,CASE WHEN T.IsTripClosed = 1 THEN EndAddress  ELSE 'Ongoing Trip' END AS EndAddress  , --Vin, LicensePlate, VehDispName as VehicleDescription, MakeName, ModelName,ModelYear,                 
   dbo.rvlf_fn_GetTimeFromSeconds(T.IdlingDuration) AS IdlingTime, T.IdlingDuration,                
   CASE WHEN T.StopTime IS NULL THEN dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SS,T.EndDate , @dtEndDate))                 
   WHEN T.StopTime =0 THEN '-'                
   ELSE dbo.rvlf_fn_GetTimeFromSeconds(T.StopTime) END AS StopDuration,                
   CASE WHEN T.StopTime IS NULL THEN ABS(DATEDIFF(SS,T.EndDate ,@dtEndDate)) ELSE T.StopTime END AS StopTime,                
   @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,                
   CEILING(CAST((ABS(ISNULL(t.OdometerStart, 0)) * @ConversionFactor) as varchar(20)))as OdometerStart,                
   CEILING(CAST((ABS(ISNULL(t.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)))as OdometerEnd,                
   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerStart, 0)) * @ConversionFactor) as varchar(20)),0,0) FROM @tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerStart ASC) As OdometerStartReading,                 
   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)),0,0)FROM @tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerEnd DESC) AS OdometerEndReading,                
   T.StartLat,T.StartLong,T.StopLat,T.StopLong FROM @tblTripDetailsForTD t ) A                
   INNER JOIN @TBLSUMMARY TS ON TS.Boxid =A.BoxId                 
   INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON A.BoxId = va.BoxId                
 INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
   LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId                
   LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId                  
   GROUP BY CONVERT(varchar,A.StartDateSort,103),A.BoxId,VIN,LicensePlate,VehicleDescription,MakeName,ModelName,ModelYear,          
   Ts.IdlingTime,Ts.RunningTime,Ts.StopTime,TS.Boxid           
   Order By A.BoxId          
                       
   SELECT VehicleName, (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END   
   FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Round(Distance,0))) AS Distance    
   --ROUND((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Round(Distance,0))),0) AS Distance-- Round(Distance,0)Distance                
   FROM                
   (                
   select v.VehicleDescription VehicleName,                
   CAST((MAX(isnull(OdometerEnd,0))-MIN(ISNULL(OdometerStart,0)))* @ConversionFactor as varchar(20))Distance      
   --, CAST((ABS(ISNULL(SUM(OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as numeric(8,2)) as Distance                
   from @tblTripDetailsForTD t                
   INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON t.BoxId = va.BoxId                
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
   Group By VehicleDescription)B Where CAST(Distance AS numeric(22,2)) > 0           
            
  SET NOCOUNT OFF          
          
END          
--BEGIN          
          
--SET NOCOUNT ON          
             
-- Declare @dtFDate datetime =@dtStartDate              
-- Declare @dtEDate datetime =@dtEndDate              
-- IF @bigFleetID IS NULL                
-- BEGIN                
--   SELECT @bigFleetID=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)              
-- DECLARE @DefaultDateFormat INT = 0;                  
           
-- 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,@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 = @bigQueryingUser                
                 
-- SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                
-- SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                
                 
-- DECLARE @tblTripDetailsForTD TABLE(                
--  [TripId] [bigint]IDENTITY(1,1) NOT NULL,                
--  [BoxId] [int] NOT NULL,                
--  [StartDate] [datetime] NOT NULL,                
--  [EndDate] [datetime] NULL,                
--  [OdometerStart] [bigint] NOT NULL,                
--  [OdometerEnd] [bigint] NULL,                
--  [IsTripClosed] [bit] NULL,                
--  [IdlingDuration] [int] NULL,                
--  [StopTime] [int] NULL,                
--  [StartAddress] nvarchar(300) NULL,                
--  [EndAddress] nvarchar(300) NULL,                
--  [Speed] int NULL,                
--  [RunningTime] int null,                
--  StartLat numeric(10,6),                
--  StartLong numeric(10,6),                
--  StopLat numeric(10,6),                --  StopLong numeric(10,6)                
                  
-- )                
                 
-- DECLARE @TBLSTART 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 @TBLSTOP TABLE                
-- (                
--  Boxid int,                
--  StopTime datetime,                
--  OdoEnd bigint,                
--  EndAddress varchar(300),                
--  tripId int,                
--  Lat numeric(10,6),                
--  Long numeric(10,6),                
--  IsTripCompleted bit                
-- )                 
                
-- DECLARE @intDuration int                
-- DECLARE @dtOriginDateTime datetime                
-- DECLARE @bigOdoMeterReading int                
-- DECLARE @bitIgnitionStatus bit                
-- DECLARE @vcStreetAddress nvarchar(250)                
-- DECLARE @tiBoxMsgInTypeId tinyint      
-- DECLARE @bigTripID bigint                
-- DECLARE @intIterator int                
-- DECLARE @canShowFuelMessage bit = 0                
                 
-- IF EXISTS (SELECT * FROM rvlfPackageOperations r INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId                
--   INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId                
--      WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)                
-- BEGIN                
--    SET @canShowFuelMessage = 1                
-- END                
                
-- DECLARE @tblMessageForProcessingTrip 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 @tblBoxes TABLE (BoxID int)                
                  
-- INSERT INTO @tblBoxes (BoxID)           
-- SELECT va.BoxID FROM rvlfVehicleAssignment va INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
-- INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                
-- WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or BoxId = @intBoxID) AND V.OrganizationId=@bigOrganizationID                
-- ORDER BY BoxId                 
                
-- DECLARE @intBoxLooping int                
-- SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes                
           
-- WHILE @intBoxLooping IS NOT NULL                
--   BEGIN                 
--      -- GET THE MSGS FOR THE BOXID                
--      DELETE FROM @tblMessageForProcessingTrip                     
--      INSERT INTO @tblMessageForProcessingTrip(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.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                          
--      AND h.BoxID = @intBoxLooping                          
--      ORDER BY h.origindatetime ASC                 
                          
--      -- GET THE IGNITION ON DETAILS                
--      DELETE FROM @TBLSTART                     
--      INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                
--      SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long FROM @tblMessageForProcessingTrip                       
--      WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                 
--      AND BoxMsgInTypeId IN(2) AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
--      WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
--      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
--      WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                  
--      AND Ignition=1 AND CustomProp LIKE '%SENSOR_NUM=3%'                
                         
        
--      --GET THE IGNITION OFF DETAILS                   
--      DELETE FROM @TBLSTOP                 
--      INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)                
--      SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long FROM @tblMessageForProcessingTrip                  
--      WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                 
--      AND BoxMsgInTypeId IN(3) AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
--      WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
--      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
--      WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                  
--      AND CustomProp LIKE '%SENSOR_NUM=3%'                
                      
--      --CHECK THE ONGOING TRIPS                 
--      IF ((SELECT TOP 1 BoxMsgInTypeId FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) ORDER BY OriginDateTime DESC)=2)                
--       BEGIN                
--        INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                
--        SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                 
--        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC                     
                 
--       IF EXISTS(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                
--          AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                
--          FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC )           
--          ORDER BY OriginDateTime DESC)                        
--        BEGIN             
--         INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long,IsTripCompleted)                
--          --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,OdoMeter,Address,Lat,Long,0                 
--          SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long,0                 
--          FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19) AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                
--          FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC )           
--          ORDER BY OriginDateTime DESC                
--        END                 
--       ELSE                
--        BEGIN                
--         INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)                
--          --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                         
--          SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                         
--        END                  
--   END                
                         
--    --PREPARE THE TRIPS AND DETAILS                    
--    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )                 
--    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 @TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                    
                       
--       IF @DTSTOPSTART IS NOT NULL                         
--        UPDATE top(1) @TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART                 
                       
--       SET @DTSTOPSTART=@DTSTART         
--       SET @DTEND=NULL                
--       SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART                 
                       
--       UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART                 
--       UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND             
--       UPDATE top(1) @TBLSTART SET Speed =(SELECT MAX(SPEED) FROM @tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),                
--       idling=(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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9                 
--         AND CustomProp NOT LIKE '%Idling:0;%'),                
--        --Running=(SELECT ISNULL(SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,                
--        --(CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60,0)                             
--        --FROM @tblMessageForProcessingTrip                 
--        --WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =3)                
--        Running=DATEDIFF(S,@DTSTART,@DTEND)                
--        WHERE tripId=@INC AND StartTime=@DTSTART                 
                        
--       SET @INC =@INC +1                
                       
--       SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART                
--     END                 
                           
--    --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME                
--    UPDATE @TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END                 
--     WHERE Running IS NOT NULL                
                    
--    --INSERT THE DETAILS IN THE MASTER TABLE                
--    INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,                
--     OdometerEnd,IdlingDuration,Speed, IsTripClosed,StopTime,RunningTime,StartLat,StartLong,StopLat,StopLong)                 
--    SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,S.idling,                
--     S.Speed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running,S.Lat,S.Long,ST.Lat,ST.Long                
--      FROM @TBLSTART S                
--       INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId                          
                     
--   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping                
                   
--   UPDATE @tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM @tblTripDetailsForTD)         
  
    
      
        
         
                   
--   END                 
                
               
--   DECLARE @TBLSUMMARY TABLE                
--   (                
--  Boxid int,           
--  StartDate varchar(25),               
--  RunningTime int,                
--  IdlingTime int,                
--  StopTime int                
--   )                
--   INSERT INTO @TBLSUMMARY (Boxid,RunningTime,IdlingTime,StopTime)                
--   SELECT BoxId,SUM(ISNULL(RunningTime,0)),SUM(ISNULL(IdlingDuration,0)),SUM(ISNULL(StopTime,0)) FROM @tblTripDetailsForTD GROUP BY BoxId          
           
--   SELECT A.BoxId,CONVERT(varchar,StartDateSort,103) as OriginDate,dbo.rvlf_fn_getTimeFromSeconds(SUM(ISNULL(TripDuration,0))) as Duration,          
--   SUM(ISNULL(A.Distance,0)) as Distance,Count(TripId) as NoOfTrips,MIN(StartDateSort) as StartDate,MAX(EndDateSort) as EndDate,          
--   Max(CASE WHEN Speed = '-' THEN 0 ELSE CAST(Speed as int) END) as MaximumSpeed, dbo.rvlf_fn_getTimeFromSeconds(SUM(ISNULL(A.StopTime,0))) as StopTime,          
--   dbo.rvlf_fn_getTimeFromSeconds(SUM(ISNULL(A.IdlingDuration,0))) as IdlingDuration,MIN(A.OdometerStart) as OdometerStart,          
--   MAX(A.OdometerEnd) AS OdometerEnd,VIN,LicensePlate,VehicleDescription,MakeName,ModelName,ModelYear,          
--   Min(StartAddress) as StartAddress,Max(EndAddress) as EndAddress,          
--   dbo.rvlf_fn_getTimeFromSeconds(TS.IdlingTime) AS IdlingSummary,                
--   dbo.rvlf_fn_getTimeFromSeconds(TS.RunningTime) as RunningSummary,                
--   dbo.rvlf_fn_getTimeFromSeconds(Ts.StopTime) as StopSummary,          
--   @DistanceCaptionPrefix As DistanceCaption,          
--   @SpeedCaptionPrefix AS SpeedCaption,          
--   Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+          
--   ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate          
--   FROM (SELECT t.TripId,                
--   CASE WHEN CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))) > 0 AND Speed =0 THEN '-' ELSE CONVERT(VARCHAR,Speed) END Speed,                
--   t.BoxId,CONVERT(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)),@DefaultDateFormat)+ ' ' + CONVERT(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)) as time),22)  as StartDate,               
--   Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)),@DefaultDateFormat)+ ' ' + Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as time),22) as EndDate,                
--   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate))  as StartDateSort,               
--   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as EndDateSort,                   
--   CASE WHEN IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,                
--   dbo.rvlf_fn_getTimeFromSeconds(RunningTime) as Duration,                
--   RunningTime as TripDuration,                 
--   CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20)))as Distance,                 
--   StartAddress,CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END AS EndAddress  , --Vin, LicensePlate, VehDispName as VehicleDescription, MakeName, ModelName,ModelYear,                 
--   dbo.rvlf_fn_GetTimeFromSeconds(IdlingDuration) AS IdlingTime, IdlingDuration,                
--   CASE WHEN StopTime IS NULL THEN dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SS,EndDate , @dtEndDate))                 
--   WHEN StopTime =0 THEN '-'                
--   ELSE dbo.rvlf_fn_GetTimeFromSeconds(StopTime) END AS StopDuration,                
--   CASE WHEN StopTime IS NULL THEN ABS(DATEDIFF(SS,EndDate ,@dtEndDate)) ELSE StopTime END AS StopTime,                
--   @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,                
--   CEILING(CAST((ABS(ISNULL(t.OdometerStart, 0)) * @ConversionFactor) as varchar(20)))as OdometerStart,                
--   CEILING(CAST((ABS(ISNULL(t.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)))as OdometerEnd,                
--   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerStart, 0)) * @ConversionFactor) as varchar(20)),0,0) FROM @tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerStart ASC) As OdometerStartReading,                 
--   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)),0,0)FROM @tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerEnd DESC) AS OdometerEndReading,                
--   StartLat,StartLong,StopLat,StopLong FROM @tblTripDetailsForTD t) A                
--   INNER JOIN @TBLSUMMARY TS ON TS.Boxid =A.BoxId                 
--   INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON A.BoxId = va.BoxId                
--   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
--   LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId                
--   LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId               
--   GROUP BY CONVERT(varchar,A.StartDateSort,103),A.BoxId,VIN,LicensePlate,VehicleDescription,MakeName,ModelName,ModelYear,Ts.IdlingTime,Ts.RunningTime,Ts.StopTime          
--   Order By A.BoxId          
                       
--   SELECT VehicleName, Round(Distance,0)Distance                
--   FROM                
--   (                
--   select v.VehicleDescription VehicleName,                
--   CAST((MAX(isnull(OdometerEnd,0))-MIN(ISNULL(OdometerStart,0)))* @ConversionFactor as varchar(20))Distance--, CAST((ABS(ISNULL(SUM(OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as numeric(8,2)) as Distance                
--   from @tblTripDetailsForTD t                
--   INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON t.BoxId = va.BoxId                
--   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
--   Group By VehicleDescription)B Where CAST(Distance AS numeric(22,2)) > 0           
            
--  SET NOCOUNT OFF          
          
--END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_Sp_GetDeviceList_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_Sp_GetDeviceList_PhoneGap](           
@FleetID bigint=null,                                        
@bigUserID  bigint = 0,                                        
@bigVehicleId bigint = null,                                        
@bigOrganizationID bigint =NULL,
@Status tinyint=null                           
)                                                        
AS                                           
/******************************************************************************/                                        
-- Name  : rvlf_Sp_GetDeviceList_PhoneGap 176,1060,null,86,1                         
-- Description : To get the ESP details for monitor                                        
-- Company  : Angler Technologies                                        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
/******************************************************************************/                                                     
BEGIN 

if @bigOrganizationID Is null              
set @bigOrganizationID=(select organizationID from rvlfFleet where FleetId=@FleetID)
--DECLARE THE VARIABLES FOR GET THE TIMEZONE DETAILS                                    
DECLARE @HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@SpeedUnit varchar(50),@DefaultDateFormat INT = 0,@ConversionFactor numeric (10,2) = 1.0                                            
DECLARE @Lang varchar(50),  @LangSetting varchar(20)                                     
SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,--@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                                        
--@SpeedUnit = CASE WHEN up.Distance = 0 THEN 'MPH' ELSE 'KMPH' 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  = @bigUserID    

-------------------------------GET THE VEHICLES BASED ON THE FLEET ----------------------------------------------              
 SELECT * FROM (
	SELECT  B.MessageInID, MD.VehicleID, B.BoxID as DeviceID, Md.EquipmentName as VehicleDescription, VT.VehicleTypeName AS DeviceType, VT.VehicleTypeId AS  DeviceTypeId,MD.EquipmentName AS Devicename,
	ISNULL((SELECT FleetName FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From 
 rvlfFleetVehicles Where VehicleId = MD.VehicleId and FleetId <> 176)), 'Site Not Assigned') as SiteName, 
 ISNULL((SELECT FleetId FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From 
 rvlfFleetVehicles Where VehicleId = MD.VehicleId and FleetId <> 176)), '0') as SiteId,
 '' AS ControllerName, '' as ControllerPositionID, '' as dcsimid, 
					B.LastStreetAddress  as StreetAddress, CAST(ISNULL((Case WHEN @Lang='LanguageArNew' THEN ISNULL(B.LastStreetAddress_AR,B.LastStreetAddress) ELSE B.LastStreetAddress END),'Address is not resolved')AS NVARCHAR(MAX))  AS Address, 
			[DateTime] =dbo.rvlf_fn_DayLightSavings(GETDATE(),@bigUserID ,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,B.LastValidDateTime), 
		CASE WHEN B.LastLatitude = 0 AND B.LastLongitude = 0 AND B.LastValidDateTime = B.LastStatusDateTime THEN 
				0
			 WHEN B.LastValidDateTime = B.LastStatusDateTime THEN 
				1 
			ELSE 
				0 
			END as IsCurrent,                                           
	OriginDateTime = dbo.rvlf_fn_DayLightSavings(B.LastStatusDateTime,@bigUserID ,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,h.OriginDateTime),                             
	DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,B.LastStatusDateTime)) as OriginDateTimeSort,
	H.BoxMsgInTypeId,
		--CASE WHEN B.DeviceStatus =1 THEN 'Information'   
		--     WHEN B.DeviceStatus =2 THEN 'Warning'
		--	 WHEN B.DeviceStatus =3 THEN 'Electrical Trip'
		--	 WHEN B.DeviceStatus =4 THEN 'Shutdown'  
		--	 WHEN B.DeviceStatus =5 THEN 'Controlled Shutdown'
		--	 WHEN B.DeviceStatus =6 THEN 'Engine' 
		--	 Else '-'
		--	 END AS [Status],
		CASE WHEN VT.VehicleTypeId =1  THEN 
			  CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) >= 480  THEN 'Offline' 
			  WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND (SUBSTRING(ISNULL(h.Digital_OP,'0000000000000000'),10,1)='1') THEN 'Running' 
		     WHEN B.DeviceStatus =1 THEN 'Information'   
		     WHEN B.DeviceStatus =2 THEN 'Warning'
			 WHEN B.DeviceStatus =3 THEN 'Electrical Trip'
			 WHEN B.DeviceStatus =4 THEN 'Shutdown'  
			 WHEN B.DeviceStatus =5 THEN 'Controlled Shutdown'
			 WHEN B.DeviceStatus =6 THEN 'Engine' 			
			 Else '-'
			 END 
			 ELSE CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) >= 480  THEN 'Offline' 
			  WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND 
			  (SUBSTRING(ISNULL(hh.Digital_IP,'0000000000000000'),9,1)='1' OR SUBSTRING(isnull(hh.Digital_IP,'0000000000000000'),8,1) ='1')
			   THEN 'Running' 
		     WHEN B.DeviceStatus =1 THEN 'Information'   
		     WHEN B.DeviceStatus =2 THEN 'Warning'
			 WHEN B.DeviceStatus =3 THEN 'Electrical Trip'
			 WHEN B.DeviceStatus =4 THEN 'Shutdown'  
			 WHEN B.DeviceStatus =5 THEN 'Controlled Shutdown'
			 WHEN B.DeviceStatus =6 THEN 'Engine' 			
			 Else '-'
			 END END AS [Status],			 
			 DeviceStatus,
			 CASE WHEN VT.VehicleTypeId =1  THEN 
			  CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) >= 480  THEN 0
			  WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND (SUBSTRING(ISNULL(h.Digital_OP,'0000000000000000'),10,1)='1') THEN 7
		     WHEN B.DeviceStatus =1 THEN 1   
		     WHEN B.DeviceStatus =2 THEN 2
			 WHEN B.DeviceStatus =3 THEN 3
			 WHEN B.DeviceStatus =4 THEN 4 
			 WHEN B.DeviceStatus =5 THEN 5
			 WHEN B.DeviceStatus =6 THEN 6		
			 Else '-'
			 END 
			 ELSE CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) >= 480  THEN 0 
			  WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND 
			  (SUBSTRING(ISNULL(hh.Digital_IP,'0000000000000000'),9,1)='1' OR SUBSTRING(isnull(hh.Digital_IP,'0000000000000000'),8,1) ='1')
			   THEN 7
		     WHEN B.DeviceStatus =1 THEN 1  
		     WHEN B.DeviceStatus =2 THEN 2
			 WHEN B.DeviceStatus =3 THEN 3
			 WHEN B.DeviceStatus =4 THEN 4
			 WHEN B.DeviceStatus =5 THEN 5
			 WHEN B.DeviceStatus =6 THEN 6 			
			 Else '-'
			 END END AS StatusId,
			 B.LastLatitude, B.LastLongitude, ct.BoxMsgInTypeName as MessageDetails, h.CustomProp,
	CAST(B.LastLatitude as VARCHAR) + ',' + CAST(B.LastLongitude as VARCHAR) as LatLng,     
	CASE WHEN B.LastValidDateTime <> B.LastStatusDateTime THEN 
			 -1 
		 ELSE 
			 B.Heading 
		 END as Heading,
	 REPLACE(   
  ( 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.DeviceStatus =1 THEN 'Information' WHEN B.DeviceStatus =2 THEN 'Warning' WHEN B.DeviceStatus =3 THEN 'Electrical Trip' WHEN B.DeviceStatus =4 THEN 'Shutdown' WHEN B.DeviceStatus =5 THEN 'Controlled Shutdown' WHEN B.DeviceStatus =6 THEN 'Engine'  Else '-' END) AS VARCHAR) 
     + '~#~' + V.VehicleDescription  
     + '~#~' + ISNULL(ct.BoxMsgInTypeName,CTT.BoxMsgInTypeName)                          
     + '~#~' + '-'  + '~#~' + '-'                          
     + '~#~' + '-'     
     + '~#~' + '-'                             
     + '~#~' +  (Case WHEN @Lang='LanguageArNew' THEN N'اتصل'            
       When @Lang='LanguageHindi' THEN N'संपर्क'             
    ELSE 'Contact' END)+ '~#~' + '-'            
  )    
  , '''','\''')AS Mapitvalues,  
	
	 '' AS Notcurposveh, 
	(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 rvlfMAKDevices MD 
	inner join rvlfVehicle V on md.VehicleId=v.VehicleId     
	INNER JOIN rvlfFleetVehicles RFV ON MD.VehicleId = RFV.vehicleId
	INNER JOIN rvlfVehicleAssignment va ON va.VehicleId = V.VehicleId
	INNER JOIN rvlfBoxID B ON B.BoxID = MD.BoxId         
	LEFT OUTER JOIN rvlfMsgInHst_Techno h ON h.MessageInID = B.MessageInID
	LEFT OUTER JOIN rvlfMsgInHst_Techno_355 hh ON hh.MessageInID =B.MessageInId
	LEFT OUTER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId
	LEFT OUTER JOIN rvlfBoxMsgInType CTT ON hh.BoxMsgInTypeId = CTT.BoxMsgInTypeId	
	LEFT OUTER JOIN rvlfVehicleType VT On MD.SubTypeId = VT.VehicleTypeId                                        
	LEFT OUTER JOIN rvlfCustomers C On MD.CustomerId = C.CustomerId	
	WHERE (@FleetID IS NULL OR @FleetID = '' OR (RFV.FleetId = @FleetID)) and B.OrganizationID=@bigOrganizationID                                   
	AND (@bigVehicleId IS NULL or @bigVehicleId = '' OR MD.VehicleId= @bigVehicleId)
	) D WHERE (@Status IS NULL or @Status = ''  OR D.[StatusId]= @Status)  ORDER BY D.OriginDateTime desc
	 
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDeviceReportingStatus]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetDeviceReportingStatus]          
 @tiType AS TINYINT            
AS          
          
/******************************************************************************/          
-- Name  : rvlf_sp_GetDeviceReportingStatus 0        
-- Description : Fail Safe Mechanism - To get the device reporting status based on each Box Id and for whole organization          
-- Author  : Kumuthini. L          
-- Company  : Angler Technologies          
-- History  : 25-Dec-2010 Kumuthini.L Created Intial Version           
--   : 09-Aug-2011 Sakthi Check organization expired or not    
--   : 28-mar-2012 Vijay - Get the organization non reporting vehivle based on fleet.      
/******************************************************************************/          
          
BEGIN          
          
 IF NOT EXISTS (SELECT NotificationType FROM rvlfFailSafeNotification WHERE NotificationType = @tiType)          
 BEGIN          
            
  INSERT INTO rvlfFailSafeNotification (NotificationType, NotificationDate, IsNotificationSent)          
  VALUES (@tiType, GETUTCDATE(), 0)          
            
 END          
          
    IF @tiType = 0 -- If Messages are not reached the database for 1 hour for all org.          
    BEGIN          
            
  IF EXISTS (SELECT NotificationType FROM rvlfFailSafeNotification WHERE NotificationType = 0 AND NotificationDate = CONVERT(DATE, GETUTCDATE()))          
  BEGIN          
            
   UPDATE rvlfFailSafeNotification SET NotificationDate = DATEADD(DD, 1, GETUTCDATE()) WHERE NotificationType = 0          
   SELECT COUNT(MessageInID) AS Count FROM rvlfMsgInHst WHERE OriginDateTime BETWEEN DATEADD(HH, -1, GETUTCDATE()) AND GETUTCDATE()          
               
     END          
     ELSE          
     BEGIN          
               
   SELECT NULL AS Count          
               
     END          
                
    END          
    ELSE -- Check if any of the device not reported for more than 3 days          
    BEGIN          
              
  IF EXISTS (SELECT NotificationType FROM rvlfFailSafeNotification WHERE NotificationType = 1) --AND NotificationDate = CONVERT(DATE, GETUTCDATE()))          
  BEGIN          
             
   UPDATE rvlfFailSafeNotification SET NotificationDate = DATEADD(DD, 1, GETUTCDATE()) WHERE NotificationType = 1          
             
   -- Vehicle Reporting Status Notifications for Trinetra Admin for all Organizations          
   DECLARE @vcDeviceStatus VARCHAR(MAX) = NULL          
                
   SELECT @vcDeviceStatus = ISNULL(@vcDeviceStatus+'','') + ('<tr><td>' + o.OrganizationName + '</td>' +           
   '<td>' + v.VehicleDescription + ' (' + CONVERT(VARCHAR(6), ih.BoxId) + ')' + '</td>' +           
   '<td>' + CONVERT(VARCHAR(25), MAX(OriginDateTime), 100) + '</td>' +           
   '<td>' + CONVERT(VARCHAR(10),DATEDIFF(DD, MAX(OriginDateTime), GETUTCDATE())) + ' day(s)' + '</td></tr>')          
   FROM rvlfMsgInHst ih          
   INNER JOIN rvlfVehicleAssignment va ON va.BoxId = ih.BoxId           
   INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId          
   INNER JOIN rvlfOrganization o ON o.OrganizationId = v.OrganizationId          
   INNER JOIN rvlfOrganizationPackage OP ON OP.OrganizationID = o.OrganizationId        
   WHERE OP.ExpiresOn > GETDATE() AND OP.IsActive=1        
   GROUP BY o.OrganizationName, v.VehicleDescription, ih.BoxId, o.ExpiresOn, o.OrganizationId           
   HAVING DATEDIFF(DD, MAX(OriginDateTime), GETUTCDATE()) > 3 AND o.ExpiresOn >= CONVERT(DATE, GETDATE()) AND o.OrganizationId IN (86)          
   ORDER BY MAX(OriginDateTime) desc,ih.BoxId ASC          
             
   SELECT '<div><p><font face="arial" size="2px"><b>Dear All,</b><br /><br /><p>Below are the vehicle(s) which have not reported:</p>'          
     + '<table border="1" cellpadding="0" cellspacing="0" style="font-family: Arial; font-size: 12px; width: 817px; height: 152px;">'          
     + '<tbody><tr><td><strong><font face="arial" size="2px">Organization Name</font></strong></td><td>'          
     + '<strong><font face="arial" size="2px">Vehicle Name (Box ID)</font></strong></td><td>'          
     + '<strong><font face="arial" size="2px">Last Reported On</font></strong></td><td>'          
     + '<strong><font face="arial" size="2px">No. Of Days</font></strong></td></tr>'          
     + @vcDeviceStatus + '</tbody></table><p><font face="arial" size="2px"><b>Best Regards, </b></font></p>'          
     + '<p><a border="0" href="http://www.trinetrawireless.com/"><img border="0" src="http://www.trinetrawireless.com/images/logo.png" style="width: 100px; height: 36px;" /></a></p>'          
     + '<hr /><font face="arial" size="1px">This is system generated mail</font></div>' AS 'VehicleStatus'          
               
     -- Vehicle Reporting Status Notifications for Administrator of each Organization          
     SELECT u.Displayname, u.Email,f.FleetName,dbo.rvlf_fn_GetVehicleStatusNotification(O.OrganizationId, O.NotificationEffectiveFrom,f.FleetId) AS VehicleStatus          
     FROM rvlfOrganization O          
     INNER JOIN rvlfUser u ON u.OrganizationId = O.OrganizationId           
     INNER JOIN rvlfFleet F ON f.OrganizationId = O.OrganizationId    
     WHERE O.IsVehicleStatusNotification = 1 AND u.UserName = 'gopal' AND u.Email IS NOT NULL   and u.OrganizationId=86 and 1=0 
	 -- included 1=0 for avoiding multiple mails and not required when vehiclestatus reports
     AND O.NotificationEffectiveFrom IS NOT NULL        
     AND dbo.rvlf_fn_GetVehicleStatusNotification(O.OrganizationId, O.NotificationEffectiveFrom,f.FleetId) IS NOT NULL          
                   
     END          
     ELSE          
     BEGIN          
               
   SELECT NULL AS 'VehicleStatus'  
             
   SELECT NULL AS Displayname, NULL AS Email, NULL AS VehicleStatus          
               
     END          
              
    END          
          
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDeviceSensorsOutputs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetDeviceSensorsOutputs]
	@intBoxId int
AS
/**************************************************************************************/
--	Name		:	rvlf_sp_GetDeviceSensorsOutputs
--	Description	:	To get assinged and unassinged Sensors and Outputs for the Devices
--	Author		:	L. Kumuthini
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	16-Nov-2009		Created Intial Version 
--              :   
/*************************************************************************************/
BEGIN
	SET NOCOUNT ON 
	
    -- Get the assigned Sensors for a particular Box Id

	SELECT SensorId, SensorName, ActionOn, ActionOff FROM rvlfBoxSensorsCfg WHERE BoxId = @intBoxId
	
	-- Get the Unassigned Sensors for a particular Box Id
	 
	SELECT SensorId, SensorName, ActionOn, ActionOff FROM rvlfSensor 
	WHERE SensorId NOT IN (SELECT SensorId FROM rvlfBoxSensorsCfg WHERE BoxId = @intBoxId)

	-- Get the assigned Outputs for a particular Box Id
	
    SELECT * FROM rvlfOutput O
    INNER JOIN rvlfBoxOutputsCfg BO ON BO.OutputId = O.OutputId
    WHERE BO.BoxId = @intBoxId
    
    -- Get the Unassigned Outputs for a particular Box Id
    
    SELECT * FROM rvlfOutput WHERE OutputId NOT IN (SELECT OutputId FROM rvlfBoxOutputsCfg WHERE BoxId = @intBoxId)
         	
	
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDeviceSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetDeviceSettings]    
    
AS    
/******************************************************************************/    
-- Name  : rvlf_sp_GetDeviceSettings    
-- Description : To select the Box Protocol Type, Communication Mode,    
--                  Sensor Details, Output Details which is required for Device    
-- Author  : L. Kumuthini    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 13-Nov-2009  Created Intial Version     
--    : 26-Oct-2010 Populate Severity Template Details    
--   : 14-Jun-2011 Modified rvlfCommMode, to get total chunck  
/******************************************************************************/    
BEGIN    
SET NOCOUNT ON     
    
    SELECT BS.BoxId, BS.FwID, BS.BoxProtocolTypeId, BS.CommModeId,FC.FwCategotyName FwCategoryName,F.FwName, PT.BoxProtocolTypeName, CM.CommModeName,    
    O.OrganizationName,F.FwCategoryID, BT.CanDisplayTemp, BT.Temp1, BT.Temp2, BT.Temp3, BT.Temp4    
    FROM rvlfBoxSettings BS    
    LEFT OUTER JOIN rvlfBoxId B on B.BoxId =BS.BoxId    
    LEFT OUTER JOIN rvlfOrganization O on O.OrganizationId =B.OrganizationId    
    LEFT OUTER JOIN rvlfBoxProtocolType PT ON PT.BoxProtocolTypeId = BS.BoxProtocolTypeId    
    LEFT OUTER JOIN rvlfCommMode CM ON CM.CommModeId = BS.CommModeId    
    LEFT OUTER JOIN rvlfFirmware F ON F.FwId = BS.FwID    
    LEFT OUTER JOIN rvlfFirmwareCategory FC ON FC.FwCategoryID = F.FwCategoryID     
	LEFT OUTER JOIN rvlfBoxTempConfig BT ON B.BoxId = BT.BoxId
        
 SELECT BoxProtocolTypeId, BoxProtocolTypeName FROM rvlfBoxProtocolType    
     
 SELECT CM.CommModeId,CM.CommModeName,AP.TotalChunk FROM rvlfCommMode CM  
 LEFT OUTER JOIN rvlfApnSettings AP ON CM.CommModeId=AP.CommModeId  
     
 SELECT * FROM rvlfSensor    
     
 SELECT * FROM rvlfOutput    
     
 EXEC rvlf_sp_GetFirmwareVersions    
     
 EXEC rvlf_sp_GetSeverityTemplate    
     
 SELECT * FROM rvlfFirmwareCategory    
     
SET NOCOUNT OFF    
END    
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDeviceStats]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetDeviceStats]
	@bigBoxID varchar(15)=null,
	@bigOrganizationID bigint=null

AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetDeviceStats null,33
--	Description	:	To get the Vehicle Monitoring details
--				:   Pass the values to @bigVehicleID or @bigBoxID 
--	Author		:	V. Narayanasamy.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	11-Nov-2009	VN	Created Intial Version 
/******************************************************************************/
BEGIN

	SELECT v.VehicleId,v.VehicleDescription as VehicleName, v.VehicleDescription,
	   (CASE WHEN MessageIn>0 THEN MessageIn ELSE 0 END )AS MessageIn, 
	   (CASE WHEN MessageOut>0 THEN MessageOut ELSE 0 END )AS MessageOut, 
	   (CASE WHEN AcknowledgedMsg>0 THEN AcknowledgedMsg ELSE 0 END)AS AcknowledgedMsg, 
	   (CASE WHEN UnAcknowledgedMsg>0 THEN UnAcknowledgedMsg ELSE 0 END)AS UnAcknowledgedMsg,
	   ISNULL(BoxProtocolTypeName,'-')AS BoxProtocolTypeName,
	   ISNULL(CommModeName,'-')AS CommModeName,
	   ISNULL(CommAddressTypeName,'-')AS CommAddressTypeName,
	   ISNULL(ServiceName,'-')AS ServiceName,
	   ISNULL (SystemInstalled,'-')AS SystemInstalled ,
	   ISNULL(BoxId,0)AS BoxId,
	   ISNULL (FwName,'-')AS FwName
	  
			
		FROM(SELECT COUNT(h.MessageInID) AS MessageIn, MessageOut, AcknowledgedMsg,
				   UnAcknowledgedMsg,VehicleId, VehicleDescription, BoxProtocolTypeName, 
				   CommModeName, CommAddressTypeName,ServiceName, SystemInstalled, 
				   a.BoxId,FwName 
				
				FROM (SELECT COUNT(mo.BoxId)as MessageOut,
					  SUM(CASE WHEN mo.Acknowledged=1 THEN 1 END)AS AcknowledgedMsg,
					  SUM(CASE WHEN mo.Acknowledged=0 THEN 1 END)AS UnAcknowledgedMsg, 
					  v.VehicleId,v.VehicleDescription,va.boxid,bp.BoxProtocolTypeName,
					  cm.CommModeName,ca.CommAddressTypeName,s.ServiceName,
					  s.SystemInstalled,f.FwName 
				   
					FROM rvlfVehicle  v
				
						INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId 
						INNER JOIN rvlfBoxSettings bs ON bs.BoxId=va.BoxId 
						INNER JOIN rvlfFirmware f ON f.FwId=bs.FwID 
						INNER JOIN rvlfBoxProtocolType bp ON bp.BoxProtocolTypeId=bs.BoxProtocolTypeId 
						INNER JOIN rvlfCommMode cm ON cm.CommModeId=bs.CommModeId 
						INNER JOIN rvlfServices s ON s.CommModeId=bs.CommModeId 
						INNER JOIN rvlfCommModeAddressType  cma ON cma.CommModeId=bs.CommModeId 
						INNER JOIN rvlfCommAddressType ca ON ca.CommAddressTypeId =cma.CommAddressTypeId 
						LEFT OUTER JOIN rvlfMsgOutHst mo ON MO.BoxId=bs.BoxId 
						
					WHERE ((@bigBoxID IS NULL) OR @bigBoxID='' OR (va.BoxId=@bigBoxID))
							AND ((@bigOrganizationID IS NULL) OR @bigOrganizationID='' OR(v.OrganizationId=@bigOrganizationID))
					GROUP BY v.VehicleId,v.VehicleDescription,va.boxid,
							 bp.BoxProtocolTypeName,cm.CommModeName,ca.CommAddressTypeName,
							 s.ServiceName,s.SystemInstalled,f.FwName)as a
					   
				LEFT OUTER JOIN rvlfMsgInHst h ON h.BoxId = a.BoxId
						
				GROUP BY MessageOut, AcknowledgedMsg, UnAcknowledgedMsg,VehicleId, 
						 VehicleDescription, BoxProtocolTypeName,CommModeName, 
						 CommAddressTypeName,ServiceName, SystemInstalled, a.BoxId,FwName)AS b
						 
			RIGHT OUTER JOIN rvlfVehicle v ON v.VehicleId =b.VehicleId 
						 
		WHERE ((@bigBoxID IS NULL) OR @bigBoxID='' OR (B.BoxId=@bigBoxID))
							AND ((@bigOrganizationID IS NULL) OR @bigOrganizationID='' OR(v.OrganizationId=@bigOrganizationID))

END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDrillDownDistanceChart]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetDrillDownDistanceChart]    

 @VehicleDesc nvarchar(max) = NULL,    
 @bigOrganizationID bigint = NULL,    
 @bigQueryingUser bigint = NULL,
 @dtStartDate datetime = Null,    
 @dtEndDate datetime = NULL,
 @bigFleetID bigint = null,
 @bigLastDays bigint = null 
 
AS  
/********************************************************************************************************    
-- Name		   : rvlf_sp_GetDrillDownDistanceChart 'Veh_999980',6,322,'8/1/2016 8:59:02 AM','8/3/2016 8:59:02 AM',8,48
-- Description : To get the Critical Alerts details  for Drill down chart      
-- Author      : Ranjith N 
-- History     :       
*********************************************************************************************************/ 
BEGIN    
 SET NOCOUNT ON 
  DECLARE @HoursToBeAdded INT = 0            
 DECLARE @MinsToBeAdded INT = 0            
 DECLARE @ConversionFactor numeric (10,2) = 1.0            
 DECLARE @DistanceCaptionPrefix varchar(15)            
 DECLARE @SpeedCaptionPrefix varchar(15)          
 DECLARE @DefaultDateFormat INT = 0;              
    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,@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 = @bigQueryingUser            

--select b.BoxMsgInTypeName,COUNT(b.BoxMsgInTypeId) as NoofAlarms from rvlfBoxMsgSeverity a
--inner join rvlfBoxMsgInType b on a.BoxMsgInTypeId=b.BoxMsgInTypeId 
--inner join rvlfVehicleAssignment c on c.BoxId=a.BoxId
--inner join rvlfVehicle d on d.VehicleId=c.VehicleId 
-- and a.AlarmLevelID=3 and d.VehicleDescription = @VehicleDesc and d.OrganizationId=@bigOrganizationID   --a.BoxId=1
--group by  b.BoxMsgInTypeName 

	--select  (case when len(mt.BoxMsgInTypeName)> 15 then (SUBSTRING(mt.BoxMsgInTypeName,1,12) + '...') else mt.BoxMsgInTypeName end) as BoxMsgInTypeName, isnull(SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END),0) as NoofAlarms from rvlfAlarm a
	--	inner join rvlfVehicleAssignment v on v.BoxId=a.BoxId
	--	inner join rvlfVehicle vi on vi.VehicleId =v.VehicleId
	--	inner join rvlfBoxMsgSeverity ms on ms.BoxId = a.BoxId
	--	inner join rvlfBoxMsgInType mt on mt.BoxMsgInTypeId = ms.BoxMsgInTypeId
	--	INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId  
	--	where	   
	--	   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR vi.OrganizationId = @bigOrganizationID) AND 
 --          (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and  
	--		a.DateTimeCreated between @dtStartDate and @dtEndDate  and 
	--		a.AlarmLevelId =3 and 
	--		vi.VehicleDescription =@VehicleDesc 
	--		and ms.BoxMsgInTypeId = a.AlarmType 
	--		--vi.OrganizationId = @bigOrganizationID
	--	group by a.AlarmLevelId,mt.BoxMsgInTypeName
	 declare @Lang varchar(50)   
    select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser

		--select  (case when len(mt.BoxMsgInTypeName)> 15 then (SUBSTRING(mt.BoxMsgInTypeName,1,12) + '...') else mt.BoxMsgInTypeName end) as BoxMsgInTypeName, isnull(SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END),0) as NoofAlarms,mt.BoxMsgInTypeName as BoxMsgTypeName from rvlfAlarm a
		--inner join rvlfVehicleAssignment v on v.BoxId=a.BoxId
		--inner join rvlfVehicle vi on vi.VehicleId =v.VehicleId
		--INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId  		
		--inner join rvlfBoxMsgInType mt on a.AlarmType=mt.BoxMsgInTypeId 
		
		--where	   
		--   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR vi.OrganizationId = @bigOrganizationID) AND
  --          (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and
		--	a.DateTimeCreated between @dtStartDate and @dtEndDate  and 
		--	a.AlarmLevelId =3 and 
		--	(case when @Lang='LanguageArNew' then  isnull(vi.VehicleDescription_Ar,vi.VehicleDescription ) else vi.VehicleDescription  end) = @VehicleDesc			
		--	and a.AlarmType = mt.BoxMsgInTypeId --and a.Description like '%Alarm%'
		--	--vi.OrganizationId = @bigOrganizationID
		--group by a.AlarmType, mt.BoxMsgInTypeName


  DECLARE @tblIdlingInfo table  
  (  
   BoxID int,  
   VehicleDescription nvarchar(50),  
   VehicleName nvarchar(50),  
   IdlingTime int,  
   RunningTime int,  
   Distance int  
  )  
 
  DECLARE @tblMessageForProcessingTrip table (            
  [OriginDateTime] [datetime] NOT NULL,            
  [BoxMsgInTypeId] [tinyint] NULL,            
  [CustomProp] [varchar](600) NULL,              
  [Speed] int NULL,            
  [Ignition] bit null,
  [OdoMeter] bigint null       
 ) 
   Declare  @TBLSTART Table            
 (            
  Processid bigint identity(1,1),            
  Boxid int,            
  StartTime datetime,            
  OdoStart bigint,
  Running int,            
  idling int,            
  Speed int,            
  StopInterval int,            
  tripId int          
 )            
             
 Declare  @TBLSTOP   Table     
 (            
  Boxid int,            
  StopTime datetime,            
  OdoEnd bigint,
  tripId int,
 IsTripCompleted bit            
 )   

Declare   @tblTripDetailsForTD TABLE(            
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,            
  [BoxId] [int] NOT NULL,            
  [StartDate] [datetime] NOT NULL,            
  [EndDate] [datetime] NULL,            
  [OdometerStart] [bigint] NOT NULL,            
  [OdometerEnd] [bigint] NULL,            
  [IsTripClosed] [bit] NULL,            
  [IdlingDuration] [int] NULL,            
  [StopTime] [int] NULL,
  [Speed] int NULL,            
  [RunningTime] int null            
        
 )   
  INSERT INTO @tblIdlingInfo (BoxID, VehicleDescription, VehicleName)              
    SELECT va.BoxId , v.VehicleDescription  AS VEH,v.VehicleDescription as VehicleDescription  
          FROM rvlfVehicleAssignment va   
           INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
           INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
          WHERE(v.OrganizationId = @bigOrganizationID)   
           AND (fv.FleetId = @bigFleetID) AND
		   v.VehicleDescription  = @VehicleDesc	           
    
  DECLARE @intBoxLooping INT =(SELECT MIN(BoxID) FROM @tblIdlingInfo)  
    
  WHILE @intBoxLooping IS NOT NULL  
   BEGIN  
    
    -- GET THE MSGS FOR THE BOXID            
    DELETE FROM @tblMessageForProcessingTrip                 
    INSERT INTO @tblMessageForProcessingTrip(OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,OdoMeter)            
      SELECT  h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,
      CASE WHEN @bigOrganizationID=23 AND BoxMsgInTypeId=2 AND CustomProp like 'SENSOR_NUM=2;%' THEN 1 ELSE CAST(SUBSTRING(sensormask,6,1) as bit) END,             
      CASE WHEN Odometer > 0 THEN Odometer ELSE 0 END                      
       FROM rvlfMsgInHst H            
        LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID                                      
       WHERE h.BoxID = @intBoxLooping AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate    
        ORDER BY h.origindatetime ASC             
                    
    -- GET THE IGNITION ON DETAILS            
    DELETE FROM @TBLSTART                 
    INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart)            
    SELECT @intBoxLooping,OriginDateTime,OdoMeter             
     FROM @tblMessageForProcessingTrip                   
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
      AND BoxMsgInTypeId IN(2)            
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)            
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)              
      AND Ignition=1 AND (@bigOrganizationID <> 23 OR (@bigOrganizationID=23 AND CustomProp LIKE '%SENSOR_NUM=2%'))
      --AND CustomProp LIKE '%SENSOR_NUM=3%'            
                   
                 
    --GET THE IGNITION OFF DETAILS               
    DELETE FROM @TBLSTOP             
    INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd)            
    SELECT @intBoxLooping,OriginDateTime,OdoMeter                
     FROM @tblMessageForProcessingTrip              
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
      AND BoxMsgInTypeId IN(3)            
      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)            
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip             
       WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)              
       AND (@bigOrganizationID <> 23 OR (@bigOrganizationID=23 AND CustomProp LIKE '%SENSOR_NUM=2%'))
                
    --CHECK THE ONGOING TRIPS             
    --IF ((SELECT TOP 1 BoxMsgInTypeId FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) ORDER BY OriginDateTime DESC)=2)            
    -- BEGIN            
    --  INSERT INTO #TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)            
    --   SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long             
    --    FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC                 
    -- IF EXISTS(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)            
    --    AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime            
    --    FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC)                    
    --  BEGIN                    
    --   INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long,IsTripCompleted)            
    --    --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,OdoMeter,Address,Lat,Long,0             
    --    SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long,0             
    --    FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)            
    --     AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime            
    --     FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC            
    --  END             
    -- ELSE            
    --  BEGIN            
    --   INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)            
    --    --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                     
    --    SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                     
    --  END              
    -- END            
                     
    --PREPARE THE TRIPS AND DETAILS                
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )             
    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 @TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                
                  
      IF @DTSTOPSTART IS NOT NULL                     
       UPDATE top(1) @TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART             
                  
      SET @DTSTOPSTART=@DTSTART             
      SET @DTEND=NULL            
      SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART           
                  
      UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART             
      UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND              
      UPDATE top(1) @TBLSTART SET Speed =(SELECT MAX(SPEED) FROM @tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),            
      idling=(SELECT SUM(ISNULL(CAST([dbo].[rvlf_fn_GetParamValueWithIndex](CustomProp,'Idling:',';') AS INT),0))        
       FROM @tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9             
        AND CustomProp NOT LIKE '%Idling:0;%'),            
       --Running=(SELECT ISNULL(SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,            
       --(CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60,0)                         
       --FROM #tblMessageForProcessingTrip             
       --WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =3)            
       Running=DATEDIFF(S,@DTSTART,@DTEND)            
       WHERE tripId=@INC AND StartTime=@DTSTART             
                   
      SET @INC =@INC +1            
                  
      SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART            
                  
     END             
                       
    --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME            
    UPDATE @TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END             
     WHERE Running IS NOT NULL            
                
    --INSERT THE DETAILS IN THE MASTER TABLE            
    INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,OdometerStart,            
     OdometerEnd,IdlingDuration,Speed, IsTripClosed,StopTime,RunningTime)             
    SELECT S.Boxid,S.StartTime,ST.StopTime,S.OdoStart,ST.OdoEnd,S.idling,            
     S.Speed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running            
      FROM @TBLSTART S            
       INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId                      
                 
   SELECT @intBoxLooping = MIN(BoxID) from @tblIdlingInfo WHERE BoxID > @intBoxLooping            
               
   UPDATE @tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM @tblTripDetailsForTD)           
   
    
  END  
  
  DECLARE @TBLSUMMARY TABLE            
  (            
   Boxid int,
   Distance bigint,
   IdlingInstances bigint                  
  )            
 INSERT INTO @TBLSUMMARY (Boxid,Distance)            
 SELECT BoxId,SUM(OdometerEnd-OdometerStart) FROM @tblTripDetailsForTD t where t.IsTripClosed = 1 GROUP BY BoxId             

 DECLARE @intBoxLooping1 INT =(SELECT MIN(BoxID) FROM @TBLSUMMARY)      
  WHILE @intBoxLooping1 IS NOT NULL  
   BEGIN
	update  @TBLSUMMARY set IdlingInstances  =
	isnull((SELECT count(BoxId) FROM @tblTripDetailsForTD t 
		where t.IsTripClosed = 1 and IdlingDuration is not null and BoxID = @intBoxLooping1  GROUP BY BoxId),0) 
	 where BoxID = @intBoxLooping1
	 
    SELECT @intBoxLooping1 = MIN(BoxID) from @TBLSUMMARY WHERE BoxID > @intBoxLooping1            
  END  

  Declare   @tblTripDetailsFinal TABLE(            
  [TripId] [bigint] NOT NULL,            
  [BoxId] [int] NOT NULL,              
  [Distance] [bigint] NOT NULL, 
  [SeriesDateVal] varchar(50) NOT NULL,
  [VehicleDescription] varchar(500) NOT Null  
 ) 
 insert into @tblTripDetailsFinal
 select a.TripId,a.BoxId,ceiling(a.OdometerEnd-a.OdometerStart) as Distance,FORMAT(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.EndDate)),'dd-MMM-yy hh:mm tt') as SeriesDateVal,b.VehicleDescription 
 from @tblTripDetailsForTD a
 inner join  @tblIdlingInfo b on b.BoxId = a.BoxId
 where a.IsTripClosed = 1 and a.OdometerStart <> a.OdometerEnd order by a.TripId

 select * from @tblTripDetailsFinal


 SET NOCOUNT OFF    
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriver]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE Procedure [dbo].[rvlf_sp_GetDriver]    
 @bigDriverId bigint = Null,     
 @bigOrganizationID bigint = null,    
 @bigUserId  bigint = null           
AS    
/******************************************************************************/    
-- Name  : [rvlf_sp_GetDriver] '',183,303
-- Description : To get the active driver details    
-- Author  : V.Narayanasamy    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 21-Jun-2010 VN Created Intial Version     
/******************************************************************************/    
BEGIN    
 SELECT DriverId,DriverName,Gender,DateOfBirth,PermanentAddress,MailingAddress,PhoneNo,MobileNo,DisplayName,Insurance,InsuranceExpiresOn,    
   LicenseNo,CONVERT(varchar,LicenseExpiresOn,103)as LicenseExpiresOn,TotalYearsOfExperience,NoOfAccidents,DateOfJoin,Photo,NoOfHoursDrived,Active  FROM rvlfDriverMaster     
  WHERE ((@bigDriverId IS NULL OR @bigDriverId='') OR @bigDriverId='' OR DriverId=@bigDriverId)     
   AND((@bigOrganizationID IS NULL OR @bigOrganizationID='') OR OrganizationID=@bigOrganizationID)     
   AND(Active=1) AND(ISDELETE=0)    
   AND((LicenseExpiresOn>=CONVERT(DATE,GETDATE())) OR LicenseExpiresOn IS NULL)   
   AND((CONVERT(DATE,DateOfJoin)<=CONVERT(DATE,GETDATE())) OR DateOfJoin IS NULL)
END    




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriver_Command]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    
    
      
CREATE Procedure [dbo].[rvlf_sp_GetDriver_Command]       
 @bigOrganizationID bigint = null,    
 @bigUserId  bigint = null,    
 @bigMode int = null,    
 @bigBoxId bigint=null,  
 @VarFingerPrintKey varchar(20) = Null,   
 @VarFingerPrintName varchar(20) = Null,   
 @VarUsername varchar(50) =null  
AS      
/******************************************************************************/      
-- Name  : [rvlf_sp_GetDriver_Command] 6 ,19  ,2    
-- Description : To get the active driver details      
-- Author  : N.Ranjith    
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--    : 11-Jun-2013 Ranjith Created Intial Version       
/******************************************************************************/      
BEGIN      
declare @Lang varchar(50)       
  select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigUserId    
  if @bigMode = 1    
   Begin    
  Select IButtonKey,IButtonKeyName from rvlfIButtonMapping where boxid =@bigBoxId and KeyType = 4 and OrganizationId= @bigOrganizationID  
   End       
   --Checking duplicate Ibutton Name Entry            
   else if @bigMode =2  
   begin            
    select * from rvlfIButtonMapping where lower(replace(IButtonKeyName,' ',''))=lower(replace(@VarFingerPrintName,' ',''))             
           and OrganizationId=@bigOrganizationID and  BoxID =@bigBoxId and KeyType =4    
              
          Declare @MaxFingerId bigint = 0  
    SET @MaxFingerId = (SELECT MAX(cast(isnull(IButtonKey,0) as int)) FROM rvlfIButtonMapping where boxid =@bigBoxId and KeyType = 4 and OrganizationId= @bigOrganizationID)  
    Select isnull(@MaxFingerId,0)+1 as NewFingerID       
   end      
   else if @bigMode = 3    
   Begin     
  Declare @MaxId bigint = 0  
  SET @MaxId = (SELECT MAX(cast(isnull(IButtonKey,0) as int)) FROM rvlfIButtonMapping where boxid =@bigBoxId and KeyType = 4 and OrganizationId= @bigOrganizationID)    
  Insert into rvlfIButtonMapping(BoxID,DriverId,IButtonKey,IButtonKeyName,KeyType,OrganizationId,UserName)  
  Values(@bigBoxId,null,isnull(@MaxId,0)+1,@VarFingerPrintName,4,@bigOrganizationID,@VarUsername)  
   End    
   else if @bigMode = 4    
   Begin     
  Update rvlfIButtonMapping set IButtonKey = @VarFingerPrintKey,IButtonKeyName =@VarFingerPrintName where boxid =@bigBoxId and IButtonKey = @VarFingerPrintKey and KeyType = 4 and OrganizationId= @bigOrganizationID  
   End    
   else if @bigMode = 5    
   Begin     
  Delete from rvlfIButtonMapping where boxid =@bigBoxId and IButtonKey = @VarFingerPrintKey and KeyType = 4 and OrganizationId= @bigOrganizationID  
   End    
   else if @bigMode = 6  
   Begin     
  Delete from rvlfIButtonMapping where boxid =@bigBoxId and KeyType = 4 and OrganizationId= @bigOrganizationID  
   End    
           
END      
    
    
    
--  ALTER Procedure [dbo].[rvlf_sp_GetDriver_Command]       
-- @bigOrganizationID bigint = null,    
-- @bigUserId  bigint = null,    
-- @bigMode int = null,    
-- @bigBoxId bigint=null,  
-- @VarIButtonName varchar(20) = Null,  
-- @BigDriverID bigint=null,  
-- @VarUsername varchar(50) =null  
--AS      
--/******************************************************************************/      
---- Name  : [rvlf_sp_GetDriver_Command] 6 ,140  ,2    
---- Description : To get the active driver details      
---- Author  : N.Ranjith    
---- Company  : Angler Technologies      
---- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
----    : 11-Jun-2013 Ranjith Created Intial Version       
--/******************************************************************************/      
--BEGIN      
--declare @Lang varchar(50)       
--  select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigUserId    
--  if @bigMode = 1    
--   Begin    
--  --select drivername,cast(DriverId as varchar(50))+ ',1' as FingerKey from rvlfDriverMaster where DriverId not in (select distinct isnull(DriverId,0) from rvlfIButtonMapping where OrganizationId = @bigOrganizationID and KeyType =4)     
--  --and (OrganizationID=@bigOrganizationID)       
--  --AND(Active=1) AND(ISDELETE=0) AND(LicenseExpiresOn>=CONVERT(DATE,GETDATE())) AND(CONVERT(DATE,DateOfJoin)<=CONVERT(DATE,GETDATE()))           
--  select D.Drivername,cast(d.DriverId as varchar(50))+ ',' + ib.IButtonKey as FingerKey  from rvlfDriverMaster d    
--  left outer join rvlfIButtonMapping ib on d.DriverId = isnull(ib.DriverId,0)    
--  where d.DriverId in (select distinct isnull(DriverId,0) from rvlfIButtonMapping where OrganizationId = @bigOrganizationID and KeyType =4)     
--  and (d.OrganizationID=@bigOrganizationID) and ib.OrganizationId = @bigOrganizationID    
--  AND(Active=1) AND(ISDELETE=0) AND(LicenseExpiresOn>=CONVERT(DATE,GETDATE())) AND(CONVERT(DATE,DateOfJoin)<=CONVERT(DATE,GETDATE()))    
--   End    
--   else if @bigMode = 2    
--   Begin    
--  --select drivername,DriverId from rvlfDriverMaster where DriverId in (select distinct isnull(DriverId,0) from rvlfIButtonMapping where OrganizationId = @bigOrganizationID)     
--  --   and (OrganizationID=@bigOrganizationID)       
--  --AND(Active=1) AND(ISDELETE=0) AND(LicenseExpiresOn>=CONVERT(DATE,GETDATE())) AND(CONVERT(DATE,DateOfJoin)<=CONVERT(DATE,GETDATE()))           
--  select D.Drivername,cast(d.DriverId as varchar(50))+ ',' + ib.IButtonKey as FingerKey  from rvlfDriverMaster d    
--  left outer join rvlfIButtonMapping ib on d.DriverId = isnull(ib.DriverId,0)    
--  where d.DriverId in (select distinct isnull(DriverId,0) from rvlfIButtonMapping where OrganizationId = @bigOrganizationID and KeyType =4)     
--  and (d.OrganizationID=@bigOrganizationID) and ib.OrganizationId = @bigOrganizationID and ib.BoxID =@bigBoxId and ib.KeyType =4    
--  AND(Active=1) AND(ISDELETE=0) AND(LicenseExpiresOn>=CONVERT(DATE,GETDATE())) AND(CONVERT(DATE,DateOfJoin)<=CONVERT(DATE,GETDATE()))     
--   End    
--   else if @bigMode = 3    
--   Begin     
--  select IButtonKey from rvlfIButtonMapping where OrganizationId = @bigOrganizationID and BoxID =@bigBoxId and KeyType =4     
--   End       
--   --Checking duplicate Ibutton Name Entry            
--   else if @bigMode =4            
--   begin            
--    select * from rvlfIButtonMapping where lower(replace(IButtonKeyName,' ',''))=lower(replace(@VarIButtonName,' ',''))             
--           and OrganizationId=@bigOrganizationID and  BoxID =@bigBoxId and KeyType =4          
--   end      
--   else if @bigMode = 5    
--   Begin     
--  Declare @MaxId bigint = 0  
--  SET @MaxId = (SELECT MAX(cast(isnull(IButtonKey,0) as int)) FROM rvlfIButtonMapping where boxid =@bigBoxId and KeyType = 4 and OrganizationId= @bigOrganizationID)    
--  Insert into rvlfIButtonMapping(BoxID,DriverId,IButtonKey,IButtonKeyName,KeyType,OrganizationId,UserName)  
--  Values(@bigBoxId,@BigDriverID,isnull(@MaxId,0)+1,@VarIButtonName,4,@bigOrganizationID,@VarUsername)  
--   End    
--   else if @bigMode = 6    
--   Begin     
--  Update rvlfIButtonMapping set DriverId=@BigDriverID,IButtonKey = @VarIButtonName,IButtonKeyName =@VarIButtonName where boxid =@bigBoxId and DriverId=@BigDriverID and IButtonKey = @VarIButtonName and IButtonKeyName =@VarIButtonName and KeyType = 4 and OrganizationId= @bigOrganizationID  
--   End    
--   else if @bigMode = 7    
--   Begin     
--  Delete from rvlfIButtonMapping where boxid =@bigBoxId and DriverId=@BigDriverID and IButtonKey = @VarIButtonName and IButtonKeyName =@VarIButtonName and KeyType = 4 and OrganizationId= @bigOrganizationID  
--   End    
           
--END      

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverActivity]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetDriverActivity]  
 @dtStartDate datetime = '2010-06-01',  
 @dtEndDate datetime = '2010-07-30',  
 @bigOrganizationID bigint = 6,  
 @bigQueryingUser bigint = 17,  
 @bigDriverGroupID bigint = NULL,  
 @bigDriverID bigint = 2,  
 @bigFleetID bigint = 8,  
 @intBoxID int = null,  
 @vcDrivers varchar(25) = null  
  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetDriverActivity @bigDriverID =2, @bigOrganizationID = 6, @dtStartDate='2010-06-01', @dtEndDate='2010-07-30', @bigQueryingUser = 17  
-- Description : To get the Driver Activity Details  
-- Author  : S.Jeyanthi  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 27-Sep-2010 SJ Created Intial Version --      
/******************************************************************************/  
BEGIN  
 Select * from rvlfDriverActivityReport  
-- SET NOCOUNT ON  
   
-- DECLARE @tblDriverActity Table  
-- (AcivityID bigint identity (1,1), DriverGroupID bigint,  
--   DriverID bigint,VehicleID bigint, VehDisplayName varchar(20),  
--   RouteName nvarchar(50),FromTime nvarchar(50),ToTime DateTime,  
--   AssignedBy bigint, AssignedDate dateTime     
-- )  
   
-- --DECLARE @tblDriverGroup Table(ID bigint identity (1,1), DriverGroupID bigint,DriverGroup nvarchar(100))   
-- --DECLARE @tblDrivers Table(ID bigint identity (1,1), DriverID bigint, DriverName nvarchar(50))   
-- --DECLARE @tblVehicle Table(ID bigint identity (1,1), VehicleID bigint,VehicleName nvarchar(50))  
-- --DECLARE @tblRoute Table(ID bigint identity (1,1), RouteID bigint,RouteName nvarchar(50),LandMarkFromID bigint,LandMarkFrom nvarchar(50), LandMarkToId bigint,LandMarkTo nvarchar(50))   
   
-- --INSERT INTO @tblDriverGroup  
-- --SELECT DriverGroupId,DriverGroupName from rvlfDriverGroupMaster where OrganizationId=@bigOrganizationID   
   
-- --INSERT INTO @tblDrivers  
-- --SELECT DriverId,DriverName from rvlfDriverMaster where OrganizationId=@bigOrganizationID   
   
-- --INSERT INTO @tblVehicle  
-- --SELECT VehicleId,VehicleDescription  from rvlfVehicle where OrganizationId=@bigOrganizationID   
     
-- --INSERT INTO @tblRoute(RouteID,RouteName)  
-- --SELECT R.RouteID,RouteName  from rvlfRouteMaster R   
-- --where OrgID=6 and RouteID =14  
   
-- --Update @tblRoute Set LandMarkFromID=(Select top 1 LndID from rvlfRouteDetails where RouteID=14 order by RouteDetailsId asc ) where RouteID=14  
-- --Update @tblRoute Set LandMarkToID=(Select top 1 LndID from rvlfRouteDetails where RouteID=14 order by RouteDetailsId DESC ) where RouteID=14  
  
-- --Update @tblRoute Set LandMarkFrom=(Select LandmarkName from rvlfLandmark  where LandmarkID=61 ) where RouteID=14  
-- --Update @tblRoute Set LandMarkTo=(Select LandmarkName from rvlfLandmark where  LandmarkID=58) where RouteID=14  
  
--------- Included to get the user prefernces---------------------  
-- DECLARE @HoursToBeAdded INT = 0  
-- DECLARE @MinsToBeAdded INT = 0  
-- DECLARE @DistanceCaptionPrefix varchar(15)  
-- DECLARE @SpeedCaptionPrefix varchar(15)  
-- 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 ,  
--     @DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(in Miles)' ELSE '(in Kms)' END,  
--     @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(in MPH)' ELSE '(in KMPH)' END  
--    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz  
--    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser  
  
--    SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))  
-- SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))  
   
   
-- IF @bigFleetID is null  
--  BEGIN  
--   SELECT @bigFleetID = FleetID FROM rvlfFleet where IsDefault= 1 and OrganizationId = @bigOrganizationID  
--  END  
  
-- DECLARE @tblDriverActivity table (ActivityID bigint identity (1,1),   
--   DriverID bigint,VehicleID bigint,AssignedFrom DateTime,  
--   AssignedTo DateTime, VehDisplayName varchar(20), BoxId int, RouteName nvarchar(50),  
--   LandMarkFrom nvarchar(50), LandMarkTo nvarchar(50))  
  
-- DECLARE @tblMessages table(  
--  [MessageInID] [uniqueidentifier] NOT NULL,  
--  [BoxId] [int] NOT NULL,  
--  [OriginDateTime] [datetime] NULL,  
--  [DateTimeReceived] [datetime] NULL,  
--  [BoxMsgInTypeDesc] [varchar](50) NOT NULL,  
--  [BoxMsgInTypeId] [tinyint] NOT NULL,  
--  [CommInfo1] [varchar](15) NULL,  
--  [CommInfo2] [int] NULL,  
--  [Latitude] [decimal](10, 6) NULL,  
--  [Longitude] [decimal](10, 6) NULL,  
--  [Speed] [int] NULL,  
--  [Heading] [smallint] NULL,  
--  [SensorMask] [varchar](max) NULL,  
--  [CustomProp] [varchar](600) NULL,  
--  [StreetAddress] [varchar](250) NOT NULL,  
--  [IsArmed] [bit] NULL,  
--  [NearestLandmark] [varchar](300) NULL,  
--  [Priority] [tinyint] NULL,  
--  [Vin] [varchar](20) NULL,  
--  [LicensePlate] [varchar](20) NULL,  
--  [Email] [varchar](2010) NULL,  
--  [SMS] [varchar](160) NULL,  
--  [VehicleID] [bigint],  
--  [VehicleDescription] [varchar](50) NULL,  
--  [VehDisplayName] [varchar](20) NULL,  
--  [OrganizationId] [bigint] NULL,  
--  [NotificationType] [varchar](22) NOT NULL,  
--  [Duration] [varchar](max) NULL,  
--  [FleetName] [varchar](100) NOT NULL,  
--  [OrganizationName] [varchar](200) NOT NULL,  
--  [DistanceCaption] [varchar](10) NOT NULL,  
--  [SpeedCaption] [varchar](10) NOT NULL,  
--  [MessageDetails] [varchar](max) NULL,  
--  [DriverID] bigint  
-- )   
  
--    INSERT INTO @tblDriverActivity   
--   (DriverID, VehicleID, AssignedFrom, AssignedTo, VehDisplayName, BoxId     
--   )  
--    select da.DriverId, da.VehicleId,da.FromTime,da.ToTime, v.VehicleDescription AS DisplayName, va.BoxId      
--    from rvlfDriverAssignment da   
--     INNER JOIN rvlfVehicle v ON v.VehicleId = da.VehicleId  
--     INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId  
--    where (@bigDriverID IS NULL OR da.DriverId = @bigDriverID)  
--    AND OrganizationId = @bigOrganizationID AND  
--    (AssignmentDate Between @dtStartDate and @dtEndDate)  
--    AND (@intBoxID is null OR BoxId = @intBoxID)  
--    --select * from @tblDriverActivity  
--  DECLARE @intIterator int;  
--  --DECLARE @intBoxID int  
--  DECLARE @dtAssignedFromDate Datetime  
--  DECLARE @dtAssignedToDate Datetime  
    
--  SELECT @intIterator = MAX(ActivityID) FROM @tblDriverActivity  
    
--  WHILE @intIterator IS NOT NULL  
--   BEGIN  
--    SELECT @intBoxID = BoxId, @dtAssignedFromDate = AssignedFrom,  
--     @dtAssignedToDate = AssignedTo , @bigDriverID = DriverID  
--     from @tblDriverActivity WHERE ActivityID = @intIterator      
      
      
--    INSERT INTO @tblMessages   
--     SELECT   
--      h.MessageInID, h.BoxId,  
--      DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime))OriginDateTime,   
--      DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.DateTimeReceived))DateTimeReceived,   
--      m.BoxMsgInTypeDesc, m.BoxMsgInTypeId,  
--      h.CommInfo1, h.CommInfo2, h.Latitude, h.Longitude,   
--      CASE WHEN h.BoxMsgInTypeId=51 THEN 0 ELSE CAST (CAST(h.Speed AS numeric(10,2)) * @ConversionFactor  as int) END as Speed,  
--       h.Heading,   
--      CASE WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3  
--      OR h.BoxMsgInTypeId = 13 THEN   
--       dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID, h.BoxId, h.MessageInID, h.OriginDateTime)  
--       ELSE ' ' END as SensorMask,  
--      h.CustomProp, ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress, h.IsArmed, h.NearestLandmark,  
--      h.Priority, v.Vin, v.LicensePlate, v.Email, v.SMS,v.VehicleId,v.VehicleDescription, v.VehicleDescription AS DisplayName,  
--      v.OrganizationId, CASE WHEN v.Notify=1 THEN 'Notify'   
--      WHEN v.Warning=1 THEN 'Warning' WHEN v.Critical =1 THEN 'Critical'   
--      ELSE 'No Notification is set' END as NotificationType,   
--      (CASE WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3 OR h.BoxMsgInTypeId = 13    
--       THEN dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID ,h.BoxId, h.MessageInID, h.OriginDateTime)  
--         WHEN h.BoxMsgInTypeId = 4 THEN ''  
--         WHEN m.BoxMsgInTypeDesc<>'Sensor'  
--       THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN   
--       dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1) END)  
--       ELSE '' END) as Duration,  
--      f.FleetName, g.OrganizationName, @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,  
--      CASE WHEN h.BoxMsgInTypeId = 28  THEN m.BoxMsgInTypeDesc   
--         WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +  
--         CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +  
--        dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'  
--       ELSE  
--      dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime)END  as MessageDetails,  
--      @bigDriverID  
--     FROM rvlfMsgInHst h   
--      INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
--      INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
--      INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
--      LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
--      INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
--      INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
--      INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
--      INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
--      WHERE  
--       ( @bigFleetID IS NULL  OR f.FleetId = @bigFleetID) AND   
--       m.Isviolation=1 AND  
--       (@intBoxID IS NULL OR h.BoxId = @intBoxID) AND  
--         h.OriginDateTime BETWEEN @dtAssignedFromDate AND @dtAssignedToDate  
      
--    SELECT @intIterator = MAX(ActivityID) FROM @tblDriverActivity WHERE ActivityID < @intIterator  
--   END  
    
--  Update @tblDriverActivity Set RouteName='Pelham 123'   
--  Update @tblDriverActivity Set LandMarkFrom='ANGLER - CBE'   
--  Update @tblDriverActivity Set LandMarkTo='Ram Nagar'   
    
--  --Select * from @tblMessages  
--  --Select distinct VehicleID ,DriverId from @tblDriverActivity  
    
--  --Select A.ActivityID,A.DriverID,A.VehicleID,A.VehDisplayName,d.DriverName,  
--  --d.MobileNo as DriverMobileNo, d.LicenseNo as DriverLicNo, v.Vin,v.LicensePlate,  
--  --@DistanceCaptionPrefix DistanceCaption,m.OriginDateTime,RouteName,LandMarkFrom,LandMarkTo,10 as Distance  
--  --from  @tblDriverActivity A    
--  --INNER JOIN rvlfDriverMaster d ON d.DriverId = A.DriverID    
--  --LEFT OUTER JOIN rvlfVehicle v ON d.OrganizationID = v.OrganizationID   
--  --LEFT OUTER JOIN @tblMessages as m ON m.DriverID = A.DriverID  
--  -- order by d.DriverId   
   
--  --Insert into rvlfDriverActivityReport   
--  Select d.DriverId,d.DriverName,d.MobileNo as DriverMobileNo,d.LicenseNo as DriverLicNo,  
--  v.Vin,v.LicensePlate,a.VehicleID, A.VehDisplayName,m.OriginDateTime,RouteName,LandMarkFrom,LandMarkTo,  
--  10 as Distance,@DistanceCaptionPrefix DistanceCaption  
--  from  @tblDriverActivity A    
--  INNER JOIN rvlfDriverMaster d ON d.DriverId = A.DriverID    
--  LEFT OUTER JOIN rvlfVehicle v ON d.OrganizationID = v.OrganizationID   
--  LEFT OUTER JOIN @tblMessages as m ON m.DriverID = A.DriverID  
--   order by d.DriverId       
   
  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverAssignmentDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetDriverAssignmentDetails]  
 @bigDriverId bigint=null,  
 @bigVehicleId bigint=null,  
 @dtFromdate datetime=null,  
 @dtTodate datetime=null,  
 @bigUserId bigint=null,  
 @intHoursToBeAdded INT = 0,  
 @intMinsToBeAdded INT = 0  
   
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_GetDriverAssignmentDetails]null,NULL,NULL,NULL,63,5,30  
-- Description : To get the driver or vehicle assignment details  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 11-Jun-2010 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
  
 SELECT DA.AssignmentDate,DA.DriverId,CONVERT(varchar(5),DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CASE WHEN FromTime IS NULL THEN PunchIn ELSE FromTime END)),108)as FromTime,  
 CONVERT(varchar(5),DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CASE WHEN ToTime IS NULL THEN PunchOut ELSE ToTime END)),108)as ToTime,VA.VehicleId,V.VehicleDescription AS VehName,  
   DM.DisplayName AS DriverName,DA.TRIPID,CASE WHEN DA.FromTime IS NULL THEN 1 ELSE 0 END AS IsAutomatic    
  FROM RVLFDRIVERASSIGNMENT DA  
   INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =DA.BOXID   
   INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId   
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId   
  WHERE ((@bigDriverId IS NULL OR @bigDriverId='') OR @bigDriverId='' OR DA.DRIVERID=@bigDriverId)   
   AND ((@bigVehicleId IS NULL OR @bigVehicleId='') OR @bigVehicleId='' OR VA.VEHICLEID=@bigVehicleId)  
   AND (@dtFromdate IS NULL OR @dtFromdate='' OR @dtTodate IS NULL OR @dtTodate='' OR ASSIGNMENTDATE BETWEEN @dtFromdate AND @dtTodate)  
  ORDER BY CASE WHEN DA.FromTime IS NULL THEN DA.PunchIn ELSE DA.FromTime END  
END  


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverBattaInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE Procedure [dbo].[rvlf_sp_GetDriverBattaInfo]  
 @bigDriverId bigint = Null,   
 @dtFromDate datetime=null,  
 @dtToDate datetime=null,  
 @bigOrganizationID bigint = null,  
 @intHoursToBeAdded INT = 0,  
 @intMinsToBeAdded INT = 0   
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_GetDriverBattaInfo]NULL,'2010-10-01','2010-10-27',6  
-- Description : To get the driver batta details based on the from and to date.  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 25-July-2010 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
 SELECT DA.AssignmentId,CONVERT(varchar(5),DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,FromTime)),108)as FromTime,  
 CONVERT(varchar(5),DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,ToTime)),108)as ToTime,  
  V.VehicleDescription as VehicleName,DM.DisplayName,CONVERT(varchar,DA.AssignmentDate,106) as AssignmentDate,DA.tripid,DA.isamtissued,ROW_NUMBER() over(ORDER BY DA.ASSIGNMENTID) AS SeqNo   
   FROM rvlfDriverAssignment DA  
   INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =DA.BOXID  
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId   
   INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId   
  WHERE ((@bigOrganizationID IS NULL OR @bigOrganizationID='') OR (DM.OrganizationID=@bigOrganizationID AND V.OrganizationId=@bigOrganizationID))  
   AND ((@bigDriverId IS NULL OR @bigDriverId='') OR DA.DriverId=@bigDriverId)  
   AND (DA.AssignmentDate BETWEEN @dtFromDate AND @dtToDate)    
   AND (CONVERT(DATETIME,DATEADD(HOUR,+5,DATEADD(MINUTE,+30,ToTime)))<GETDATE())   
END  
  


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverBattaInfo1]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
  
CREATE Procedure [dbo].[rvlf_sp_GetDriverBattaInfo1]  
 @bigDriverId bigint = Null,   
 @dtFromDate datetime=null,  
 @dtToDate datetime=null,  
 @bigOrganizationID bigint = null,  
 @intHoursToBeAdded INT = 0,  
 @intMinsToBeAdded INT = 0,  
 @bitType bit=null,
 @bigUserID bigint = Null        
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_GetDriverBattaInfo1]null,'2010-11-22','2010-11-30',22,5,30,0  
-- Description : To get the driver batta details based on the from and to date.  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 10-Nov-2010 VN Created Intial Version   
/******************************************************************************/  
BEGIN   
  
declare @tbl table  
(  
 datein datetime,  
 dateout datetime,  
 boxid bigint,  
 driver bigint,  
 inc int  
)  
declare @tbl1 table  
(   
 dateout datetime,  
 driver bigint  
)  
insert into @tbl (datein,boxid,driver)  
select OriginDateTime,BoxId,CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))AS BIGINT) END  from rvlfmsginhst where CONVERT(date,origindatetime) between @dtFromDate and @dtToDate   
          and BoxMsgInTypeId=76  
          and case when CustomProp like '%MAPID=%' then CAST(substring(CustomProp,CHARINDEX('MAPID=',customprop,1)+6,len(CustomProp)) AS bigint)end in (select DriverId  from rvlfDriverMaster where OrganizationID=@bigOrganizationID)  
          and (@bigDriverId IS NULL OR case when CustomProp like '%MAPID=%' then CAST(substring(CustomProp,CHARINDEX('MAPID=',customprop,1)+6,len(CustomProp)) AS bigint) end=@bigDriverId)   
          and CustomProp like '%Driver Status%'  
          and CASE WHEN CustomProp LIKE '%Driver Status=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,CHARINDEX(';',CustomProp,  
        CHARINDEX('Driver Status=',CustomProp,1)) - (CHARINDEX('Driver Status=',CustomProp,1)+14)) as VARCHAR) END='IN'  
    and boxid in(select BoxId from rvlfBoxId where OrganizationId=@bigOrganizationID)    
   -- and @bigDriverId in (select DriverId from rvlfDriverMaster where OrganizationID= @bigOrganizationID)       
          order by OriginDateTime   
insert @tbl1(dateout,driver)  
select OriginDateTime,CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))AS BIGINT) END from rvlfmsginhst where CONVERT(date,origindatetime) between @dtFromDate and @dtToDate   
          and BoxMsgInTypeId=76  
          and case when CustomProp like '%MAPID=%' then CAST(substring(CustomProp,CHARINDEX('MAPID=',customprop,1)+6,len(CustomProp)) AS bigint)end in (select DriverId  from rvlfDriverMaster where OrganizationID=@bigOrganizationID)  
          and (@bigDriverId IS NULL OR case when CustomProp like '%MAPID=%' then CAST(substring(CustomProp,CHARINDEX('MAPID=',customprop,1)+6,len(CustomProp)) AS bigint) end=@bigDriverId)  
          and CustomProp like '%Driver Status%'  
          and CASE WHEN CustomProp LIKE '%Driver Status=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,CHARINDEX(';',CustomProp,  
        CHARINDEX('Driver Status=',CustomProp,1)) - (CHARINDEX('Driver Status=',CustomProp,1)+14)) as VARCHAR) END='OUT'  
    and boxid in(select BoxId from rvlfBoxId where OrganizationId=@bigOrganizationID)    
   -- and @bigDriverId in (select DriverId from rvlfDriverMaster where OrganizationID= @bigOrganizationID)           
          order by OriginDateTime    
  
UPDATE @tbl SET inc=1 WHERE driver=0  
       
while exists(select * from @tbl where inc is null)  
begin  
  
 declare @dt datetime =null   
 SET @bigDriverId=NULL  
 select top 1 @dt=datein,@bigDriverId=driver from @tbl where dateout is null AND inc IS NULL  
  
 if exists(select * from @tbl1 where dateout >=@dt and dateout <(select top 1 datein from @tbl where dateout is null AND inc IS NULL and datein>@dt and driver=@bigDriverId))   
  begin  
   update top(1) @tbl set dateout=(select top 1 dateout  from @tbl1 where dateout>@dt and driver=@bigDriverId)where dateout is null and datein=@dt and inc is null       
  end  
 else  
  begin  
   --update top(1) @tbl set dateout=@dt where dateout is null and datein=@dt and inc is null    
   delete from @tbl where datein=@dt and driver=@bigDriverId      
  end  
 update @tbl set inc=1 where inc is null and datein=@dt     
  
end    
IF(@bitType=0)  
 BEGIN  
   SELECT DM.DisplayName,V.VehicleDescription AS VehicleName,  
 REPLACE(CONVERT(VARCHAR,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,datein)),109),':000','') AS FromTime,  
 REPLACE(CONVERT(VARCHAR,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,dateout)),109),':000','')AS ToTime,  
 dm.DriverId,datein as StartDate,dateout as Enddate,null as NoOfTrips,V.VehicleId,  
 CASE WHEN DI.DriverId IS NULL THEN 'false' ELSE 'true' END AS AmtIssued    
    FROM @tbl T  
  INNER JOIN rvlfDriverMaster DM ON DM.DriverId=T.driver AND DM.OrganizationID=@bigOrganizationID   
  INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=T.boxid   
  INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId  
  LEFT OUTER JOIN rvlfDriverIncentiveAmounts DI ON DI.TripStart=T.datein AND DI.TripEnd=T.dateout AND DI.DriverId=T.driver    
    WHERE datein IS NOT NULL   
  AND dateout IS NOT NULL  
    
 END  
ELSE  
 BEGIN  
  declare @tblGroup table  
  (  
   datein datetime,  
   dateout datetime,  
   boxid bigint,  
   driver bigint,  
   NoOfTrips int,  
   inc int  
  )  
  insert into @tblGroup(boxid,driver,NoOfTrips)  
   select boxid,driver,COUNT(driver) from @tbl where dateout is not null and driver!=0 group by driver,boxid      
     
  while exists(select * from @tblGroup where inc is null)  
   begin  
    set @bigDriverId =null  
    declare @bixid bigint=null  
    select top 1 @bigDriverId=driver,@bixid=boxid from @tblGroup where inc is null and datein is null  
    update top (1) @tblGroup set datein=(select min(datein) from @tbl where driver=@bigDriverId and boxid=@bixid),  
     dateout=(select MAX(dateout) from @tbl where driver=@bigDriverId and boxid=@bixid)   
     where inc is null and datein is null and driver=@bigDriverId   
       
    update top(1) @tblGroup set inc =1 where inc is null and driver=@bigDriverId and boxid=@bixid   
        
   end     
   SELECT DM.DisplayName,V.VehicleDescription AS VehicleName,  
   REPLACE(CONVERT(VARCHAR,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,datein)),109),':000','') AS FromTime,  
   REPLACE(CONVERT(VARCHAR,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,dateout)),109),':000','')AS ToTime,  
   dm.DriverId,datein as StartDate,dateout as Enddate,NoOfTrips,V.VehicleId,  
   CASE WHEN DI.DriverId IS NULL THEN 'false' ELSE 'true' END AS AmtIssued       
      FROM @tblGroup T  
    INNER JOIN rvlfDriverMaster DM ON DM.DriverId=T.driver AND DM.OrganizationID=@bigOrganizationID   
    INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=T.boxid   
    INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId  
    LEFT OUTER JOIN rvlfDriverIncentiveAmounts DI ON DI.TripStart>=T.datein AND DI.TripEnd<=T.dateout AND DI.DriverId=T.driver     
      WHERE datein IS NOT NULL   
    AND dateout IS NOT NULL    
    GROUP BY DI.DriverId,DM.DisplayName,V.VehicleDescription,datein,dateout,dm.DriverId,NoOfTrips,V.VehicleId  
 END  
  
--select * from @tbl   
--select * from @tbl1   
--select * from @tblGroup   
  
END      
         
         

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverBehaviour]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetDriverBehaviour]  
 @dtStartDate datetime = null,  
 @dtEndDate datetime = null,  
 @bigOrganizationID bigint = null,  
 @bigQueryingUser bigint = 0,  
 @bigDriverID bigint = NULL,  
 @intSPoint int = null,  
 @intHBPoint int = null,  
 @intEBPoint int = null,  
 @intHAPoint int = null,  
 @intEAPoint int = null,  
 @intACCPoint int = null,  
 @bigFleetID bigint = NULL,  
 @intBoxID int = null,  
 @vcDrivers varchar(25) = null  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetDriverBehaviour @bigOrganizationID = 6, @dtStartDate='2011-01-17', @dtEndDate='2011-1-20', @bigQueryingUser = 12  
-- Description : To get the driver behaviour  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>>  Initial Reason  
--    : 17-Jun-2010 MJJC Created Intial Version   
--    : 23-Jun-2010 MJJC Included the provision for fleet and vehicle level  
--    : 29-Jun-2010 MJJC Vehicle Display Nmae as Vehicle Description  
--    : 05-Jul-2010 MJJC Changed the script for getting the driver assignment dates  
--    : 21-Aug-2010 LK     Changed the Vehicle Display Name to Vehicle Name  
/******************************************************************************/  
  
  
BEGIN  
 SET NOCOUNT ON   
   
 ------- Included to get the user prefernces---------------------  
 DECLARE @HoursToBeAdded INT = 0  
 DECLARE @MinsToBeAdded INT = 0  
 DECLARE @DistanceCaptionPrefix varchar(15)  
 DECLARE @SpeedCaptionPrefix varchar(15)  
 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 ,  
     @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 = @bigQueryingUser  
  
    SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))  
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))  
   
   
 IF @bigFleetID is null  
  BEGIN  
   SELECT @bigFleetID = FleetID FROM rvlfFleet where IsDefault= 1 and OrganizationId = @bigOrganizationID  
  END  
  
 DECLARE @tblDriverBehaviour table (BehaviourID bigint identity (1,1),   
   DriverID bigint,VehicleID bigint,AssignedFrom DateTime,  
   AssignedTo DateTime, VehDisplayName varchar(20), BoxId int,  
   SpeedRanking int, SpeedCount int,HarshBrakingRanking int, HarshBrakingCount int,  
   ExtremeBrakingRanking int,ExtremeBrakingCount int, HarshAccelerationRanking int,  
   HarshAccelerationCount int,ExtremeAccelerationRanking int, ExtremeAccelerationCount int,  
   AccidentRanking int,AccidentCount int)  
  
  
  
 DECLARE @tblMessages table(  
  [MessageInID] [uniqueidentifier] NOT NULL,  
  [BoxId] [int] NOT NULL,  
  [OriginDateTime] [datetime] NULL,  
  [DateTimeReceived] [datetime] NULL,  
  [BoxMsgInTypeDesc] [varchar](50) NOT NULL,  
  [BoxMsgInTypeId] [tinyint] NOT NULL,  
  [CommInfo1] [varchar](15) NULL,  
  [CommInfo2] [int] NULL,  
  [Latitude] [decimal](10, 6) NULL,  
  [Longitude] [decimal](10, 6) NULL,  
  [Speed] [int] NULL,  
  [SpeedDisply] [varchar](15) NULL,  
  [Heading] [smallint] NULL,  
  [SensorMask] [varchar](max) NULL,  
  [CustomProp] [varchar](600) NULL,  
  [StreetAddress] [varchar](250) NOT NULL,  
  [IsArmed] [bit] NULL,  
  [NearestLandmark] [varchar](300) NULL,  
  [Priority] [tinyint] NULL,  
  [Vin] [varchar](20) NULL,  
  [LicensePlate] [varchar](20) NULL,  
  [Email] [varchar](2010) NULL,  
  [SMS] [varchar](160) NULL,  
  [VehicleID] [bigint],  
  [VehicleDescription] [varchar](50) NULL,  
  [VehDisplayName] [varchar](20) NULL,  
  [OrganizationId] [bigint] NULL,  
  [NotificationType] [varchar](22) NOT NULL,  
  [Duration] [varchar](max) NULL,  
  [FleetName] [varchar](100) NOT NULL,  
  [OrganizationName] [varchar](200) NOT NULL,  
  [DistanceCaption] [varchar](10) NOT NULL,  
  [SpeedCaption] [varchar](10) NOT NULL,  
  [MessageDetails] [varchar](max) NULL,  
  [DriverID] bigint  
 )   
   
 --CHECK IF THE DRIVER HAVE IBUTTON  
 IF EXISTS(SELECT MessageInID FROM rvlfMsgInHst M  
    INNER JOIN rvlfDriverMaster DM ON DM.DriverId =CASE WHEN CustomProp LIKE '%MAPID=%'   
     THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))ELSE 0  END  
    INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =M.BoxId   
    INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId    
    WHERE (V.OrganizationId = @bigOrganizationID)  
     AND(DM.OrganizationID =@bigOrganizationID)   
     AND OriginDateTime BETWEEN @dtStartDate and @dtEndDate  
     AND (@intBoxID is null OR M.BoxId = @intBoxID)  
     AND BoxMsgInTypeId=76  
     AND (@bigDriverID IS NULL OR DM.DriverId  = @bigDriverID)   
     AND (@vcDrivers IS NULL OR DM.DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDrivers,',')))  
     AND (CASE WHEN CustomProp LIKE '%Driver Status=%'   
      THEN SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,  
      (CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,1))-(CHARINDEX('Driver Status=',CustomProp,1)+14))) ELSE 'NI' END)='IN')  
  BEGIN  
   INSERT INTO @tblDriverBehaviour   
    (DriverID, VehicleID, AssignedFrom, AssignedTo, VehDisplayName, BoxId,  
    SpeedRanking, SpeedCount, HarshBrakingRanking, HarshBrakingCount, ExtremeBrakingRanking,   
    ExtremeBrakingCount, HarshAccelerationRanking, HarshAccelerationCount,   
    ExtremeAccelerationRanking, ExtremeAccelerationCount)  
   SELECT DriverId,V.VehicleId,M.OriginDateTime,NULL,V.VehicleDescription,M.BoxId,0,0,0,0,0,0,0,0,0,0  
   FROM rvlfMsgInHst M  
    INNER JOIN rvlfDriverMaster DM ON DM.DriverId =CASE WHEN CustomProp LIKE '%MAPID=%'   
     THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))ELSE 0  END  
    INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =M.BoxId   
    INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId    
    WHERE (V.OrganizationId = @bigOrganizationID)  
     AND(DM.OrganizationID =@bigOrganizationID)   
     AND OriginDateTime BETWEEN @dtStartDate and @dtEndDate  
     AND (@intBoxID is null OR M.BoxId = @intBoxID)  
     AND BoxMsgInTypeId=76  
     AND (@bigDriverID IS NULL OR CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) AS BIGINT) ELSE 0 END = @bigDriverID)   
     AND (@vcDrivers IS NULL OR CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) AS BIGINT) ELSE 0 END IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDrivers,',')))    
     AND (CASE WHEN CustomProp LIKE '%Driver Status=%'   
      THEN SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,  
      (CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,1))-(CHARINDEX('Driver Status=',CustomProp,1)+14))) ELSE 'NI' END)='IN'  
      
   DECLARE @bigBehaviourLoop bigint=null  
   SELECT @bigBehaviourLoop=MIN(BehaviourID) FROM @tblDriverBehaviour        
   WHILE @bigBehaviourLoop IS NOT NULL  
    BEGIN  
     DECLARE @bigDriver bigint=null,@dtStart datetime =null,@dtEnd datetime=null,@intBoxidLoop int=null  
     SELECT @bigDriver=DriverID,@dtStart =AssignedFrom,@intBoxidLoop=BoxId  FROM @tblDriverBehaviour WHERE BehaviourID=@bigBehaviourLoop AND AssignedTo IS NULL  
       
     --GET THE PUNCH OUT TIME  
       
       SELECT TOP 1 @dtEnd=OriginDateTime   
      FROM rvlfMsgInHst   
       WHERE BoxId =@intBoxidLoop  
        AND OriginDateTime >@dtStart  
        AND OriginDateTime <= @dtEndDate  
        AND BoxMsgInTypeId =76  
        AND (CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) AS BIGINT) ELSE 0 END = @bigDriver)     
        AND (CASE WHEN CustomProp LIKE '%Driver Status=%'   
         THEN SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,  
         (CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,1))-(CHARINDEX('Driver Status=',CustomProp,1)+14))) ELSE 'NI' END)='OUT'  
        ORDER BY OriginDateTime   
     IF(@dtEnd IS NULL OR @dtEnd ='')  
      BEGIN  
       SET @dtEnd =@dtEndDate          
      END  
     UPDATE @tblDriverBehaviour SET AssignedTo =@dtEnd WHERE DriverID=@bigDriver AND AssignedFrom =@dtStart AND BoxId=@intBoxidLoop AND AssignedTo IS NULL  
       
     SELECT @bigBehaviourLoop =MIN(BehaviourID) FROM @tblDriverBehaviour WHERE BehaviourID > @bigBehaviourLoop           
    END              
  END      
 ELSE  
  BEGIN  
   INSERT INTO @tblDriverBehaviour   
    (DriverID, VehicleID, AssignedFrom, AssignedTo, VehDisplayName, BoxId,  
    SpeedRanking, SpeedCount, HarshBrakingRanking, HarshBrakingCount, ExtremeBrakingRanking,   
    ExtremeBrakingCount, HarshAccelerationRanking, HarshAccelerationCount,   
    ExtremeAccelerationRanking, ExtremeAccelerationCount)  
     select da.DriverId, va.VehicleId,da.FromTime,da.ToTime, v.VehicleDescription AS DisplayName, va.BoxId,  
     0,0,0,0,0,0,0,0,0,0  
     from rvlfDriverAssignment da   
      INNER JOIN rvlfVehicleAssignment va ON DA.BOXID = va.BoxId   
      INNER JOIN rvlfVehicle v ON v.VehicleId = VA.VehicleId        
     where (@bigDriverID IS NULL OR da.DriverId = @bigDriverID)  
     AND (@vcDrivers IS NULL OR da.DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDrivers,',')))    
     AND OrganizationId = @bigOrganizationID AND  
     (AssignmentDate Between @dtStartDate and @dtEndDate)  
     AND (@intBoxID is null OR DA.BoxId = @intBoxID)  
  END  
  
  DECLARE @intIterator int;  
  --DECLARE @intBoxID int  
  DECLARE @dtAssignedFromDate Datetime  
  DECLARE @dtAssignedToDate Datetime  
  DECLARE @intSpeedRanking int  
  DECLARE @intSpeedCount int  
  DECLARE @intHarshBrakingRanking int  
  DECLARE @intHarshBrakingCount int  
  DECLARE @intExtremeBrakingRanking int  
  DECLARE @intExtremeBrakingCount int  
  DECLARE @intHarshAccelerationRanking int  
  DECLARE @intHarshAccelerationCount int  
  DECLARE @intExtremeAccelerationRanking int  
  DECLARE @intExtremeAccelerationCount int  
  DECLARE @intAccidentCount int  
  DECLARE @intAccidentRanking int  
  SELECT @intIterator = MAX(BehaviourID) FROM @tblDriverBehaviour  
    
  WHILE @intIterator IS NOT NULL  
   BEGIN  
    SELECT @intBoxID = BoxId, @dtAssignedFromDate = AssignedFrom,  
     @dtAssignedToDate = AssignedTo , @bigDriverID = DriverID  
     from @tblDriverBehaviour WHERE BehaviourID = @intIterator  
    SET @intSpeedRanking = 0; SET @intSpeedCount  = 0; SET @intHarshBrakingRanking = 0; SET @intHarshBrakingCount = 0;  
    SET @intExtremeBrakingRanking = 0; SET @intExtremeBrakingCount = 0; SET @intHarshAccelerationRanking = 0;  
    SET @intHarshAccelerationCount = 0; SET @intExtremeAccelerationRanking = 0; SET @intExtremeAccelerationCount = 0;  
    SET @intAccidentCount=0; SET @intAccidentRanking=0  
    SELECT   
     @intSpeedRanking = SUM(CASE WHEN h.BoxMsgInTypeId = 4 THEN ISNULL(@intSPoint ,r.Rating) ELSE 0 END),  
     @intSpeedCount = SUM(CASE WHEN h.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END),  
     @intHarshBrakingRanking =SUM(CASE WHEN h.BoxMsgInTypeId = 14 THEN ISNULL(@intHBPoint, r.Rating) ELSE 0 END),  
     @intHarshBrakingCount = SUM(CASE WHEN h.BoxMsgInTypeId = 14 THEN 1 ELSE 0 END),  
     @intExtremeBrakingRanking = SUM(CASE WHEN h.BoxMsgInTypeId = 15 THEN ISNULL(@intEBPoint,r.Rating) ELSE 0 END),  
     @intExtremeBrakingCount = SUM(CASE WHEN h.BoxMsgInTypeId = 15 THEN 1 ELSE 0 END),  
     @intHarshAccelerationRanking = SUM(CASE WHEN h.BoxMsgInTypeId = 16 THEN ISNULL(@intHAPoint,r.Rating) ELSE 0 END),  
     @intHarshAccelerationCount = SUM(CASE WHEN h.BoxMsgInTypeId = 16 THEN 1 ELSE 0 END),  
     @intExtremeAccelerationRanking = SUM(CASE WHEN h.BoxMsgInTypeId = 17 THEN ISNULL(@intEAPoint,r.Rating) ELSE 0 END),  
     @intExtremeAccelerationCount = SUM(CASE WHEN h.BoxMsgInTypeId = 17 THEN 1 ELSE 0 END),  
     @intAccidentRanking= SUM(CASE WHEN h.BoxMsgInTypeId = 66 THEN ISNULL(@intACCPoint,r.Rating) ELSE 0 END),   
     @intAccidentCount = SUM(CASE WHEN h.BoxMsgInTypeId = 66 THEN 1 ELSE 0 END)  
    FROM rvlfMsgInHst h   
     INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
     LEFT OUTER JOIN rvlfViolationRating r ON h.BoxMsgInTypeId = r.BoxMsgInTypeID  
    WHERE  
     r.OrganizationId= @bigOrganizationID and   
     (@intBoxID IS NULL OR h.BoxId = @intBoxID) AND  
     (h.OriginDateTime BETWEEN @dtAssignedFromDate AND @dtAssignedToDate)  
    Group By h.BoxId  
      
    INSERT INTO @tblMessages   
     SELECT   
      h.MessageInID, h.BoxId,  
      DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime))OriginDateTime,   
      DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.DateTimeReceived))DateTimeReceived,   
      m.BoxMsgInTypeDesc, m.BoxMsgInTypeId,  
      h.CommInfo1, h.CommInfo2, h.Latitude, h.Longitude,   
      CASE WHEN h.BoxMsgInTypeId=51 THEN 0 ELSE CAST (CAST(h.Speed AS numeric(10,2)) * @ConversionFactor  as int) END as Speed,  
      CASE WHEN H.BoxMsgInTypeId =51 THEN NULL ELSE CAST(CAST(Speed  * @ConversionFactor as INT) AS VARCHAR)+ CASE WHEN CustomProp LIKE '%speed1=%' THEN ' --> '+ CAST(CAST((CAST(SUBSTRING(CustomProp,CHARINDEX('speed1=',CustomProp,0)+7,(LEN(CustomProp))) AS INT)* @ConversionFactor) AS INT) AS VARCHAR) ELSE ''  END  END  as Speed1,   
       h.Heading,   
      CASE WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3  
      OR h.BoxMsgInTypeId = 13 THEN   
       dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID, h.BoxId, h.MessageInID, h.OriginDateTime)  
       ELSE ' ' END as SensorMask,  
      h.CustomProp, ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress, h.IsArmed, h.NearestLandmark,  
      h.Priority, v.Vin, v.LicensePlate, v.Email, v.SMS,v.VehicleId,v.VehicleDescription, v.VehicleDescription AS DisplayName,  
      v.OrganizationId, CASE WHEN v.Notify=1 THEN 'Notify'   
      WHEN v.Warning=1 THEN 'Warning' WHEN v.Critical =1 THEN 'Critical'   
      ELSE 'No Notification is set' END as NotificationType,   
      (CASE WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3 OR h.BoxMsgInTypeId = 13    
       THEN dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID ,h.BoxId, h.MessageInID, h.OriginDateTime)  
         WHEN h.BoxMsgInTypeId = 4 THEN ''  
         WHEN m.BoxMsgInTypeDesc<>'Sensor'  
       THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN   
       dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1) END)  
       ELSE '' END) as Duration,  
      f.FleetName, g.OrganizationName, @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,  
      CASE WHEN h.BoxMsgInTypeId = 28  THEN m.BoxMsgInTypeDesc   
         WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +  
         CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +  
        dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'  
       ELSE  
      dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime)END  as MessageDetails,  
      @bigDriverID  
     FROM rvlfMsgInHst h   
      INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
      INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
      INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
      LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
      INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
      INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
      INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
      INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
      WHERE  
       ( @bigFleetID IS NULL  OR f.FleetId = @bigFleetID) AND   
       m.Isviolation=1 AND  
       (@intBoxID IS NULL OR h.BoxId = @intBoxID) AND  
         h.OriginDateTime BETWEEN @dtAssignedFromDate AND @dtAssignedToDate  
       
    Update @tblDriverBehaviour SET SpeedRanking = @intSpeedRanking, SpeedCount = @intSpeedCount,  
     HarshBrakingRanking = @intHarshBrakingRanking, HarshBrakingCount = @intHarshBrakingCount,  
     ExtremeBrakingRanking = @intExtremeBrakingRanking, ExtremeBrakingCount = @intExtremeBrakingCount,  
     HarshAccelerationRanking = @intHarshAccelerationRanking, HarshAccelerationCount = @intHarshAccelerationCount,  
     ExtremeAccelerationRanking = @intExtremeAccelerationRanking, ExtremeAccelerationCount = @intExtremeAccelerationCount,  
     AccidentRanking=@intAccidentRanking,AccidentCount=@intAccidentCount   
    WHERE BehaviourID = @intIterator  
      
    SELECT @intIterator = MAX(BehaviourID) FROM @tblDriverBehaviour WHERE BehaviourID < @intIterator  
   END  
  --SELECT * FROM @tblMessages order by BoxMsgInTypeId  
  SELECT d.DriverId,d.DriverName, d.DisplayName as DriverDispName, d.MobileNo as DriverMobileNo, d.LicenseNo as DriverLicNo,  
   m.VehicleID, m.VehicleDescription, m.VehDisplayName,m.BoxId, b.SR, b.SC,b.HBR, b.HBC, b.EBR, b.EBC,  
   b.HAR, b.HAC, b.EAR, b.EAC,B.ACR,B.ACC,b.TotalViolations,b.TotalRanking,m.BoxMsgInTypeDesc, m.SensorMask,  
   MessageInID, OriginDateTime, DateTimeReceived,  
   CASE WHEN Speed=0 THEN '-' ELSE CAST(Speed AS VARCHAR) END AS Speed,  
   CASE WHEN SpeedDisply='0' THEN '-' ELSE SpeedDisply END AS SpeedDisply,   
   StreetAddress, Vin, LicensePlate,CASE WHEN Duration IS NULL OR Duration='' THEN '-' ELSE Duration END AS Duration, FleetName,  
   OrganizationName, DistanceCaption, SpeedCaption, MessageDetails FROM   
   (SELECT *, SC+HBC+EBC+HAC+EAC+ACC   as TotalViolations, SR+HBR+EBR+HAR+EAR+ACR  as TotalRanking FROM   
   (SELECT DriverID, SUM(SpeedRanking) as SR, SUM(SpeedCount) as SC,  
    SUM(HarshBrakingRanking) HBR, SUM(HarshBrakingCount) as HBC, SUM(ExtremeBrakingRanking) EBR,  
    SUM(ExtremeBrakingCount) EBC, SUM(HarshAccelerationRanking) HAR, SUM(HarshAccelerationCount) as HAC,  
    SUM(ExtremeAccelerationRanking) EAR, SUM(ExtremeAccelerationCount) as EAC,SUM(AccidentCount) as ACC,  
    SUM(AccidentRanking) ACR  
   FROM @tblDriverBehaviour   
   GROUP BY DriverID--, VehicleID, VehDisplayName, BoxId   
   ) as a ) as b LEFT OUTER JOIN   
     @tblMessages as m ON m.DriverID = b.DriverID --and m.BoxId = b.BoxId  
    INNER JOIN rvlfDriverMaster d ON d.DriverId = m.DriverID  
    LEFT OUTER JOIN rvlfViolationRating v ON d.OrganizationID = v.OrganizationID   
   and m.BoxMsgInTypeId = v.BoxMsgInTypeID order by DriverId  
    
  SELECT ISNULL(@intSPoint ,[4]) as SP,ISNULL(@intHBPoint ,[14]) as HBP,  
   ISNULL(@intEBPoint ,[15]) as EBP,ISNULL(@intHAPoint ,[16]) as HAP,  
   ISNULL(@intEAPoint ,[17]) as EAP,ISNULL(@intACCPoint ,[66]) as ACP FROM (  
   SELECT mt.BoxMsgInTypeId, vr.Rating FROM rvlfViolationRating vr   
    INNER JOIN rvlfOrganization g ON vr.OrganizationID= g.OrganizationId  
    INNER JOIN rvlfBoxMsgInType mt ON mt.BoxMsgInTypeId = vr.BoxMsgInTypeID  
   WHERE vr.OrganizationID = @bigOrganizationID) as d   
  PIVOT (sum(rating) FOR Boxmsgintypeid in ([4],[14],[15],[16],[17],[66])) as p     
     
 SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverBehaviour_Opt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetDriverBehaviour_Opt]      
 @dtStartDate datetime = null,              
 @dtEndDate datetime = null,              
 @bigOrganizationID bigint = null,              
 @bigQueryingUser bigint = 0,              
 @bigDriverID bigint = NULL,              
 @intSPoint int = null,              
 @intHBPoint int = null,              
 @intEBPoint int = null,              
 @intHAPoint int = null,              
 @intEAPoint int = null,              
 @intACCPoint int = null,              
 @bigFleetID bigint = NULL,              
 @intBoxID varchar(max) = null,              
 @vcDrivers varchar(25) = null              
AS                
/******************************************************************************/              
-- Name  : rvlf_sp_GetDriverBehaviour_Opt '2012-08-16','2012-08-26',138,303,null,10,10,10,15,null,null,null          
-- Description : To get the driver behaviour              
-- Author  : M. Jebamalai Jaya Chitra.              
-- Company  : Angler Technologies              
-- History  : <<Date(dd-MON-yyyy)>>  Initial Reason              
--    : 17-Jun-2010 MJJC Created Intial Version               
--    : 23-Jun-2010 MJJC Included the provision for fleet and vehicle level              
--    : 29-Jun-2010 MJJC Vehicle Display Nmae as Vehicle Description              
--    : 05-Jul-2010 MJJC Changed the script for getting the driver assignment dates              
--    : 21-Aug-2010 LK     Changed the Vehicle Display Name to Vehicle Name          
--    : 10-Aug-2011 Ranjith Date Format Included            
/******************************************************************************/              
                
BEGIN              
 SET NOCOUNT ON               
  Declare @dtFDate datetime =@dtStartDate        
 Declare @dtEDate datetime =@dtEndDate              
 ------- Included to get the user prefernces---------------------              
 DECLARE @HoursToBeAdded INT = 0              
 DECLARE @MinsToBeAdded INT = 0              
 DECLARE @DistanceCaptionPrefix varchar(15)              
 DECLARE @SpeedCaptionPrefix varchar(15)              
 DECLARE @ConversionFactor numeric (10,2) = 1.0              
 DECLARE @DefaultDateFormat INT = 0               
         
    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,        
     @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 = @bigQueryingUser              
              
    SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))              
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))              
               
 IF @bigFleetID is null              
  BEGIN              
   SELECT @bigFleetID = FleetID FROM rvlfFleet where IsDefault= 1 and OrganizationId = @bigOrganizationID              
  END              
      
 DECLARE @tblDriverBehaviour table (BehaviourID bigint identity (1,1),               
   DriverID bigint,VehicleID bigint,AssignedFrom DateTime,              
   AssignedTo DateTime, VehDisplayName varchar(20), BoxId int,              
   SpeedRanking int, SpeedCount int,HarshBrakingRanking int, HarshBrakingCount int,              
   ExtremeBrakingRanking int,ExtremeBrakingCount int, HarshAccelerationRanking int,              
   HarshAccelerationCount int,ExtremeAccelerationRanking int, ExtremeAccelerationCount int,              
   AccidentRanking int,AccidentCount int)              
              
 DECLARE @tblMessages table(              
  [MessageInID] [uniqueidentifier] NOT NULL,              
  [BoxId] [int] NOT NULL,              
  [OriginDateTime] [datetime] NULL,      
  [DateTimeReceived] [datetime] NULL,              
  [BoxMsgInTypeDesc] [varchar](50) NOT NULL,              
  [BoxMsgInTypeId] [tinyint] NOT NULL,              
 [CommInfo1] [varchar](15) NULL,              
  [CommInfo2] [int] NULL,              
  [Latitude] [decimal](10, 6) NULL,              
  [Longitude] [decimal](10, 6) NULL,              
  [Speed] [int] NULL,              
  [SpeedDisply] [varchar](15) NULL,              
  [Heading] [smallint] NULL,              
  [SensorMask] [varchar](max) NULL,              
  [CustomProp] [varchar](600) NULL,              
  [StreetAddress] [varchar](250) NOT NULL,              
  [IsArmed] [bit] NULL,              
  [NearestLandmark] [varchar](300) NULL,              
  [Priority] [tinyint] NULL,              
  [Vin] [varchar](20) NULL,              
  [LicensePlate] [varchar](20) NULL,              
  [Email] [varchar](2010) NULL,              
  [SMS] [varchar](160) NULL,              
  [VehicleID] [bigint],              
  [VehicleDescription] [varchar](50) NULL,              
  [VehDisplayName] [varchar](20) NULL,              
  [OrganizationId] [bigint] NULL,              
  [NotificationType] [varchar](22) NOT NULL,              
  [Duration] [varchar](max) NULL,              
  [FleetName] [varchar](100) NOT NULL,              
  [OrganizationName] [varchar](200) NOT NULL,              
  [DistanceCaption] [varchar](10) NOT NULL,              
  [SpeedCaption] [varchar](10) NOT NULL,              
  [MessageDetails] [varchar](max) NULL,              
  [DriverID] bigint              
 )               
               
 --GET THE BOXIDS FOR THE FLEET              
 DECLARE @vcBoxIds VARCHAR(MAX)=NULL              
  SELECT @vcBoxIds=COALESCE(@vcBoxIds,'')+CONVERT(VARCHAR,VA.BoxId)+',' FROM rvlfFleetVehicles FV               
   INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=FV.VehicleId               
  WHERE FV.FleetId=@bigFleetID AND (@intBoxID IS NULL OR @intBoxID='0' OR @intBoxID='' OR VA.BOXID=@intBoxID)               
 -------------------------------------              
               
 --GET THE DRIVERS FOR THE ORGANIZATION              
 DECLARE @vcDriverIds VARCHAR(MAX)=NULL              
  SELECT @vcDriverIds=COALESCE(@vcDriverIds,'')+CONVERT(VARCHAR,DM.DriverId)+','  FROM rvlfDriverMaster DM              
    LEFT OUTER JOIN rvlfDriverGroupAssignment DG ON DG.DriverId=DM.DriverId               
   WHERE OrganizationID=@bigOrganizationID               
    AND (@bigDriverID IS NULL OR @bigDriverID='' OR DM.DriverId=@bigDriverID)               
    --AND (@bigDriverGroupId IS NULL OR @bigDriverGroupId='' OR DG.DriverGroupId=@bigDriverGroupId)              
               
 --GET THE DRIVER TRIPS              
 DECLARE @tblDriverTrips TABLE              
 (              
  ProcessId bigint identity(1,1),              
  Boxid int null,              
  DriverId bigint null,              
  TripTime datetime null,              
  TripStatus varchar(5)null               
 )                 
               
 --GET THE FIRST PUNCH DETAILS FROM DRIVER ASSIGNMENT              
 DECLARE @DTFIRSTPUNCH DATETIME =NULL,@bitIsIbutton bit=null,@bitIsRFID bit=null              
 SELECT TOP 1 @DTFIRSTPUNCH=PunchIn FROM rvlfDriverAssignment               
  WHERE BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))              
   AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))               
   AND PunchIn IS NOT NULL AND PunchOut IS NOT NULL        
   AND PunchIn BETWEEN @dtStartDate  AND @dtEndDate            
  ORDER BY PunchIn      
                
--CHECK IF THE PUNCH IS BEFORE THE STATDATEANDTIME                
IF(@DTFIRSTPUNCH IS NOT NULL AND @DTFIRSTPUNCH<@dtStartDate)              
 BEGIN SET @DTFIRSTPUNCH=@dtStartDate END        
ELSE IF (@DTFIRSTPUNCH IS NULL) BEGIN SET @DTFIRSTPUNCH=@dtStartDate END        
               
 --GET THE IBUTTON RIGHTS FOR THE ORGANIZATION              
 SELECT @bitIsIbutton= CASE WHEN PO.PackageId IS NULL OR PO.PackageId ='' THEN 0 ELSE 1 END               
  FROM rvlfPackageOperations PO              
   INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId               
  WHERE OperationID =147 AND IsActive =1 AND OrganizationID=@bigOrganizationID               
               
 IF (@bitIsIbutton=1)              
  BEGIN              
   INSERT INTO @tblDriverTrips (Boxid,DriverId,TripTime,TripStatus)      
    SELECT BoxId,CASE WHEN CustomProp LIKE'%MAPID=%' THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,              
      (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))) ELSE 0 END,OriginDateTime,              
      SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,0)+14,              
    (CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,0))-(CHARINDEX('Driver Status=',CustomProp,0)+14)))              
     FROM rvlfMsgInHst               
      WHERE BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))              
       AND BoxMsgInTypeId =76              
       AND SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,              
        (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))) IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))              
       AND CustomProp LIKE'%Driver Status=%' AND CustomProp LIKE '%MAPID=%'                    
       --AND OriginDateTime BETWEEN @dtStartDate AND CASE WHEN @DTFIRSTPUNCH IS NOT NULL THEN CASE WHEN @DTFIRSTPUNCH BETWEEN @dtStartDate AND @dtEndDate THEN @DTFIRSTPUNCH ELSE @dtEndDate END ELSE @dtEndDate END              
       AND OriginDateTime BETWEEN @dtStartDate AND  @dtEndDate               
      ORDER BY BoxId, SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,      
        (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))),OriginDateTime      
  END     
    
    
  SELECT  @bitIsRFID = CASE WHEN PO.OperationID=188 AND (PO.PackageId IS NULL OR PO.PackageId ='') THEN 0 WHEN PO.OperationID=188 THEN 1  END  FROM rvlfPackageOperations PO INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId               
 WHERE OperationID IN (188) AND IsActive =1 AND OrganizationID=@bigOrganizationID     
      
 IF (@bitIsRFID =1) --RFID 29-may15     
  BEGIN        
   INSERT INTO @tblDriverTrips (Boxid,DriverId,TripTime,TripStatus)      
   SELECT h.BoxId,DM.DriverId,h.OriginDateTime,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Punch:',';')      
   FROM rvlfMsgInHst h       
   INNER JOIN rvlfIButtonMapping BM ON (IButtonKey=dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'RF_ID=',';')) AND BM.KeyType=3         
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=BM.DriverId        
   WHERE h.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))        
   AND ((h.BoxMsgInTypeId=100 AND h.CustomProp like '%RF_ID=%') )        
   AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate          
   AND BoxMsgInTypeId IN(100)      
   ORDER BY h.BoxId,h.MessageInID,DM.DriverId,h.OriginDateTime          
  END  
             
 --GET THE TRIPS              
 DECLARE @tblDriverTripDetails TABLE              
 (                
  TripId bigint identity(1,1),              
  Boxid int null,              
  DriverId bigint null,              
  StartTime datetime null,              
  EndTime datetime null,              
  TripInStatus varchar(5) null,      
  TripOutStatus varchar(5) null      
 )               
 INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)              
 SELECT MT.Boxid,MT.DriverId,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus              
   FROM @tblDriverTrips AS MT               
    LEFT OUTER JOIN @tblDriverTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'IN' and MT.DriverId=ST.DriverId                    
                
 --DELETE THE INVALID TRIPS                
 DELETE FROM @tblDriverTripDetails WHERE StartTime IS NULL --OR TripInStatus=TripOutStatus               
               
 --GET THE MANUEL AND AUTOMATIC SCHEDULES              
 IF(@DTFIRSTPUNCH IS NOT NULL)              
  BEGIN              
   INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)              
   SELECT BoxId,DriverId,CASE WHEN PunchOut IS NULL THEN ToTime ELSE PunchOut END,'OUT',              
    CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END,'IN'                
    FROM rvlfDriverAssignment                
    WHERE @DTFIRSTPUNCH BETWEEN (CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END)        
    AND (CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END)        
     --@DTFIRSTPUNCH <= CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END               
     --AND @dtEndDate >= CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END              
     AND BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))              
     AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))               
  END              
 ELSE              
  BEGIN              
   INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)              
   SELECT BoxId,DriverId,CASE WHEN PunchOut IS NULL THEN ToTime ELSE PunchOut END,'OUT',              
    CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END,'IN'                
    FROM rvlfDriverAssignment                
     WHERE @dtStartDate BETWEEN (CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END)        
     AND (CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END)        
      --@dtStartDate <= CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END               
      --AND @dtEndDate >= CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END              
      AND BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))              
      AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))            
  END              
                   
 -- INSERT DRIVER IN PUNCHES               
 INSERT INTO @tblDriverBehaviour               
    (DriverID, VehicleID, AssignedFrom, AssignedTo, VehDisplayName, BoxId,              
    SpeedRanking, SpeedCount, HarshBrakingRanking, HarshBrakingCount, ExtremeBrakingRanking,      
    ExtremeBrakingCount, HarshAccelerationRanking, HarshAccelerationCount,      
    ExtremeAccelerationRanking, ExtremeAccelerationCount,AccidentRanking,AccidentCount)      
 SELECT DriverId,VA.VehicleId,StartTime,EndTime,V.VehicleDescription,TD.Boxid,0,0,0,0,0,0,0,0,0,0,0,0      
  FROM @tblDriverTripDetails TD      
   INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=TD.Boxid               
   INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId               
                    
  -- INSERT THE MESSAGES WHICH HAS COME BETWEEN THE DRIVER PUNCH IN AND OUT              
  INSERT INTO @tblMessages               
   SELECT               
    h.MessageInID, h.BoxId,          
     OriginDateTime = dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,h.OriginDateTime),         
     DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,h.DateTimeReceived),                 
    --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime))OriginDateTime,               
    --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.DateTimeReceived))DateTimeReceived,               
    m.BoxMsgInTypeDesc, m.BoxMsgInTypeId,              
    h.CommInfo1, h.CommInfo2, h.Latitude, h.Longitude,               
    CASE WHEN h.BoxMsgInTypeId=51 THEN 0 ELSE CAST (CAST(h.Speed AS numeric(10,2)) * @ConversionFactor  as int) END as Speed,              
    CASE WHEN H.BoxMsgInTypeId =51 THEN NULL ELSE CAST(CAST(Speed  * @ConversionFactor as INT) AS VARCHAR)+ CASE WHEN CustomProp LIKE '%speed1=%' THEN ' --> '+ CAST(CAST((CAST(SUBSTRING(CustomProp,CHARINDEX('speed1=',CustomProp,0)+7,(LEN(CustomProp))) AS 
 
    
 INT)* @ConversionFactor) AS INT) AS VARCHAR) ELSE ''  END  END  as Speed1,               
     h.Heading,               
    CASE WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3              
    OR h.BoxMsgInTypeId = 13 THEN               
     dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID, h.BoxId, h.MessageInID, h.OriginDateTime)              
     ELSE ' ' END as SensorMask,              
    h.CustomProp, ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress, h.IsArmed, h.NearestLandmark,              
    h.Priority, v.Vin, v.LicensePlate, v.Email, v.SMS,v.VehicleId,v.VehicleDescription, v.VehicleDescription AS DisplayName,              
    v.OrganizationId, CASE WHEN v.Notify=1 THEN 'Notify'               
    WHEN v.Warning=1 THEN 'Warning' WHEN v.Critical =1 THEN 'Critical'               
    ELSE 'No Notification is set' END as NotificationType,               
    (CASE WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3 OR h.BoxMsgInTypeId = 13                
     THEN dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID ,h.BoxId, h.MessageInID, h.OriginDateTime)              
       WHEN h.BoxMsgInTypeId = 4 THEN ''              
       WHEN m.BoxMsgInTypeDesc<>'Sensor'              
     THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN               
     dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1) END)              
     ELSE '' END) as Duration,              
    f.FleetName, g.OrganizationName, @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,              
    CASE WHEN h.BoxMsgInTypeId = 28  THEN m.BoxMsgInTypeDesc               
       WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +              
       CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +              
      dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'              
     ELSE              
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime)END  as MessageDetails,              
    db.DriverID              
 FROM rvlfMsgInHst h               
    INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId              
    INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId              
    INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId              
    LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID               
    INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId              
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId              
    INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId              
    INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId              
    INNER JOIN @tblDriverBehaviour db ON db.BoxId = va.BoxId              
    WHERE              
     (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND               
     m.Isviolation=1 AND              
     (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR h.BoxId = @intBoxID) AND              
       h.OriginDateTime BETWEEN (CASE WHEN DATEDIFF(dd,db.AssignedFrom,db.AssignedTo) > 1 THEN @dtStartDate        
      ELSE db.AssignedFrom END) AND db.AssignedTo              
            
                       
  DECLARE @intIterator int;              
  --DECLARE @intBoxID int              
  DECLARE @dtAssignedFromDate Datetime              
  DECLARE @dtAssignedToDate Datetime              
  DECLARE @intSpeedRanking int              
  DECLARE @intSpeedCount int              
  DECLARE @intHarshBrakingRanking int              
  DECLARE @intHarshBrakingCount int              
  DECLARE @intExtremeBrakingRanking int              
  DECLARE @intExtremeBrakingCount int              
  DECLARE @intHarshAccelerationRanking int              
 DECLARE @intHarshAccelerationCount int              
  DECLARE @intExtremeAccelerationRanking int              
  DECLARE @intExtremeAccelerationCount int              
  DECLARE @intAccidentCount int              
  DECLARE @intAccidentRanking int              
  SELECT @intIterator = MAX(BehaviourID) FROM @tblDriverBehaviour              
                
  WHILE @intIterator IS NOT NULL              
   BEGIN              
    SELECT @intBoxID = BoxId, @dtAssignedFromDate = AssignedFrom,              
     @dtAssignedToDate = AssignedTo , @bigDriverID = DriverID              
     from @tblDriverBehaviour WHERE BehaviourID = @intIterator              
    SET @intSpeedRanking = 0; SET @intSpeedCount  = 0; SET @intHarshBrakingRanking = 0; SET @intHarshBrakingCount = 0;              
    SET @intExtremeBrakingRanking = 0; SET @intExtremeBrakingCount = 0; SET @intHarshAccelerationRanking = 0;              
    SET @intHarshAccelerationCount = 0; SET @intExtremeAccelerationRanking = 0; SET @intExtremeAccelerationCount = 0;              
    SET @intAccidentCount=0; SET @intAccidentRanking=0              
                  
    SELECT               
     @intSpeedRanking = SUM(CASE WHEN h.BoxMsgInTypeId = 4 THEN ISNULL(@intSPoint ,r.Rating) ELSE 0 END),              
     @intSpeedCount = SUM(CASE WHEN h.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END),              
     @intHarshBrakingRanking =SUM(CASE WHEN h.BoxMsgInTypeId = 14 THEN ISNULL(@intHBPoint, r.Rating) ELSE 0 END),              
     @intHarshBrakingCount = SUM(CASE WHEN h.BoxMsgInTypeId = 14 THEN 1 ELSE 0 END),              
     @intExtremeBrakingRanking = SUM(CASE WHEN h.BoxMsgInTypeId = 15 THEN ISNULL(@intEBPoint,r.Rating) ELSE 0 END),              
     @intExtremeBrakingCount = SUM(CASE WHEN h.BoxMsgInTypeId = 15 THEN 1 ELSE 0 END),              
    @intHarshAccelerationRanking = SUM(CASE WHEN h.BoxMsgInTypeId = 16 THEN ISNULL(@intHAPoint,r.Rating) ELSE 0 END),              
     @intHarshAccelerationCount = SUM(CASE WHEN h.BoxMsgInTypeId = 16 THEN 1 ELSE 0 END),              
     @intExtremeAccelerationRanking = SUM(CASE WHEN h.BoxMsgInTypeId = 17 THEN ISNULL(@intEAPoint,r.Rating) ELSE 0 END),              
     @intExtremeAccelerationCount = SUM(CASE WHEN h.BoxMsgInTypeId = 17 THEN 1 ELSE 0 END),              
     @intAccidentRanking= SUM(CASE WHEN h.BoxMsgInTypeId = 66 THEN ISNULL(@intACCPoint,r.Rating) ELSE 0 END),               
     @intAccidentCount = SUM(CASE WHEN h.BoxMsgInTypeId = 66 THEN 1 ELSE 0 END)              
    FROM rvlfMsgInHst h               
     INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId              
     LEFT OUTER JOIN rvlfViolationRating r ON h.BoxMsgInTypeId = r.BoxMsgInTypeID              
    WHERE              
     r.OrganizationId= @bigOrganizationID and               
     (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR h.BoxId = @intBoxID) AND              
     (h.OriginDateTime BETWEEN (CASE WHEN DATEDIFF(dd,@dtAssignedFromDate,@dtAssignedToDate) > 1 THEN @dtStartDate        
      ELSE @dtAssignedFromDate END) AND @dtAssignedToDate)              
    Group By h.BoxId              
                   
    Update @tblDriverBehaviour SET SpeedRanking = @intSpeedRanking, SpeedCount = @intSpeedCount,              
     HarshBrakingRanking = @intHarshBrakingRanking, HarshBrakingCount = @intHarshBrakingCount,              
     ExtremeBrakingRanking = @intExtremeBrakingRanking, ExtremeBrakingCount = @intExtremeBrakingCount,              
     HarshAccelerationRanking = @intHarshAccelerationRanking, HarshAccelerationCount = @intHarshAccelerationCount,              
     ExtremeAccelerationRanking = @intExtremeAccelerationRanking, ExtremeAccelerationCount = @intExtremeAccelerationCount,              
     AccidentRanking=@intAccidentRanking,AccidentCount=@intAccidentCount               
    WHERE BehaviourID = @intIterator              
                  
    SELECT @intIterator = MAX(BehaviourID) FROM @tblDriverBehaviour WHERE BehaviourID < @intIterator              
   END              
                
  --SELECT * FROM @tblMessages order by BoxMsgInTypeId              
  SELECT distinct d.DriverId,d.DriverName, d.DisplayName as DriverDispName, d.MobileNo as DriverMobileNo,               
   d.LicenseNo as DriverLicNo, m.VehicleID, m.VehicleDescription, m.VehDisplayName,m.BoxId,               
   b.SR, b.SC,b.HBR, b.HBC, b.EBR, b.EBC,b.HAR, b.HAC, b.EAR, b.EAC,B.ACR,B.ACC,b.TotalViolations,              
   b.TotalRanking,m.BoxMsgInTypeDesc AS 'BoxMsgInTypeName', m.SensorMask,MessageInID,         
    OriginDateTime = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,OriginDateTime), DateTimeReceived,              
   --Convert(varchar,OriginDateTime,@DefaultDateFormat) + ' ' + Convert(varchar,Cast(OriginDateTime as time),22) as  OriginDateTime,           
   CASE WHEN Speed=0 THEN '-' ELSE CAST(Speed AS VARCHAR) END AS Speed,              
   CASE WHEN SpeedDisply='0' THEN '-' ELSE SpeedDisply END AS SpeedDisply,               
   StreetAddress, Vin, LicensePlate,CASE WHEN Duration IS NULL OR Duration='' THEN '-' ELSE Duration END AS Duration, FleetName,              
   OrganizationName, DistanceCaption, SpeedCaption, MessageDetails,        
   Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,        
   PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())        
   --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate       
  
    
    FROM               
   (SELECT *, SC+HBC+EBC+HAC+EAC+ACC   as TotalViolations, SR+HBR+EBR+HAR+EAR+ACR  as TotalRanking FROM               
   (SELECT DriverID, SUM(SpeedRanking) as SR, SUM(SpeedCount) as SC,              
    SUM(HarshBrakingRanking) HBR, SUM(HarshBrakingCount) as HBC, SUM(ExtremeBrakingRanking) EBR,              
    SUM(ExtremeBrakingCount) EBC, SUM(HarshAccelerationRanking) HAR, SUM(HarshAccelerationCount) as HAC,              
    SUM(ExtremeAccelerationRanking) EAR, SUM(ExtremeAccelerationCount) as EAC,SUM(AccidentCount) as ACC,              
    SUM(AccidentRanking) ACR              
   FROM @tblDriverBehaviour               
   GROUP BY DriverID--, VehicleID, VehDisplayName, BoxId               
   ) as a ) as b LEFT OUTER JOIN               
     @tblMessages as m ON m.DriverID = b.DriverID --and m.BoxId = b.BoxId              
    INNER JOIN rvlfDriverMaster d ON d.DriverId = m.DriverID              
    LEFT OUTER JOIN rvlfViolationRating v ON d.OrganizationID = v.OrganizationID               
   and m.BoxMsgInTypeId = v.BoxMsgInTypeID order by DriverId,OriginDateTime               
                
  SELECT ISNULL(@intSPoint ,[4]) as SP,ISNULL(@intHBPoint ,[14]) as HBP,              
   ISNULL(@intEBPoint ,[15]) as EBP,ISNULL(@intHAPoint ,[16]) as HAP,              
   ISNULL(@intEAPoint ,[17]) as EAP,ISNULL(@intACCPoint ,[66]) as ACP FROM (              
   SELECT mt.BoxMsgInTypeId, vr.Rating FROM rvlfViolationRating vr               
    INNER JOIN rvlfOrganization g ON vr.OrganizationID= g.OrganizationId              
    INNER JOIN rvlfBoxMsgInType mt ON mt.BoxMsgInTypeId = vr.BoxMsgInTypeID              
   WHERE vr.OrganizationID = @bigOrganizationID) as d               
  PIVOT (sum(rating) FOR Boxmsgintypeid in ([4],[14],[15],[16],[17],[66])) as p                 
                 
 SET NOCOUNT OFF              
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverBehaviour_RAG]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetDriverBehaviour_RAG]        
 @dtStartDate datetime = null,        
 @dtEndDate datetime = null,        
 @bigOrganizationID bigint = null,        
 @bigQueryingUser bigint = null,        
 @bigDriverID bigint = null,        
 @intSPoint int = null,        
 @intHBPoint int = null,        
 @intEBPoint int = null,        
 @intHAPoint int = null,        
 @intEAPoint int = null,        
 @intACCPoint int = null,        
 @bigFleetID bigint = null,        
 @intBoxID varchar(max) = null,        
 @vcDrivers varchar(25) = null         
AS        
/************************************************************************************************/              
-- Name  : rvlf_sp_GetDriverBehaviour_RAG '2015-06-03 08:00:00 AM','2015-06-04 10:00:00 AM',257,502,null,null,null,null,null,null,null,null      
-- Description : To get the driver behaviour              
-- Author  : Sakthi Gopinath S             
-- Company  : Angler Technologies              
/**************************************************************************************************/        
BEGIN        
SET NOCOUNT ON        
        
 Declare @dtFDate datetime =@dtStartDate          
 Declare @dtEDate datetime =@dtEndDate                
 ------- Included to get the user prefernces---------------------                
 DECLARE @HoursToBeAdded INT = 0                
 DECLARE @MinsToBeAdded INT = 0                
 DECLARE @DistanceCaptionPrefix varchar(15)                
 DECLARE @SpeedCaptionPrefix varchar(15)                
 DECLARE @ConversionFactor numeric (10,2) = 1.0                
 DECLARE @DefaultDateFormat INT = 0       
 DECLARE @orgName varchar(30) = null       
 DECLARE @fleetName varchar(30) = null                
           
 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,          
     @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 = @bigQueryingUser                
                
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                
 SELECT @orgName=OrganizationDisplayName FROM rvlfOrganization WHERE OrganizationId = @bigOrganizationID                
 IF @bigFleetID is null                
  BEGIN                
   SELECT @bigFleetID = FleetID,@fleetName=FleetName FROM rvlfFleet where IsDefault= 1 and OrganizationId = @bigOrganizationID                
  END                
                
 DECLARE @tblDriverBehaviour table (BehaviourID bigint identity (1,1),                 
   DriverID bigint,VehicleID bigint,AssignedFrom DateTime,                
   AssignedTo DateTime, VehDisplayName varchar(20), BoxId int,                
   SpeedRanking int, SpeedCount int,HarshBrakingRanking int, HarshBrakingCount int,                
   ExtremeBrakingRanking int,ExtremeBrakingCount int, HarshAccelerationRanking int,                
   HarshAccelerationCount int,ExtremeAccelerationRanking int, ExtremeAccelerationCount int,                
   AccidentRanking int,AccidentCount int,SpeedDuration int)                
                
 DECLARE @tblMessages table(                
  [MessageInID] [uniqueidentifier] NOT NULL,                
  [BoxId] [int] NOT NULL,                
  [OriginDateTime] [datetime] NULL,                
  [DateTimeReceived] [datetime] NULL,              
  [BoxMsgInTypeDesc] [varchar](50) NOT NULL,                
  [BoxMsgInTypeId] [tinyint] NOT NULL,                
  [CommInfo1] [varchar](15) NULL,                
  [CommInfo2] [int] NULL,                
  [Latitude] [decimal](10, 6) NULL,                
  [Longitude] [decimal](10, 6) NULL,                
  [Speed] [int] NULL,                
  [SpeedDisply] [varchar](15) NULL,                
  [Heading] [smallint] NULL,                
  [SensorMask] [varchar](max) NULL,                
  [CustomProp] [varchar](600) NULL,                
  [StreetAddress] [varchar](250) NOT NULL,                
  [IsArmed] [bit] NULL,                
  [NearestLandmark] [varchar](300) NULL,                
  [Priority] [tinyint] NULL,                
  [Vin] [varchar](20) NULL,                
  [LicensePlate] [varchar](20) NULL,             
  [Email] [varchar](2010) NULL,                
  [SMS] [varchar](160) NULL,                
  [VehicleID] [bigint],                
  [VehicleDescription] [varchar](50) NULL,                
  [VehDisplayName] [varchar](20) NULL,                
  [OrganizationId] [bigint] NULL,                
  [NotificationType] [varchar](22) NOT NULL,                
  [Duration] [varchar](max) NULL,                
  [FleetName] [varchar](100) NOT NULL,                
  [OrganizationName] [varchar](200) NOT NULL,                
  [DistanceCaption] [varchar](10) NOT NULL,                
  [SpeedCaption] [varchar](10) NOT NULL,                
  [MessageDetails] [varchar](max) NULL,              
  [DriverID] bigint                
 )                 
                 
 --GET THE BOXIDS FOR THE FLEET                
 DECLARE @vcBoxIds VARCHAR(MAX)=NULL                
  SELECT @vcBoxIds=COALESCE(@vcBoxIds,'')+CONVERT(VARCHAR,VA.BoxId)+',' FROM rvlfFleetVehicles FV                 
   INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=FV.VehicleId                 
  WHERE FV.FleetId=@bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR VA.BOXID=@intBoxID)                 
 -------------------------------------                
                 
 --GET THE DRIVERS FOR THE ORGANIZATION                
 DECLARE @vcDriverIds VARCHAR(MAX)=NULL                
  SELECT @vcDriverIds=COALESCE(@vcDriverIds,'')+CONVERT(VARCHAR,DM.DriverId)+','  FROM rvlfDriverMaster DM                
    LEFT OUTER JOIN rvlfDriverGroupAssignment DG ON DG.DriverId=DM.DriverId                 
   WHERE OrganizationID=@bigOrganizationID                 
    AND (@bigDriverID IS NULL OR @bigDriverID='' OR DM.DriverId=@bigDriverID)                 
    --AND (@bigDriverGroupId IS NULL OR @bigDriverGroupId='' OR DG.DriverGroupId=@bigDriverGroupId)                
                 
 --GET THE DRIVER TRIPS                
 DECLARE @tblDriverTrips TABLE                
 (                
  ProcessId bigint identity(1,1),                
  Boxid int null,                
  DriverId bigint null,                
  TripTime datetime null,           
  Customprop varchar(600) null,          
  Speed int null,           
  TripStatus varchar(5)null                 
 )                   
                 
 --GET THE FIRST PUNCH DETAILS FROM DRIVER ASSIGNMENT                
 DECLARE @DTFIRSTPUNCH DATETIME =NULL,@bitIsIbutton bit=null ,@bitIsRFID bit=null  
                 
 SELECT TOP 1 @DTFIRSTPUNCH=PunchIn FROM rvlfDriverAssignment                 
  WHERE BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                
   AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))                 
   AND PunchIn IS NOT NULL AND PunchOut IS NOT NULL      
   AND PunchIn BETWEEN @dtStartDate  AND @dtEndDate              
  ORDER BY PunchIn                 
                  
--CHECK IF THE PUNCH IS BEFORE THE STATDATEANDTIME                  
IF(@DTFIRSTPUNCH IS NOT NULL AND @DTFIRSTPUNCH<@dtStartDate)                
 BEGIN SET @DTFIRSTPUNCH=@dtStartDate END      
 ELSE IF (@DTFIRSTPUNCH IS NULL) BEGIN SET @DTFIRSTPUNCH=@dtStartDate END             
                 
 --GET THE IBUTTON RIGHTS FOR THE ORGANIZATION                
 SELECT @bitIsIbutton= CASE WHEN PO.PackageId IS NULL OR PO.PackageId ='' THEN 0 ELSE 1 END                 
  FROM rvlfPackageOperations PO                
   INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId                 
  WHERE OperationID =147 AND IsActive =1 AND OrganizationID=@bigOrganizationID                 
                 
 IF (@bitIsIbutton=1)                
  BEGIN                
   INSERT INTO @tblDriverTrips (Boxid,DriverId,TripTime,TripStatus)                
    SELECT BoxId,CASE WHEN CustomProp LIKE'%MAPID=%' THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,                
      (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))) ELSE 0 END,OriginDateTime,                
      SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,0)+14,                
    (CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,0))-(CHARINDEX('Driver Status=',CustomProp,0)+14)))                
     FROM rvlfMsgInHst                 
      WHERE BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                
       AND BoxMsgInTypeId =76                
       AND SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,                
        (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))) IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))                
       AND CustomProp LIKE'%Driver Status=%' AND CustomProp LIKE '%MAPID=%'                      
       --AND OriginDateTime BETWEEN @dtStartDate AND CASE WHEN @DTFIRSTPUNCH IS NOT NULL THEN CASE WHEN @DTFIRSTPUNCH BETWEEN @dtStartDate AND @dtEndDate THEN @DTFIRSTPUNCH ELSE @dtEndDate END ELSE @dtEndDate END                
       AND OriginDateTime BETWEEN @dtStartDate AND  @dtEndDate                 
      ORDER BY BoxId, SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,                
        (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))),OriginDateTime                
  END    
    
 SELECT  @bitIsRFID = CASE WHEN PO.OperationID=188 AND (PO.PackageId IS NULL OR PO.PackageId ='') THEN 0 WHEN PO.OperationID=188 THEN 1  END  FROM rvlfPackageOperations PO INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId               



 WHERE OperationID IN (188) AND IsActive =1 AND OrganizationID=@bigOrganizationID     
      
 IF (@bitIsRFID =1) --RFID 29-may15     
  BEGIN        
   INSERT INTO @tblDriverTrips (Boxid,DriverId,TripTime,TripStatus)      
   SELECT h.BoxId,DM.DriverId,h.OriginDateTime,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Punch:',';')      
   FROM rvlfMsgInHst h       
   INNER JOIN rvlfIButtonMapping BM ON (IButtonKey=dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'RF_ID=',';')) AND BM.KeyType in(2,3)        
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=BM.DriverId        
   WHERE h.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))        
   AND ((h.BoxMsgInTypeId=100 AND h.CustomProp like '%RF_ID=%') )        
   AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate          
   AND BoxMsgInTypeId IN(100)      
   ORDER BY h.BoxId,h.MessageInID,DM.DriverId,h.OriginDateTime          
  END  
   
  -- select * from @tblDriverTrips             
 --GET THE TRIPS                
 DECLARE @tblDriverTripDetails TABLE                
 (                  
  TripId bigint identity(1,1),                
  Boxid int null,                
  DriverId bigint null,                
  StartTime datetime null,                
  EndTime datetime null,                
  TripInStatus varchar(5) null,                
  TripOutStatus varchar(5) null,        
  OdoStart bigint null,        
  OdoEnd bigint null,        
  Speed int null,        
  SpeedDuration int null                 
 )                 
 INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)                
 SELECT MT.Boxid,MT.DriverId,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus                
   FROM @tblDriverTrips AS MT                 
    LEFT OUTER JOIN @tblDriverTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'IN' and MT.DriverId=ST.DriverId                      
                  
 --DELETE THE INVALID TRIPS                  
 DELETE FROM @tblDriverTripDetails WHERE StartTime IS NULL --OR TripInStatus=TripOutStatus                 
                 --commented to fix the rfid based trips
-- --GET THE MANUEL AND AUTOMATIC SCHEDULES                
-- IF(@DTFIRSTPUNCH IS NOT NULL)                
--  BEGIN                
--   INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)                
--   SELECT BoxId,DriverId,CASE WHEN PunchOut IS NULL THEN ToTime ELSE PunchOut END,'OUT',                
--    CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END,'IN'                  
--    FROM rvlfDriverAssignment                  
--    WHERE @DTFIRSTPUNCH BETWEEN (CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END)      
-- AND (CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END)      
--     --@DTFIRSTPUNCH <= CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END                 
--     --AND @dtEndDate >= CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END                
--     AND BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                
--     AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))              
               
--  END                
-- ELSE                
--  BEGIN                
--   INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)                
--   SELECT BoxId,DriverId,CASE WHEN PunchOut IS NULL THEN ToTime ELSE PunchOut END,'OUT',                
--    CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END,'IN'                  
--    FROM rvlfDriverAssignment                  
--     WHERE @dtStartDate BETWEEN (CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END)      
--   AND (CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END)      
--   --@dtStartDate <= CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END                 
--      --AND @dtEndDate >= CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END                
--AND BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                
--      AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))                 
--  END                
        
--GET THE TRIP DETAILS        
         
 DECLARE @bigTripid bigint=null        
 SELECT @bigTripid = MIN(TripId) FROM @tblDriverTripDetails          
 WHILE (@bigTripid IS NOT NULL)        
  BEGIN        
   DECLARE @dtTripStart datetime=null,@dtTripEnd datetime=null        
   SET @intBoxID=NULL        
   SELECT @intBoxID=Boxid,@dtTripStart =StartTime,@dtTripEnd=EndTime FROM @tblDriverTripDetails WHERE TripId=@bigTripid         
   DELETE FROM @tblDriverTrips         
   INSERT INTO @tblDriverTrips (Customprop,Speed,TripTime)        
    SELECT CustomProp,Speed,OriginDateTime        
    FROM rvlfMsgInHst H        
     LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID          
    WHERE BoxId=@intBoxID AND OriginDateTime BETWEEN @dtTripStart AND @dtTripEnd         
     AND BoxMsgInTypeId IN(SELECT DISTINCT MT.BoxMsgInTypeId  FROM rvlfUserGroupSecurity UGS         
        INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId         
        INNER JOIN rvlfBoxMsgInType MT ON MT.OperationTypeID=UGS.OperationTypeId         
       WHERE UGA.UserId=@bigQueryingUser)ORDER BY OriginDateTime         
                  
   UPDATE @tblDriverTripDetails SET        
    Speed=(SELECT ISNULL(MAX(Speed),0) FROM @tblDriverTrips WHERE Speed!=0 AND Speed IS NOT NULL),         
    OdoStart=(SELECT TOP 1 CASE WHEN CustomProp LIKE '%Odometer=%' THEN         
      SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,        
      CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END from @tblDriverTrips ),        
    OdoEnd=(SELECT TOP 1 CASE WHEN CustomProp LIKE '%Odometer=%' THEN         
      SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,        
      CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END from @tblDriverTrips ORDER BY TripTime DESC),        
    SpeedDuration = (SELECT SUM(CASE WHEN Customprop like '%Speed with Duration:%' THEN CAST(SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,        
        CHARINDEX(';',CustomProp)-1 -CHARINDEX(':',CustomProp,1)) AS int) ELSE 0 END) FROM @tblDriverTrips GROUP BY DriverId)        
   WHERE TripId=@bigTripid         
             
   SELECT @bigTripid =MIN(TripId) FROM @tblDriverTripDetails WHERE TripId >@bigTripid             
  END        
        
 DECLARE @tblSummary TABLE        
 (        
  DriverId bigint null,        
  TotDistance int null,        
  MaxSpeed int null,        
  TotSpeedDuration int null        
 )         
 INSERT INTO @tblSummary (DriverId,TotDistance,MaxSpeed,TotSpeedDuration)        
 SELECT DriverId,SUM((OdoEnd-OdoStart)),MAX(Speed),SUM(SpeedDuration) FROM @tblDriverTripDetails GROUP BY DriverId         
             
 -- INSERT DRIVER IN PUNCHES                 
 INSERT INTO @tblDriverBehaviour                 
    (DriverID, VehicleID, AssignedFrom, AssignedTo, VehDisplayName, BoxId,                
    SpeedRanking, SpeedCount, HarshBrakingRanking, HarshBrakingCount, ExtremeBrakingRanking,                 
    ExtremeBrakingCount, HarshAccelerationRanking, HarshAccelerationCount,                 
    ExtremeAccelerationRanking, ExtremeAccelerationCount,AccidentRanking,AccidentCount)                
 SELECT DriverId,VA.VehicleId,StartTime,EndTime,V.VehicleDescription,TD.Boxid,0,0,0,0,0,0,0,0,0,0,0,0                  
 FROM @tblDriverTripDetails TD                
 INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=TD.Boxid                 
    INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId                 
                      --commented because not use any where 06-amy16
  -- INSERT THE MESSAGES WHICH HAS COME BETWEEN THE DRIVER PUNCH IN AND OUT              
 --INSERT INTO @tblMessages                 
 --  SELECT                 
 --   h.MessageInID, h.BoxId,                
 --   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime))OriginDateTime,                 
 --   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.DateTimeReceived))DateTimeReceived,                 
 --   m.BoxMsgInTypeDesc, m.BoxMsgInTypeId,                
 --   h.CommInfo1, h.CommInfo2, h.Latitude, h.Longitude,                 
 --   CASE WHEN h.BoxMsgInTypeId=51 THEN 0 ELSE CAST (CAST(h.Speed AS numeric(10,2)) * @ConversionFactor  as int) END as Speed,                
 --   CASE WHEN H.BoxMsgInTypeId =51 THEN NULL ELSE CAST(CAST(h.Speed * @ConversionFactor as INT) AS VARCHAR)+ CASE WHEN CustomProp LIKE '%speed1=%' THEN ' --> '+ CAST(CAST((CAST(SUBSTRING(CustomProp,CHARINDEX('speed1=',CustomProp,0)+7,(LEN(CustomProp))) AS

  
    
        
 --INT)* @ConversionFactor) AS INT) AS VARCHAR) ELSE ''  END  END  as Speed1,                 
 --    h.Heading,                 
 --   CASE WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3                
 --   OR h.BoxMsgInTypeId = 13 THEN                 
 --    dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID, h.BoxId, h.MessageInID, h.OriginDateTime)                
 --    ELSE ' ' END as SensorMask,                
 --   h.CustomProp, ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress, h.IsArmed, h.NearestLandmark,                
 --   h.Priority, v.Vin, v.LicensePlate, v.Email, v.SMS,v.VehicleId,v.VehicleDescription, v.VehicleDescription AS DisplayName,                
 --   v.OrganizationId, CASE WHEN v.Notify=1 THEN 'Notify'                 
 --   WHEN v.Warning=1 THEN 'Warning' WHEN v.Critical =1 THEN 'Critical'                 
 --   ELSE 'No Notification is set' END as NotificationType,                 
 --   (CASE WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3 OR h.BoxMsgInTypeId = 13                  
 --    THEN dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID ,h.BoxId, h.MessageInID, h.OriginDateTime)                
 --      WHEN h.BoxMsgInTypeId = 4 THEN ''                
 --      WHEN m.BoxMsgInTypeDesc<>'Sensor'                
 --    THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN                 
 --    dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1) END)                
 --    ELSE '' END) as Duration,                
 --   f.FleetName, g.OrganizationName, @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,                
 --   CASE WHEN h.BoxMsgInTypeId = 28  THEN m.BoxMsgInTypeDesc                 
 --      WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +                
 --      CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +                
 --     dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'                
 --    ELSE                
 --   dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime)END  as MessageDetails,                
 --   db.DriverID                
 --  FROM rvlfMsgInHst h                 
 --   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                
 --   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                
 --   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId                
 --   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID                 
 --   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
 --   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId                
 --   INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId                
 --   INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId                
 --   INNER JOIN @tblDriverBehaviour db ON db.BoxId = va.BoxId         
 --   WHERE                
 --    (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND                 
 --    m.Isviolation=1 AND                
 --    (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR h.BoxId = @intBoxID) AND                
 --      h.OriginDateTime BETWEEN (CASE WHEN DATEDIFF(dd,db.AssignedFrom,db.AssignedTo) > 1 THEN @dtStartDate      
 --     ELSE db.AssignedFrom END) AND db.AssignedTo                
                         
  DECLARE @intIterator int;                
  --DECLARE @intBoxID int                
  DECLARE @dtAssignedFromDate Datetime                
  DECLARE @dtAssignedToDate Datetime                
  DECLARE @intSpeedRanking int                
  DECLARE @intSpeedCount int                
  DECLARE @intHarshBrakingRanking int                
  DECLARE @intHarshBrakingCount int                
  DECLARE @intExtremeBrakingRanking int                
  DECLARE @intExtremeBrakingCount int                
  DECLARE @intHarshAccelerationRanking int                
  DECLARE @intHarshAccelerationCount int                
  DECLARE @intExtremeAccelerationRanking int                
  DECLARE @intExtremeAccelerationCount int                
  DECLARE @intAccidentCount int                
  DECLARE @intAccidentRanking int              
  DECLARE @speedDuration int            
  SELECT @intIterator = MAX(BehaviourID) FROM @tblDriverBehaviour   
          
  --SELECT * FROM @tblDriverBehaviour        
                  
  WHILE @intIterator IS NOT NULL                
   BEGIN                
    SELECT @intBoxID = BoxId, @dtAssignedFromDate = AssignedFrom,                
     @dtAssignedToDate = AssignedTo , @bigDriverID = DriverID                
     from @tblDriverBehaviour WHERE BehaviourID = @intIterator                
    SET @intSpeedRanking = 0; SET @intSpeedCount  = 0; SET @intHarshBrakingRanking = 0; SET @intHarshBrakingCount = 0;                
    SET @intExtremeBrakingRanking = 0; SET @intExtremeBrakingCount = 0; SET @intHarshAccelerationRanking = 0;                
    SET @intHarshAccelerationCount = 0; SET @intExtremeAccelerationRanking = 0; SET @intExtremeAccelerationCount = 0;            
    SET @intAccidentCount=0; SET @intAccidentRanking=0; SET @speedDuration=0;        
                 
            
    --SELECT         
    -- --MAX(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) END) AS MaxOdometer,        
    -- --MIN(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) END) AS MinOdometer,        
    --  @distanceCalc =(MAX(CASE WHEN h.CustomProp LIKE '%Odometer=%' THEN CAST(SUBSTRING (h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)+9,CHARINDEX(';',h.CustomProp,                
    --  CHARINDEX('Odometer=',h.CustomProp,1)) - (CHARINDEX('Odometer=',h.CustomProp,1)+9)) as bigint) END) - MIN(CASE WHEN h.CustomProp LIKE '%Odometer=%' THEN         
    --  CAST(SUBSTRING(h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)+9,CHARINDEX(';',h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)) -         
    --  (CHARINDEX('Odometer=',h.CustomProp,1)+9)) as bigint) END)),          
    --  @maxSpeed= MAX(h.Speed)        
    --FROM rvlfMsgInHst h                 
    -- INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                
    -- --LEFT OUTER JOIN rvlfViolationRating r ON h.BoxMsgInTypeId = r.BoxMsgInTypeID                
    --WHERE                
    -- --r.OrganizationId= @bigOrganizationID and                 
    -- (@intBoxID IS NULL OR @intBoxID='' OR h.BoxId = @intBoxID) AND                
    -- (h.OriginDateTime BETWEEN @dtAssignedFromDate AND @dtAssignedToDate)                
    --Group By h.BoxId            
               
    SELECT                 
     @intSpeedRanking = SUM(CASE WHEN h.BoxMsgInTypeId = 4 THEN ISNULL(@intSPoint ,r.Rating) ELSE 0 END),                
     @intSpeedCount = SUM(CASE WHEN h.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END),                
     @intHarshBrakingRanking =SUM(CASE WHEN h.BoxMsgInTypeId = 14 THEN ISNULL(@intHBPoint, r.Rating) ELSE 0 END),                
     @intHarshBrakingCount = SUM(CASE WHEN h.BoxMsgInTypeId = 14 THEN 1 ELSE 0 END),                
     @intExtremeBrakingRanking = SUM(CASE WHEN h.BoxMsgInTypeId = 15 THEN ISNULL(@intEBPoint,r.Rating) ELSE 0 END),                
     @intExtremeBrakingCount = SUM(CASE WHEN h.BoxMsgInTypeId = 15 THEN 1 ELSE 0 END),                
     @intHarshAccelerationRanking = SUM(CASE WHEN h.BoxMsgInTypeId = 16 THEN ISNULL(@intHAPoint,r.Rating) ELSE 0 END),                
     @intHarshAccelerationCount = SUM(CASE WHEN h.BoxMsgInTypeId = 16 THEN 1 ELSE 0 END),                
     @intExtremeAccelerationRanking = SUM(CASE WHEN h.BoxMsgInTypeId = 17 THEN ISNULL(@intEAPoint,r.Rating) ELSE 0 END),                
     @intExtremeAccelerationCount = SUM(CASE WHEN h.BoxMsgInTypeId = 17 THEN 1 ELSE 0 END),                
     @intAccidentRanking= SUM(CASE WHEN h.BoxMsgInTypeId = 66 THEN ISNULL(@intACCPoint,r.Rating) ELSE 0 END),                 
     @intAccidentCount = SUM(CASE WHEN h.BoxMsgInTypeId = 66 THEN 1 ELSE 0 END),        
     @speedDuration = SUM(CASE WHEN h.BoxMsgInTypeId = 51 THEN CAST(SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,        
  CHARINDEX(';',CustomProp)-1 -CHARINDEX(':',CustomProp,1)) AS int) ELSE 0 END)        
     FROM rvlfMsgInHst h                 
     INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                
     LEFT OUTER JOIN rvlfViolationRating r ON h.BoxMsgInTypeId = r.BoxMsgInTypeID                
     WHERE                
     r.OrganizationId= @bigOrganizationID and                 
     (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR h.BoxId = @intBoxID) AND                
     (h.OriginDateTime BETWEEN (CASE WHEN DATEDIFF(dd,@dtAssignedFromDate,@dtAssignedToDate) > 1 THEN @dtStartDate      
      ELSE @dtAssignedFromDate END) AND @dtAssignedToDate)                
    Group By h.BoxId                
                     
    Update @tblDriverBehaviour SET SpeedRanking = @intSpeedRanking, SpeedCount = @intSpeedCount,                
     HarshBrakingRanking = @intHarshBrakingRanking, HarshBrakingCount = @intHarshBrakingCount,                
     ExtremeBrakingRanking = @intExtremeBrakingRanking, ExtremeBrakingCount = @intExtremeBrakingCount,                
     HarshAccelerationRanking = @intHarshAccelerationRanking, HarshAccelerationCount = @intHarshAccelerationCount,                
     ExtremeAccelerationRanking = @intExtremeAccelerationRanking, ExtremeAccelerationCount = @intExtremeAccelerationCount,                
     AccidentRanking=@intAccidentRanking,AccidentCount=@intAccidentCount,SpeedDuration=@speedDuration        
    WHERE BehaviourID = @intIterator                
                    
    SELECT @intIterator = MAX(BehaviourID) FROM @tblDriverBehaviour WHERE BehaviourID < @intIterator                
   END                
          
  SELECT rpt.*,CAST((rpt.ACCPer100KM+rpt.DCCPer100KM+rpt.SecPerKm) AS DECIMAL(6,2)) AS TotalScore,      
  @fleetName AS FleetName,@orgName AS OrganizationName,      
  Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,      
  Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,      
   PasGenerateddate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())      
  --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate       

  
  FROM        
  (SELECT RAG.DriverID,RAG.DriverDispName,ISNULL(ts.TotDistance,0) AS Distance,RAG.AccelerationCount,        
  CASE WHEN ISNULL(ts.TotDistance,0)=0 THEN 0 ELSE ((100*(RAG.AccelerationCount))/CAST(ISNULL(ts.TotDistance,0) AS DECIMAL(6,2))) END AS ACCPer100KM,        
  RAG.DeccelerationCount,        
  CASE WHEN ISNULL(ts.TotDistance,0)=0 THEN 0 ELSE ((100*( RAG.DeccelerationCount))/CAST(ISNULL(ts.TotDistance,0) AS DECIMAL(6,2))) END AS DCCPer100KM,          
  ts.MaxSpeed,dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(ts.TotSpeedDuration,0)) AS OverSpeedTime,        
  CAST((CASE WHEN ISNULL(ts.TotDistance,0)=0 THEN CAST(0 as decimal(6,2)) ELSE (SecPerKm / ts.TotDistance) END) AS DECIMAL(6,2)) AS SecPerKm FROM        
   (SELECT DD.DriverID,d.DriverName, d.DisplayName as DriverDispName, d.MobileNo as DriverMobileNo,          
   (DD.HAC + DD.EAC) AS AccelerationCount, (DD.HBC + DD.EBC) AS DeccelerationCount,SD AS SpeedDuration,        
   CAST((SD/10) AS DECIMAL(6,2)) AS SecPerKm        
   FROM(SELECT AB.DriverID, SUM(AB.SpeedRanking) as SR, SUM(AB.SpeedCount) as SC,                
   SUM(AB.HarshBrakingRanking) HBR, SUM(AB.HarshBrakingCount) as HBC, SUM(AB.ExtremeBrakingRanking) EBR,                
   SUM(AB.ExtremeBrakingCount) EBC, SUM(AB.HarshAccelerationRanking) HAR, SUM(AB.HarshAccelerationCount) as HAC,                
   SUM(AB.ExtremeAccelerationRanking) EAR, SUM(AB.ExtremeAccelerationCount) as EAC,SUM(AB.AccidentCount) as ACC,                
   SUM(AB.AccidentRanking) ACR,SUM(AB.SpeedDuration) SD               
   FROM @tblDriverBehaviour AB LEFT JOIN @tblDriverBehaviour db On db.BehaviourID=AB.DriverID          
   GROUP BY AB.DriverID) DD INNER JOIN rvlfDriverMaster d ON d.DriverId= DD.DriverID          
   --INNER JOIN (SELECT DriverID,SUM(DistanceTravelled) AS Distance,MAX(Speed) AS MaxSpeed FROM @tblDriverBehaviour GROUP BY DriverID)           
   --AS m ON m.DriverID = d.DriverID        
   ) RAG INNER JOIN         
   @tblSummary ts ON ts.DriverId=RAG.DriverID) rpt        
   ORDER BY rpt.DriverID        
        
  ---Dummy Data for RAG----------      
 --DECLARE @tblRAG TABLE      
 --(      
 -- DriverID int,      
 -- DriverDispName varchar(25),      
 -- Distance int,      
 -- AccelerationCount int,      
 -- DeccelerationCount int,      
 -- MaxSpeed int,      
 -- Duration int,      
 -- OverSpeedTime time      
 --)      
 --INSERT INTO @tblRAG VALUES(1,'Test Driver',137,1,1,65,2,'00:00:2.000')      
 --INSERT INTO @tblRAG VALUES(2,'Smith',376,4,2,93,0,'00:00:00.000')      
 --INSERT INTO @tblRAG VALUES(3,'McCoy',525,4,10,87,0,'00:00:00.000')      
 --INSERT INTO @tblRAG VALUES(4,'John',177,2,4,58,0,'00:00:00.000')      
 --INSERT INTO @tblRAG VALUES(5,'Tan',350,3,16,71,0,'00:00:00.000')      
 --INSERT INTO @tblRAG VALUES(6,'Dinesh',108,2,4,73,0,'00:00:00.000')      
 --INSERT INTO @tblRAG VALUES(7,'Skoar',229,16,4,74,0,'00:00:00.000')      
 --INSERT INTO @tblRAG VALUES(8,'Raja',112,8,4,80,0,'00:00:00.000')      
 --SELECT RAG.*,(RAG.AccPer100KM+RAG.DccPer100KM+RAG.SecPerKm) AS TotalScore,      
 --@fleetName AS FleetName,@orgName AS OrganizationName,      
 --Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,      
 --Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,      
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate         

 --FROM      
 --(SELECT  DriverID,DriverDispName,Distance,AccelerationCount,      
 --Cast((100/CAST(Distance AS decimal(6,2)))*AccelerationCount AS decimal(6,2)) AS AccPer100KM,      
 --DeccelerationCount,      
 --Cast((100/CAST(Distance AS decimal(6,2)))*DeccelerationCount AS decimal(6,2)) AS DccPer100KM,      
 --MaxSpeed,OverSpeedTime,      
 --CAST(((Duration/Cast(10 AS decimal(6,2)))/Distance) AS decimal(6,2)) AS SecPerKm       
 --FROM @tblRAG) RAG      
    ---End Dummy Data for RAG----------      
        
SET NOCOUNT OFF        
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverGroupAssignment]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetDriverGroupAssignment]        
 @driverGroupId bigint = null      
AS        
/******************************************************************************/        
-- Name  : [rvlf_sp_GetDriverGroupAssignment] 82,999987,null,6        
-- Description : To get the Driver list based on driver group
-- Author  : N .Ranjith        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  02-MAr-2012 
/******************************************************************************/        

BEGIN        
      select * from rvlfDriverGroupAssignment where DriverGroupId  =@driverGroupId
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverIncentives]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetDriverIncentives]
	@bigTripId bigint=null,
	@bigOrganizationId bigint=null,
	@intHoursToBeAdded INT = null,
	@intMinsToBeAdded INT = null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_GetDriverIncentives]172,6,5,30
--	Description	:	To get the driver incentive details
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	19-Oct-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN
	
	DECLARE @DTFROMTIME DATETIME=NULL
	DECLARE @DTTOTIME DATETIME=NULL
	DECLARE @BIGVEHICLEID BIGINT=NULL
	DECLARE @VCVEHICLETYPE VARCHAR(5)=NULL
	DECLARE @ODOSTART BIGINT=NULL
	DECLARE @ODOEND BIGINT=NULL
	DECLARE @BIGDRIVERID BIGINT=NULL
	DECLARE @DTTRIPSTART DATETIME=NULL
	DECLARE @DTTRIPEND DATETIME=NULL
	DECLARE @TINOOFDRIVERS TINYINT=1 

--GET THE TRIP DETAILS
SELECT @DTFROMTIME=FromTime,@DTTOTIME=ToTime,@BIGVEHICLEID=VA.VehicleId,@BIGDRIVERID=DriverId  
	FROM rvlfDriverAssignment DA 
		INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=DA.BOXID  
	WHERE AssignmentId  =@bigTripId 

--GET THE NO OF DRIVER IN THE TRIP
IF EXISTS(SELECT DriverId FROM rvlfDriverAssignment WHERE AssignmentId=@bigTripId AND TripId IS NOT NULL)
	BEGIN
		SET @TINOOFDRIVERS=2
	END 
ELSE
	BEGIN
		SET @TINOOFDRIVERS=1
	END
--GET THE VEHICLE TYPE
SELECT @VCVEHICLETYPE =Category FROM rvlfVehicle WHERE VehicleId=@BIGVEHICLEID 

IF (@VCVEHICLETYPE IS NOT NULL)
BEGIN
DECLARE @TBLMSGS TABLE(
	MessageId uniqueidentifier,
	DateandTime datetime,
	customParam varchar(600),
	BoxtypeId int	
)

--INSERT THE MESSAGE DETAILS TO TEMP TABLE
INSERT INTO @TBLMSGS (MessageId,DateandTime,customParam,BoxtypeId)
	SELECT MessageInID,OriginDateTime,CustomProp,BoxMsgInTypeId FROM rvlfMsgInHst WHERE OriginDateTime BETWEEN @DTFROMTIME AND @DTTOTIME AND BoxId =(SELECT BoxId FROM rvlfVehicleAssignment WHERE VehicleId=@BIGVEHICLEID)

--GET THE ODOMETER START AND END VALUES 
	SELECT TOP 1 @ODOSTART=(CASE WHEN customParam LIKE '%Driver Status=%' THEN CAST( SUBSTRING (customParam,CHARINDEX('Odometer=',customParam,1)+9,CHARINDEX(';',customParam,
								CHARINDEX('Odometer=',customParam,1)) - (CHARINDEX('Odometer=',customParam,1)+9)) as bigint) END ),@DTTRIPSTART=DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DateandTime))
			FROM @TBLMSGS WHERE BoxtypeId=76 
							AND CASE WHEN customParam LIKE '%MAPID=%' THEN CAST(SUBSTRING(customParam,CHARINDEX('MAPID=',customParam,1)+6,LEN(customParam))AS BIGINT) END=@BIGDRIVERID 
							AND CASE WHEN customParam LIKE '%Driver Status=%' THEN CAST( SUBSTRING (customParam,CHARINDEX('Driver Status=',customParam,1)+14,CHARINDEX(';',customParam,
								CHARINDEX('Driver Status=',customParam,1)) - (CHARINDEX('Driver Status=',customParam,1)+14)) as VARCHAR) END='IN' ORDER BY DateandTime ASC
								
	SELECT TOP 1 @ODOEND=(CASE WHEN customParam LIKE '%Driver Status=%' THEN CAST( SUBSTRING (customParam,CHARINDEX('Odometer=',customParam,1)+9,CHARINDEX(';',customParam,
								CHARINDEX('Odometer=',customParam,1)) - (CHARINDEX('Odometer=',customParam,1)+9)) as bigint) END ),
			@DTTRIPEND=DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DateandTime)) 								 
			FROM @TBLMSGS WHERE BoxtypeId=76
								AND CASE WHEN customParam LIKE '%MAPID=%' THEN CAST(SUBSTRING(customParam,CHARINDEX('MAPID=',customParam,1)+6,LEN(customParam))AS BIGINT) END=@BIGDRIVERID
								AND CASE WHEN customParam LIKE '%Driver Status=%' THEN CAST( SUBSTRING (customParam,CHARINDEX('Driver Status=',customParam,1)+14,CHARINDEX(';',customParam,
								CHARINDEX('Driver Status=',customParam,1)) - (CHARINDEX('Driver Status=',customParam,1)+14)) as VARCHAR) END='OUT' ORDER BY DateandTime DESC								
	
--IF THE ODOSTART,ODOEND VALUE IS NULL	THAN GET THE PRIVIOUS ODOMETER START VALUE 
IF(@ODOSTART IS NULL)
	BEGIN
		SELECT TOP 1 @DTFROMTIME=OriginDateTime,@ODOSTART=(CASE WHEN CustomProp LIKE '%Driver Status=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Odometer=',CustomProp,1)+9,CHARINDEX(';',CustomProp,
								CHARINDEX('Odometer=',CustomProp,1)) - (CHARINDEX('Odometer=',CustomProp,1)+9)) as bigint) END ),
								@DTTRIPSTART=DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,OriginDateTime))
			FROM rvlfMsgInHst WHERE BoxMsgInTypeId=76 
							AND CASE WHEN CustomProp LIKE '%MAPID=%' THEN  CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))AS BIGINT) END=@BIGDRIVERID AND OriginDateTime < @DTFROMTIME 
							AND CONVERT(DATE,OriginDateTime)=CONVERT(DATE,@DTFROMTIME)
							AND CASE WHEN CustomProp LIKE '%Driver Status=%' THEN CAST(SUBSTRING (CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,CHARINDEX(';',CustomProp,
								CHARINDEX('Driver Status=',CustomProp,1)) - (CHARINDEX('Driver Status=',CustomProp,1)+14)) as VARCHAR) END='IN' ORDER BY OriginDateTime DESC								
	END

IF(@ODOEND IS NULL)
	BEGIN
		SELECT TOP 1 @DTTOTIME=OriginDateTime,@ODOEND=(CASE WHEN CustomProp LIKE '%Driver Status=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Odometer=',CustomProp,1)+9,CHARINDEX(';',CustomProp,
								CHARINDEX('Odometer=',CustomProp,1)) - (CHARINDEX('Odometer=',CustomProp,1)+9)) as bigint) END ),
							@DTTRIPEND =DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,OriginDateTime))
			FROM rvlfMsgInHst WHERE BoxMsgInTypeId=76 
							AND CASE WHEN CustomProp LIKE '%MAPID=%' THEN  CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))AS BIGINT) END=@BIGDRIVERID AND OriginDateTime > @DTFROMTIME 
							AND CONVERT(DATE,OriginDateTime)=CONVERT(DATE,@DTFROMTIME)
							AND CASE WHEN CustomProp LIKE '%Driver Status=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,CHARINDEX(';',CustomProp,
								CHARINDEX('Driver Status=',CustomProp,1)) - (CHARINDEX('Driver Status=',CustomProp,1)+14)) as VARCHAR) END='OUT' ORDER BY OriginDateTime ASC											
	END	

DELETE FROM @TBLMSGS 
	
--INSERT THE MESSAGE DETAILS TO TEMP TABLE
INSERT INTO @TBLMSGS (MessageId,DateandTime,customParam,BoxtypeId)
	SELECT MessageInID,OriginDateTime,CustomProp,BoxMsgInTypeId FROM rvlfMsgInHst WHERE OriginDateTime BETWEEN @DTFROMTIME AND @DTTOTIME AND BoxId =(SELECT BoxId FROM rvlfVehicleAssignment WHERE VehicleId=@BIGVEHICLEID)	
	
--CALCULATE THE INCENTIVES
IF(@ODOSTART IS NOT NULL AND @ODOEND IS NOT NULL)
	BEGIN
		DECLARE @TOTALDISTANCE INT=NULL
		
		--CALCULATE THE TOTAL DISTANCE DRIVEN 
		SET @TOTALDISTANCE =@ODOEND -@ODOSTART 						
		
		--DECLARE INSENTIVE DETAILS TABLE
		DECLARE @TBLINCENTIVES TABLE
		(
			DriverName varchar(30),
			DriverName1 varchar(30),
			MobileNo varchar(20),
			MobileNo1 varchar(20),
			LicenseNo varchar(50),
			LicenseNo1 varchar(50),
			VehicleName varchar(30),
			VehicleType varchar(5),
			LicensePlate varchar(50),
			ScheduleDate datetime,
			FormPlace varchar(50),
			ToPlace varchar(50),
			StartTime TIME(7),
			EndTime TIME(7),
			OdoStart bigint,
			OdoEnd bigint,
			TotalDistance int,
			IncentiveName varchar(50),
			IncentiveAmt numeric(10,2)	
		)
		
		DECLARE @TBLALLOWANCES TABLE
		(
			AllowanceId bigint,
			AllowanceName varchar(50),
			FromTime time(7),
			ToTime time(7),
			Amt numeric(7,2),
			Ignition bit,
			ProcessStatus bit			
		)
		
		DECLARE @BIGINCENTIVEID BIGINT=NULL		
		--GET THE INCENTIVE DETAILS FROM THE INCENTIVE TABLE
		SELECT @BIGINCENTIVEID=BattaId FROM rvlfDriverBattaDetails 
			WHERE OrganizationId=@bigOrganizationId AND Active =1 AND VehicleType=@VCVEHICLETYPE 
				AND @TOTALDISTANCE BETWEEN FromRange AND ToRange 
				AND OrganizationId=@bigOrganizationId 
				AND NoOfDrivers=@TINOOFDRIVERS 
		IF (@BIGINCENTIVEID IS NULL)
			SELECT @BIGINCENTIVEID=BattaId FROM rvlfDriverBattaDetails 
				WHERE OrganizationId=@bigOrganizationId AND Active =1 AND VehicleType=@VCVEHICLETYPE 
					AND @TOTALDISTANCE BETWEEN FromRange AND ToRange 
					AND OrganizationId=@bigOrganizationId 
					AND NoOfDrivers=0	
		--GET THE ALLOWANCE DETAILS FROM THE INCENTIVE TABLE

		INSERT INTO @TBLALLOWANCES(AllowanceId,AllowanceName,FromTime,ToTime,Amt,Ignition,ProcessStatus)
		SELECT BattaId,Description,FromTime,ToTime,OtherAmt,IgnitionStatus,0  FROM rvlfDriverBattaDetails 
			WHERE OrganizationId=@bigOrganizationId AND Active =1 AND VehicleType=@VCVEHICLETYPE 
				AND FromTime IS NOT NULL AND ToTime IS NOT NULL
				AND (NoOfDrivers=@TINOOFDRIVERS OR NoOfDrivers=0)
		
		IF(@BIGINCENTIVEID IS NOT NULL)
			BEGIN
				--CALCULATE THE INCENTIVE BASED ON THE DISTANCE
				INSERT INTO @TBLINCENTIVES(DriverName,DriverName1,MobileNo,MobileNo1,LicenseNo,LicenseNo1,
					VehicleName,VehicleType,LicensePlate,ScheduleDate,FormPlace,ToPlace,StartTime,EndTime,OdoStart,
					OdoEnd,TotalDistance,IncentiveName,IncentiveAmt)
				SELECT DM.DisplayName,DM1.DisplayName,DM.MobileNo,DM1.MobileNo,DM.LicenseNo,DM1.LicenseNo,
					V.VehicleDescription,V.Category,V.LicensePlate,CONVERT(VARCHAR,DA.AssignmentDate,106),
					L1.LandmarkName,L2.LandmarkName,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DA.FromTime))),
					CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DA.ToTime))),
					@ODOSTART,@ODOEND,@TOTALDISTANCE,DB.Description,(@TOTALDISTANCE * DB.RatePerKM)+ISNULL(DB.OtherAmt,0)  
					FROM rvlfDriverAssignment DA
						LEFT OUTER JOIN rvlfDriverAssignment DA1 ON DA1.TripId=DA.AssignmentId 
						INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId
						LEFT OUTER JOIN rvlfDriverMaster DM1 ON DM1.DriverId=DA1.DriverId
						INNER JOIN RVLFVEHICLEASSIGNMENT VA ON VA.BOXID=DA.BOXID 
						INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId  
						LEFT OUTER JOIN rvlfLandmark L1 ON L1.LandmarkID=DA.FromLandmarkId 
						LEFT OUTER JOIN rvlfLandmark L2 ON L2.LandmarkID =DA.ToLandmarkId
						INNER JOIN rvlfDriverBattaDetails DB ON DB.BattaId=@BIGINCENTIVEID 
					WHERE DA.ASSIGNMENTID=@bigTripId 
			END	
			
		--CALCULATE THE ALLOWANCES BASED ON THE IGNITION ON SETUP
		WHILE EXISTS(SELECT AllowanceId FROM @TBLALLOWANCES WHERE ProcessStatus=0)
			BEGIN
				SET @BIGINCENTIVEID=NULL
				DECLARE @FROMTIME TIME=NULL
				DECLARE @TOTIME TIME=NULL				
				DECLARE @IGNITION BIT=NULL
				SELECT TOP 1 @BIGINCENTIVEID=AllowanceId,@FROMTIME=FromTime,@TOTIME=ToTime,@IGNITION=Ignition FROM @TBLALLOWANCES where ProcessStatus=0
			
			IF(@IGNITION =1)
				BEGIN				
				IF(CONVERT(TIME,@DTTRIPSTART)<=@FROMTIME AND CONVERT(TIME,@DTTRIPEND)>=@TOTIME)
					BEGIN
						INSERT INTO @TBLINCENTIVES(DriverName,DriverName1,MobileNo,MobileNo1,LicenseNo,LicenseNo1,
							VehicleName,VehicleType,LicensePlate,ScheduleDate,FormPlace,ToPlace,StartTime,EndTime,
							OdoStart,OdoEnd,TotalDistance,IncentiveName,IncentiveAmt)
						SELECT DM.DisplayName,DM1.DisplayName,DM.MobileNo,DM1.MobileNo,DM.LicenseNo,DM1.LicenseNo,
							V.VehicleDescription,V.Category,V.LicensePlate,CONVERT(VARCHAR,DA.AssignmentDate,106),
							L1.LandmarkName,L2.LandmarkName,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DA.FromTime))),
							CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DA.ToTime))),
							@ODOSTART,@ODOEND,@TOTALDISTANCE,DB.Description,DB.OtherAmt 
							FROM rvlfDriverAssignment DA
								LEFT OUTER JOIN rvlfDriverAssignment DA1 ON DA1.TripId=DA.AssignmentId 
								INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId
								INNER JOIN RVLFVEHICLEASSIGNMENT VA ON VA.BOXID=DA.BOXID
								LEFT OUTER JOIN rvlfDriverMaster DM1 ON DM1.DriverId=DA1.DriverId
								INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId  
								LEFT OUTER JOIN rvlfLandmark L1 ON L1.LandmarkID=DA.FromLandmarkId 
								LEFT OUTER JOIN rvlfLandmark L2 ON L2.LandmarkID =DA.ToLandmarkId
								INNER JOIN rvlfDriverBattaDetails DB ON DB.BattaId=@BIGINCENTIVEID 
							WHERE DA.ASSIGNMENTID=@bigTripId 							
					END	
				END
			IF(@IGNITION =0)
				BEGIN			
					DECLARE @bigOdoStart bigint=null
					DECLARE @bigOdoEnd bigint=null
					SELECT TOP 1 @bigOdoStart=(CASE WHEN customParam LIKE '%Odometer=%' THEN CAST( SUBSTRING (customParam,CHARINDEX('Odometer=',customParam,1)+9,CHARINDEX(';',customParam,
								CHARINDEX('Odometer=',customParam,1)) - (CHARINDEX('Odometer=',customParam,1)+9)) as bigint) END ) from @TBLMSGS 
						WHERE CONVERT(time,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DateandTime))) between @FROMTIME and @TOTIME
							AND customParam LIKE '%Odometer=%' order by DateandTime 													
					SELECT TOP 1 @bigOdoEnd=(CASE WHEN customParam LIKE '%Odometer=%' THEN CAST( SUBSTRING (customParam,CHARINDEX('Odometer=',customParam,1)+9,CHARINDEX(';',customParam,
								CHARINDEX('Odometer=',customParam,1)) - (CHARINDEX('Odometer=',customParam,1)+9)) as bigint) END ) from @TBLMSGS 
						WHERE CONVERT(time,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DateandTime))) between @FROMTIME and @TOTIME  
							AND customParam LIKE '%Odometer=%'order by DateandTime desc																							
					IF(@bigOdoStart IS NULL)
						SELECT TOP 1 @bigOdoStart=(CASE WHEN customParam LIKE '%Odometer=%' THEN CAST( SUBSTRING (customParam,CHARINDEX('Odometer=',customParam,1)+9,CHARINDEX(';',customParam,
								CHARINDEX('Odometer=',customParam,1)) - (CHARINDEX('Odometer=',customParam,1)+9)) as bigint) END ) from @TBLMSGS 
						WHERE CONVERT(time,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DateandTime))) < @FROMTIME 
							AND customParam LIKE '%Odometer=%' order by DateandTime DESC 																		
                    IF(@bigOdoEnd IS NULL)
						SELECT TOP 1 @bigOdoEnd=(CASE WHEN customParam LIKE '%Odometer=%' THEN CAST( SUBSTRING (customParam,CHARINDEX('Odometer=',customParam,1)+9,CHARINDEX(';',customParam,
								CHARINDEX('Odometer=',customParam,1)) - (CHARINDEX('Odometer=',customParam,1)+9)) as bigint) END ) from @TBLMSGS 
						WHERE CONVERT(time,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DateandTime))) > @TOTIME 
							AND customParam LIKE '%Odometer=%'order by DateandTime																															

					IF((@bigOdoStart=@bigOdoEnd)OR(@bigOdoStart IS NULL AND @bigOdoEnd IS NULL))
						BEGIN							
							INSERT INTO @TBLINCENTIVES(DriverName,DriverName1,MobileNo,MobileNo1,LicenseNo,LicenseNo1,VehicleName,VehicleType,LicensePlate,ScheduleDate,FormPlace,ToPlace,StartTime,EndTime,OdoStart,OdoEnd,TotalDistance,IncentiveName,IncentiveAmt)
							SELECT DM.DisplayName,DM1.DisplayName,DM.MobileNo,DM1.MobileNo,DM.LicenseNo,DM1.LicenseNo,V.VehicleDescription,
									V.Category,V.LicensePlate,CONVERT(VARCHAR,DA.AssignmentDate,106),L1.LandmarkName, 
									L2.LandmarkName,
									CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DA.FromTime))),
									CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DA.ToTime))),
									@ODOSTART,@ODOEND,@TOTALDISTANCE,DB.Description,DB.OtherAmt 
								FROM rvlfDriverAssignment DA
									LEFT OUTER JOIN rvlfDriverAssignment DA1 ON DA1.TripId=DA.AssignmentId 
									INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId
									LEFT OUTER JOIN rvlfDriverMaster DM1 ON DM1.DriverId=DA1.DriverId
									INNER JOIN RVLFVEHICLEASSIGNMENT VA ON VA.BOXID=DA.BOXID
									INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId  
									LEFT OUTER JOIN rvlfLandmark L1 ON L1.LandmarkID=DA.FromLandmarkId 
									LEFT OUTER JOIN rvlfLandmark L2 ON L2.LandmarkID =DA.ToLandmarkId
									INNER JOIN rvlfDriverBattaDetails DB ON DB.BattaId=@BIGINCENTIVEID 
								WHERE DA.ASSIGNMENTID=@bigTripId 																
						END 
				END				
				UPDATE @TBLALLOWANCES SET ProcessStatus=1 WHERE AllowanceId=@BIGINCENTIVEID 			
			END
			IF(@VCVEHICLETYPE='LMV')
				BEGIN
					DECLARE @VCVEHICLENAME VARCHAR(4)=NULL
					SELECT @VCVEHICLENAME=LEFT(VehicleDescription,4)  FROM rvlfVehicle WHERE VehicleId=@BIGVEHICLEID 
					IF(@VCVEHICLENAME='Team' OR @VCVEHICLENAME ='TEAM')
						BEGIN	
							INSERT INTO @TBLINCENTIVES(DriverName,DriverName1,MobileNo,MobileNo1,LicenseNo,
								LicenseNo1,VehicleName,VehicleType,LicensePlate,ScheduleDate,FormPlace,ToPlace,
								StartTime,EndTime,OdoStart,OdoEnd,TotalDistance,IncentiveName,IncentiveAmt)
							SELECT DM.DisplayName,DM1.DisplayName,DM.MobileNo,DM1.MobileNo,DM.LicenseNo,
								DM1.LicenseNo,V.VehicleDescription,V.Category,V.LicensePlate,
								CONVERT(VARCHAR,DA.AssignmentDate,106),L1.LandmarkName,L2.LandmarkName,
								CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DA.FromTime))),
								CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DA.ToTime))),
								@ODOSTART,@ODOEND,@TOTALDISTANCE,'Team Vehicle Allowance',120
									FROM rvlfDriverAssignment DA
										LEFT OUTER JOIN rvlfDriverAssignment DA1 ON DA1.TripId=DA.AssignmentId 
										INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId
										INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =DA.BOXID 
										LEFT OUTER JOIN rvlfDriverMaster DM1 ON DM1.DriverId=DA1.DriverId
										INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId  
										LEFT OUTER JOIN rvlfLandmark L1 ON L1.LandmarkID=DA.FromLandmarkId 
										LEFT OUTER JOIN rvlfLandmark L2 ON L2.LandmarkID =DA.ToLandmarkId										
									WHERE DA.ASSIGNMENTID=@bigTripId 
						END
					
				END
	END
END	
SELECT DriverName,ISNULL(DriverName1,'NA') as DriverName1 ,MobileNo,ISNULL(MobileNo1,'NA') AS MobileNo1,LicenseNo,
	ISNULL(LicenseNo1,'NA') AS LicenseNo1 ,VehicleName,VehicleType,LicensePlate,CONVERT(VARCHAR,ScheduleDate,106)AS ScheduleDate,
	FormPlace,ToPlace,StartTime,EndTime,OdoStart,OdoEnd,TotalDistance,IncentiveName,IncentiveAmt 
	 FROM @TBLINCENTIVES 	


	 
END




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverIncentives1]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetDriverIncentives1]
	@driverId bigint=null,
	@bigOrganizationId bigint=null,
	@intHoursToBeAdded INT = null,
	@intMinsToBeAdded INT = null,
	@dtFrom datetime=null,
	@dtTo datetime= null,
	@bitType bit=null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_GetDriverIncentives1]46,6,5,30,'2010-11-01 09:23:42.000','2010-11-09 12:47:20.000',NULL
--	Description	:	To get the driver incentive details
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	10-Nov-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN

DECLARE @TBLSCHEDULES TABLE
(
	ScheduleTime datetime,
	CustomProp varchar(600),
	BoxId BIGINT,
	StreetAddress varchar(500),
	Inc int
)
DECLARE @TBLINCENTIVES TABLE
		(
			DriverName varchar(30),
			DriverName1 varchar(30),
			MobileNo varchar(20),
			MobileNo1 varchar(20),
			LicenseNo varchar(50),
			LicenseNo1 varchar(50),
			VehicleName varchar(30),
			VehicleType varchar(5),
			LicensePlate varchar(50),
			ScheduleDate datetime,
			FormPlace varchar(500),
			ToPlace varchar(500),
			StartTime TIME(7),
			EndTime TIME(7),
			OdoStart bigint,
			OdoEnd bigint,
			TotalDistance int,
			IncentiveName varchar(200),
			IncentiveAmt numeric(10,2),
			ViAllowance numeric(5,2),
			ViDeduction numeric(5,2)	
		)
INSERT INTO @TBLSCHEDULES(SCHEDULETIME,CUSTOMPROP,BoxId,StreetAddress)
	SELECT OriginDateTime,CustomProp,BoxId,StreetAddress FROM rvlfmsginhst WHERE origindatetime BETWEEN @dtFrom AND @dtTo 
          AND BoxMsgInTypeId=76
          AND CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(substring(CustomProp,CHARINDEX('MAPID=',customprop,1)+6,len(CustomProp)) AS bigint) END=@driverid 
          AND CustomProp LIKE '%Driver Status%'
          ORDER BY OriginDateTime 

	
WHILE EXISTS(SELECT * FROM @TBLSCHEDULES WHERE Inc IS NULL)
BEGIN	
	DECLARE @DTFROMTIME DATETIME=NULL
	DECLARE @DTTOTIME DATETIME=NULL
	DECLARE @BIGVEHICLEID BIGINT=NULL
	DECLARE @VCVEHICLETYPE VARCHAR(5)=NULL
	DECLARE @ODOSTART BIGINT=NULL
	DECLARE @ODOEND BIGINT=NULL
	DECLARE @BIGDRIVERID BIGINT=NULL
	DECLARE @DTTRIPSTART DATETIME=NULL
	DECLARE @DTTRIPEND DATETIME=NULL
	DECLARE @TINOOFDRIVERS TINYINT=1 
	DECLARE @bigTripId BIGINT=NULL
    DECLARE @FROMADDRESS VARCHAR(500)=NULL
    DECLARE @TOADDRESS VARCHAR(500)=NULL
    
	SELECT TOP 1 @DTFROMTIME=ScheduleTime,@BIGDRIVERID=@driverId,@BIGVEHICLEID=V.VehicleId,@VCVEHICLETYPE=V.Category,
		@ODOSTART=(CASE WHEN CustomProp LIKE '%Driver Status=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Odometer=',CustomProp,1)+9,CHARINDEX(';',CustomProp,
								CHARINDEX('Odometer=',CustomProp,1)) - (CHARINDEX('Odometer=',CustomProp,1)+9)) as bigint) END ),
								@DTTRIPSTART=DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,ScheduleTime)),
			@FROMADDRESS=StreetAddress								 
		FROM @TBLSCHEDULES S
			INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=S.BoxId
			INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId 
		WHERE CASE WHEN CustomProp LIKE '%Driver Status=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,CHARINDEX(';',CustomProp,
								CHARINDEX('Driver Status=',CustomProp,1)) - (CHARINDEX('Driver Status=',CustomProp,1)+14)) as VARCHAR) END='IN'
			AND Inc IS NULL
	UPDATE TOP(1) @TBLSCHEDULES SET Inc=1 WHERE ScheduleTime=@DTFROMTIME AND Inc IS NULL	
	
	SELECT TOP 1 @DTTOTIME=ScheduleTime,
		@ODOEND=(CASE WHEN CustomProp LIKE '%Driver Status=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Odometer=',CustomProp,1)+9,CHARINDEX(';',CustomProp,
								CHARINDEX('Odometer=',CustomProp,1)) - (CHARINDEX('Odometer=',CustomProp,1)+9)) as bigint) END ),
			@DTTRIPEND=DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,ScheduleTime)),
			@TOADDRESS=StreetAddress				 	
		FROM @TBLSCHEDULES 
		WHERE CASE WHEN CustomProp LIKE '%Driver Status=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,CHARINDEX(';',CustomProp,
								CHARINDEX('Driver Status=',CustomProp,1)) - (CHARINDEX('Driver Status=',CustomProp,1)+14)) as VARCHAR) END='OUT'
			AND Inc IS NULL	
			
		UPDATE TOP(1) @TBLSCHEDULES SET Inc=1 WHERE ScheduleTime=@DTTOTIME AND Inc IS NULL	
		

--GET THE NO OF DRIVER IN THE TRIP
IF EXISTS(SELECT DriverId FROM rvlfDriverAssignment WHERE AssignmentId=@bigTripId AND TripId IS NOT NULL)
	BEGIN
		SET @TINOOFDRIVERS=2
	END 
ELSE
	BEGIN
		SET @TINOOFDRIVERS=1
	END


IF (@VCVEHICLETYPE IS NOT NULL)
BEGIN
DECLARE @TBLMSGS TABLE(
	MessageId uniqueidentifier,
	DateandTime datetime,
	customParam varchar(600),
	BoxtypeId int	
)

DELETE FROM @TBLMSGS 

--INSERT THE MESSAGE DETAILS TO TEMP TABLE
INSERT INTO @TBLMSGS (MessageId,DateandTime,customParam,BoxtypeId)
	SELECT MessageInID,OriginDateTime,CustomProp,BoxMsgInTypeId FROM rvlfMsgInHst WHERE OriginDateTime BETWEEN @DTFROMTIME AND @DTTOTIME AND BoxId =(SELECT BoxId FROM rvlfVehicleAssignment WHERE VehicleId=@BIGVEHICLEID)

--VIOLATION RELATED FUNCTIONALITY
DECLARE @TBLVIOLATIONS TABLE( RATING INT)
INSERT INTO @TBLVIOLATIONS(RATING)
SELECT V.Rating FROM @TBLMSGS T 
	INNER JOIN rvlfViolationRating V ON V.BoxMsgInTypeID=T.BoxtypeId 
 WHERE V.OrganizationID=@bigOrganizationId 	
DECLARE @TOTVIOLATIONPOINTS INT=0
SELECT @TOTVIOLATIONPOINTS=SUM(RATING) FROM @TBLVIOLATIONS GROUP BY RATING 
DECLARE @tinAllPercentage tinyint=0
DECLARE @tinDedPercentage tinyint=0
DECLARE @intAllViolations int=0
DECLARE @intDedViolations int=0
IF EXISTS(SELECT BattaId FROM rvlfDriverBattaDetails WHERE OrganizationId=@bigOrganizationId AND Active =1 AND VehicleType=@VCVEHICLETYPE 
				AND ViolationPoints IS NOT NULL AND PercentageOfAmt IS NOT NULL)
	BEGIN
		SELECT TOP 1 @tinAllPercentage=PercentageOfAmt,@intAllViolations=ViolationPoints FROM rvlfDriverBattaDetails WHERE OrganizationId=@bigOrganizationId AND Active =1 AND VehicleType=@VCVEHICLETYPE 
				AND ViolationPoints IS NOT NULL AND PercentageOfAmt IS NOT NULL AND IsAllowance=1 ORDER BY BattaId DESC
		SELECT TOP 1 @tinDedPercentage=PercentageOfAmt,@intDedViolations=ViolationPoints FROM rvlfDriverBattaDetails WHERE OrganizationId=@bigOrganizationId AND Active =1 AND VehicleType=@VCVEHICLETYPE 
				AND ViolationPoints IS NOT NULL AND PercentageOfAmt IS NOT NULL AND IsAllowance=0 ORDER BY BattaId DESC				
	END
					

--CALCULATE THE INCENTIVES
IF(@ODOSTART IS NOT NULL AND @ODOEND IS NOT NULL)
	BEGIN
		DECLARE @TOTALDISTANCE INT=NULL
		
		--CALCULATE THE TOTAL DISTANCE DRIVEN 
		SET @TOTALDISTANCE =@ODOEND-@ODOSTART 						
		
		--DECLARE INSENTIVE DETAILS TABLE
		
		
		DECLARE @TBLALLOWANCES TABLE
		(
			AllowanceId bigint,
			AllowanceName varchar(50),
			FromTime time(7),
			ToTime time(7),
			Amt numeric(7,2),
			Ignition bit,
			ProcessStatus bit			
		)
		
		DECLARE @BIGINCENTIVEID BIGINT=NULL		
		--GET THE INCENTIVE DETAILS FROM THE INCENTIVE TABLE
		SELECT @BIGINCENTIVEID=BattaId FROM rvlfDriverBattaDetails 
			WHERE OrganizationId=@bigOrganizationId AND Active =1 AND VehicleType=@VCVEHICLETYPE 
				AND @TOTALDISTANCE BETWEEN FromRange AND ToRange 
				AND OrganizationId=@bigOrganizationId 
				AND NoOfDrivers=@TINOOFDRIVERS 
		IF (@BIGINCENTIVEID IS NULL)
			SELECT @BIGINCENTIVEID=BattaId FROM rvlfDriverBattaDetails 
				WHERE OrganizationId=@bigOrganizationId AND Active =1 AND VehicleType=@VCVEHICLETYPE 
					AND @TOTALDISTANCE BETWEEN FromRange AND ToRange 
					AND OrganizationId=@bigOrganizationId 
					AND NoOfDrivers=0	
		--GET THE ALLOWANCE DETAILS FROM THE INCENTIVE TABLE

		INSERT INTO @TBLALLOWANCES(AllowanceId,AllowanceName,FromTime,ToTime,Amt,Ignition,ProcessStatus)
		SELECT BattaId,Description,FromTime,ToTime,OtherAmt,IgnitionStatus,0  FROM rvlfDriverBattaDetails 
			WHERE OrganizationId=@bigOrganizationId AND Active =1 AND VehicleType=@VCVEHICLETYPE 
				AND FromTime IS NOT NULL AND ToTime IS NOT NULL
				AND (NoOfDrivers=@TINOOFDRIVERS OR NoOfDrivers=0)
		
		IF(@BIGINCENTIVEID IS NOT NULL)
			BEGIN
				--CALCULATE THE INCENTIVE BASED ON THE DISTANCE
				INSERT INTO @TBLINCENTIVES(DriverName,DriverName1,MobileNo,MobileNo1,LicenseNo,LicenseNo1,
					VehicleName,VehicleType,LicensePlate,ScheduleDate,FormPlace,ToPlace,StartTime,EndTime,OdoStart,
					OdoEnd,TotalDistance,IncentiveName,IncentiveAmt,ViAllowance,ViDeduction)
				SELECT DM.DisplayName,null as DisplayName,DM.MobileNo,null as MobileNo,DM.LicenseNo,null as LicenseNo,
					V.VehicleDescription,V.Category,V.LicensePlate,CONVERT(VARCHAR,@DTTRIPSTART,106),
					@FROMADDRESS,@TOADDRESS,CONVERT(TIME,@DTTRIPSTART),
					CONVERT(TIME,@DTTRIPEND),
					@ODOSTART,@ODOEND,@TOTALDISTANCE,DB.Description + '(Kilometer From-'+CAST(DB.FromRange AS VARCHAR)+' To-'+CAST(DB.ToRange AS VARCHAR) +')' 
					,(@TOTALDISTANCE * DB.RatePerKM)+ISNULL(DB.OtherAmt,0),  
					CASE WHEN @tinAllPercentage!=0 THEN CASE WHEN @TOTVIOLATIONPOINTS<=@intAllViolations THEN (@TOTALDISTANCE * DB.RatePerKM)+ISNULL(DB.OtherAmt,0)*(@tinAllPercentage/100) ELSE 0 END ELSE 0 END,
					CASE WHEN @tinDedPercentage!=0 THEN CASE WHEN @TOTVIOLATIONPOINTS>=@intDedViolations THEN (@TOTALDISTANCE * DB.RatePerKM)+ISNULL(DB.OtherAmt,0)*(@tinDedPercentage/100) ELSE 0 END ELSE 0 END
					 
					FROM rvlfDriverMaster DM 					
						INNER JOIN rvlfVehicle V ON V.VehicleId=@BIGVEHICLEID						
						INNER JOIN rvlfDriverBattaDetails DB ON DB.BattaId=@BIGINCENTIVEID 
					WHERE DM.DriverId=@driverid
			END	
			
		--CALCULATE THE ALLOWANCES BASED ON THE IGNITION ON SETUP
		WHILE EXISTS(SELECT AllowanceId FROM @TBLALLOWANCES WHERE ProcessStatus=0)
			BEGIN
				SET @BIGINCENTIVEID=NULL
				DECLARE @FROMTIME TIME=NULL
				DECLARE @TOTIME TIME=NULL				
				DECLARE @IGNITION BIT=NULL
				SELECT TOP 1 @BIGINCENTIVEID=AllowanceId,@FROMTIME=FromTime,@TOTIME=ToTime,@IGNITION=Ignition FROM @TBLALLOWANCES where ProcessStatus=0
		
			IF(@IGNITION =1)
				BEGIN	
				--RESTRICT THE ALLOWANCES OUT OF IGNITION ON TIME			
				IF((CONVERT(TIME,@DTTRIPSTART)<=@FROMTIME AND CONVERT(TIME,@DTTRIPEND)>=@TOTIME)
					AND (SELECT COUNT(BoxtypeId) FROM @TBLMSGS WHERE BoxtypeId=3 AND CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DateandTime)))<@FROMTIME)=0)
					BEGIN
						INSERT INTO @TBLINCENTIVES(DriverName,DriverName1,MobileNo,MobileNo1,LicenseNo,LicenseNo1,
							VehicleName,VehicleType,LicensePlate,ScheduleDate,FormPlace,ToPlace,StartTime,EndTime,
							OdoStart,OdoEnd,TotalDistance,IncentiveName,IncentiveAmt,ViAllowance,ViDeduction)
						SELECT DM.DisplayName,null as DisplayName,DM.MobileNo,null as MobileNo,DM.LicenseNo,null as LicenseNo,
							V.VehicleDescription,V.Category,V.LicensePlate,CONVERT(VARCHAR,@DTTRIPSTART,106),
							@FROMADDRESS,@TOADDRESS,CONVERT(TIME,@DTTRIPSTART),
							CONVERT(TIME,@DTTRIPEND),
							@ODOSTART,@ODOEND,@TOTALDISTANCE,DB.Description + '(Time From-'+CAST(DB.FromTime AS VARCHAR(5))+' To-'+CAST(DB.ToTime AS VARCHAR(5)) +')',DB.OtherAmt,
							CASE WHEN @tinAllPercentage!=0 THEN CASE WHEN @TOTVIOLATIONPOINTS<=@intAllViolations THEN ISNULL(DB.OtherAmt,0)*(@tinAllPercentage/100) ELSE 0 END ELSE 0 END,
							CASE WHEN @tinDedPercentage!=0 THEN CASE WHEN @TOTVIOLATIONPOINTS>=@intDedViolations THEN ISNULL(DB.OtherAmt,0)*(@tinDedPercentage/100) ELSE 0 END ELSE 0 END
					  
							FROM rvlfDriverMaster DM 								
								INNER JOIN rvlfVehicle V ON V.VehicleId=@BIGVEHICLEID						
								INNER JOIN rvlfDriverBattaDetails DB ON DB.BattaId=@BIGINCENTIVEID 
							WHERE DM.DriverId=@driverid													
					END	
				END
			IF(@IGNITION =0)
				BEGIN												
					DECLARE @bigOdoStart bigint=null
					DECLARE @bigOdoEnd bigint=null
					SELECT TOP 1 @bigOdoStart=(CASE WHEN customParam LIKE '%Odometer=%' THEN CAST( SUBSTRING (customParam,CHARINDEX('Odometer=',customParam,1)+9,CHARINDEX(';',customParam,
								CHARINDEX('Odometer=',customParam,1)) - (CHARINDEX('Odometer=',customParam,1)+9)) as bigint) END ) from @TBLMSGS 
						WHERE CONVERT(time,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DateandTime))) between @FROMTIME and @TOTIME 
							AND customParam LIKE '%Odometer=%' order by DateandTime 													
					SELECT TOP 1 @bigOdoEnd=(CASE WHEN customParam LIKE '%Odometer=%' THEN CAST( SUBSTRING (customParam,CHARINDEX('Odometer=',customParam,1)+9,CHARINDEX(';',customParam,
								CHARINDEX('Odometer=',customParam,1)) - (CHARINDEX('Odometer=',customParam,1)+9)) as bigint) END ) from @TBLMSGS 
						WHERE CONVERT(time,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DateandTime))) between @FROMTIME and @TOTIME 
							AND customParam LIKE '%Odometer=%' order by DateandTime desc																							
					IF(@bigOdoStart IS NULL)
						SELECT TOP 1 @bigOdoStart=(CASE WHEN customParam LIKE '%Odometer=%' THEN CAST( SUBSTRING (customParam,CHARINDEX('Odometer=',customParam,1)+9,CHARINDEX(';',customParam,
								CHARINDEX('Odometer=',customParam,1)) - (CHARINDEX('Odometer=',customParam,1)+9)) as bigint) END ) from @TBLMSGS 
						WHERE CONVERT(time,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DateandTime))) < @FROMTIME
							AND customParam LIKE '%Odometer=%' order by DateandTime DESC 																		
                    IF(@bigOdoEnd IS NULL)
						SELECT TOP 1 @bigOdoEnd=(CASE WHEN customParam LIKE '%Odometer=%' THEN CAST( SUBSTRING (customParam,CHARINDEX('Odometer=',customParam,1)+9,CHARINDEX(';',customParam,
								CHARINDEX('Odometer=',customParam,1)) - (CHARINDEX('Odometer=',customParam,1)+9)) as bigint) END ) from @TBLMSGS 
						WHERE CONVERT(time,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,DateandTime))) > @TOTIME 
							AND customParam LIKE '%Odometer=%' order by DateandTime																															
					IF((@bigOdoStart=@bigOdoEnd)OR(@bigOdoStart IS NULL AND @bigOdoEnd IS NULL))
						BEGIN	
							INSERT INTO @TBLINCENTIVES(DriverName,DriverName1,MobileNo,MobileNo1,LicenseNo,
								LicenseNo1,VehicleName,VehicleType,LicensePlate,ScheduleDate,FormPlace,ToPlace,
								StartTime,EndTime,OdoStart,OdoEnd,TotalDistance,IncentiveName,IncentiveAmt,ViAllowance,ViDeduction)
							SELECT DM.DisplayName,null as DisplayName,DM.MobileNo,null as MobileNo,DM.LicenseNo,null as LicenseNo,
								V.VehicleDescription,V.Category,V.LicensePlate,CONVERT(VARCHAR,@DTTRIPSTART,106),
								@FROMADDRESS,@TOADDRESS,CONVERT(TIME,@DTTRIPSTART),
								CONVERT(TIME,@DTTRIPEND),
								@ODOSTART,@ODOEND,@TOTALDISTANCE,DB.Description + '(Time From-'+CAST(DB.FromTime AS VARCHAR(5))+' To-'+CAST(DB.ToTime AS VARCHAR(5)) +')',DB.OtherAmt,
							CASE WHEN @tinAllPercentage!=0 THEN CASE WHEN @TOTVIOLATIONPOINTS<=@intAllViolations THEN ISNULL(DB.OtherAmt,0)*(@tinAllPercentage/100) ELSE 0 END ELSE 0 END,
							CASE WHEN @tinDedPercentage!=0 THEN CASE WHEN @TOTVIOLATIONPOINTS>=@intDedViolations THEN ISNULL(DB.OtherAmt,0)*(@tinDedPercentage/100) ELSE 0 END ELSE 0 END 
							FROM rvlfDriverMaster DM 								
								INNER JOIN rvlfVehicle V ON V.VehicleId=@BIGVEHICLEID						
								INNER JOIN rvlfDriverBattaDetails DB ON DB.BattaId=@BIGINCENTIVEID 
							WHERE DM.DriverId=@driverid								
						END 
				END				
				UPDATE @TBLALLOWANCES SET ProcessStatus=1 WHERE AllowanceId=@BIGINCENTIVEID 	
						
			END
			IF(@VCVEHICLETYPE='LMV')
				BEGIN
					DECLARE @VCVEHICLENAME VARCHAR(4)=NULL
					SELECT @VCVEHICLENAME=LEFT(VehicleDescription,4)  FROM rvlfVehicle WHERE VehicleId=@BIGVEHICLEID 
					IF(@VCVEHICLENAME='Team' OR @VCVEHICLENAME ='TEAM')
						BEGIN	
							INSERT INTO @TBLINCENTIVES(DriverName,DriverName1,MobileNo,MobileNo1,LicenseNo,
								LicenseNo1,VehicleName,VehicleType,LicensePlate,ScheduleDate,FormPlace,ToPlace,
								StartTime,EndTime,OdoStart,OdoEnd,TotalDistance,IncentiveName,IncentiveAmt,ViAllowance,ViDeduction)
							SELECT DM.DisplayName,null as DisplayName,DM.MobileNo,null as MobileNo,DM.LicenseNo,null as LicenseNo,
							V.VehicleDescription,V.Category,V.LicensePlate,CONVERT(VARCHAR,@DTTRIPSTART,106),
							@FROMADDRESS,@TOADDRESS,CONVERT(TIME,@DTTRIPSTART),
							CONVERT(TIME,@DTTRIPEND),
							@ODOSTART,@ODOEND,@TOTALDISTANCE,DB.Description + '(Team Vehicle)',DB.OtherAmt,
							CASE WHEN @tinAllPercentage!=0 THEN CASE WHEN @TOTVIOLATIONPOINTS<=@intAllViolations THEN ISNULL(DB.OtherAmt,0)*(@tinAllPercentage/100) ELSE 0 END ELSE 0 END,
							CASE WHEN @tinDedPercentage!=0 THEN CASE WHEN @TOTVIOLATIONPOINTS>=@intDedViolations THEN ISNULL(DB.OtherAmt,0)*(@tinDedPercentage/100) ELSE 0 END ELSE 0 END 
							FROM rvlfDriverMaster DM 								
								INNER JOIN rvlfVehicle V ON V.VehicleId=@BIGVEHICLEID						
								INNER JOIN rvlfDriverBattaDetails DB ON DB.BattaId=@BIGINCENTIVEID 
							WHERE DM.DriverId=@driverid	
						END
					
				END
	END
END	
END
	
SELECT DriverName,ISNULL(DriverName1,'NA') as DriverName1 ,MobileNo,ISNULL(MobileNo1,'NA') AS MobileNo1,LicenseNo,
	ISNULL(LicenseNo1,'NA') AS LicenseNo1 ,VehicleName,VehicleType,LicensePlate,CONVERT(VARCHAR,ScheduleDate,106)AS ScheduleDate,
	FormPlace,ToPlace,StartTime,EndTime,OdoStart,OdoEnd,TotalDistance,IncentiveName,IncentiveAmt,
	DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,@dtFrom)) as FromDate,
	DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,@dtTo)) as ToDate,ViAllowance,
	ViDeduction as ViDeductions,(IncentiveAmt+ViAllowance)-ViDeduction as NetAmount
	 FROM @TBLINCENTIVES 	

SELECT SUM(IncentiveAmt)AS TOTAMT FROM @TBLINCENTIVES GROUP BY DriverName 

END
	 




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetDriverInfo]        
 @bigDriverId bigint = Null,         
 @bigOrganizationID bigint = null,      
 @bigQueryingUser bigint = 0         
AS        
/******************************************************************************/        
-- Name  : [rvlf_sp_GetDriverInfo] '312','6',303
-- Description : To get the driver details        
-- Author  : V.Narayanasamy        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--          : 10-Jun-2010 VN Created Intial Version         
--          : 08-Aug-2011 Ranjith Date Format included      
--          : 16-Mar-2012 Ranjith DateofJoin column added for checking       
--			: 01-Oct-2014 Add no of previous instances of driver   
--			: 22-Dec-2015 Added License Type and License Issued columns - Anbarasu.e   
/******************************************************************************/        
BEGIN        
	DECLARE @DefaultDateFormat INT = 0;        
	DECLARE @ConversionFactor numeric (10,2) = 1.0        
	DECLARE @HoursToBeAdded INT = 0          
	DECLARE @MinsToBeAdded INT = 0       
	declare @Lang varchar(50)         
	SELECT @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser            
        
	SELECT  @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,
			@ConversionFactor = CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 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 = @bigQueryingUser        
        
	UPDATE rvlfDriverMaster SET Active=0 WHERE LicenseExpiresOn < CONVERT(DATE,GETDATE())         
	
	SELECT	DM.DriverId,(case when @Lang='LanguageArNew' then   
			case WHEN dm.DisplayNameAr = '' THEN DriverName ELSE   isnull(dm.DisplayNameAr,dm.DriverName) END end) as DriverName,  
			Gender,CONVERT(varchar,DateOfBirth,@DefaultDateFormat)as DateOfBirth,PermanentAddress,MailingAddress,PhoneNo,MobileNo,  
			-- (case when @Lang='LanguageArNew'THEN  case WHEN dm.DisplayNameAr = '' THEN DisplayName ELSE isnull(DisplayNameAr,DisplayName) END end)as DisplayName,        
			LTRIM(REPLACE(REPLACE((case when @Lang='LanguageArNew' then isnull(DisplayNameAr,DisplayName) else DisplayName end),'?',''),'.','')) as DisplayName,      
			Insurance,LicenseNo,LicenseType,      
			CONVERT(varchar,LicenseIssuedOn,@DefaultDateFormat)as LicenseIssuedOn,          
			CONVERT(varchar,LicenseExpiresOn,@DefaultDateFormat)as LicenseExpiresOn,          
			CONVERT(varchar,LicenseExpiresOn,103) as LicenseExpiresOnSort,      
			TotalYearsOfExperience,NoOfAccidents,DateOfJoin,Photo,NoOfHoursDrived,Active,DM.IsDelete,S.ShiftID,        
			DGA.DriverGroupId,M.IButtonId,M.IButtonKeyName,        
			ISNULL(dbo.rvlf_fn_GetNotificationsList(11, DM.DriverId, 1,1,0),'') as EmailList,         
			ISNULL(dbo.rvlf_fn_GetNotificationsList(11, DM.DriverId, 0,1,0),'') as SMSList,        
			REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(11, DM.DriverId, 1,0,1),''),',',', ') as EmailUserNameList,        
			REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(11, DM.DriverId, 0,0,1),''),',',', ') as SMSUserNameList,      
			dm.DisplayNameAr,DriverName  as DriverNameEdit,DisplayName as DisplayNameEdit,
			(case when DateOfJoin <=dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) or DateOfJoin is null then  0 else 1 end) DOJChecking,  
			(SELECT COUNT(DriverId) FROM dbo.rvlfAccidentDetails ad WHERE ad.DriverId = DM.DriverId AND ad.IsDelete=0) AS AccidentInstances, DM.OrganizationID,
			Convert(varchar,InsuranceExpiresOn,@DefaultDateFormat)as InsuranceExpiresOn,Convert(varchar,InsuranceRenewedOn,@DefaultDateFormat)as InsuranceRenewedOn  
	FROM	rvlfDriverMaster DM        
	LEFT OUTER JOIN rvlfOrgShifts S ON S.ShiftID=DM.ShiftId        
	LEFT OUTER JOIN rvlfDriverGroupAssignment DGA ON DGA.DriverId=DM.DriverId          
	LEFT OUTER JOIN rvlfIButtonMapping M ON M.DriverId=DM.DriverId          
	WHERE	(@bigDriverId IS NULL OR @bigDriverId ='' OR DM.DriverId=@bigDriverId)         
	AND		(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR DM.OrganizationID=@bigOrganizationID) AND(ISDELETE=0)         
           
	SELECT * FROM rvlfDRIVERGROUPMASTER         
	WHERE (@bigOrganizationId IS NULL OR @bigOrganizationId='' OR OrganizationID=@bigOrganizationId)        
	--AND(@bigDriverGroupId IS NULL OR DRIVERGROUPID=@bigDriverGroupId)        
END      
 -- select * from rvlfDriverMaster where DriverId =15

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverorVehicleSchedules]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetDriverorVehicleSchedules]  
 @bigDriverId bigint = Null,   
 @bigVehicleId bigint = Null,   
 @bigOrganizationID bigint = null,  
 @dtFromDate datetime=null,   
 @dtTodate datetime=null,  
 @bitMode bit=null,  
 @bigUserId bigint=null,  
 @intHoursToBeAdded INT = 0,  
 @intMinsToBeAdded INT = 0
 
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_GetDriverorVehicleSchedules]null,NULL,6,'2011-07-12','2011-07-12',1,63,5,30  
-- Description : To get the driver/vehicle schedule details  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 15-Jun-2010 VN Created Intial Version   
--             : 09-Aug-2011 Ranjith Date Format Included
/******************************************************************************/  
BEGIN  
  
 DECLARE @VcDayName VARCHAR(15)=NULL         
 DECLARE @DefaultDateFormat INT = 0
 
  SELECT @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 = @bigUserId  
         
 IF(@bitMode =1)  
  BEGIN       
   SELECT DA.DriverId,CASE WHEN DM.Active=0 THEN DM.DisplayName + ' - (Inactive)' ELSE DM.DisplayName END AS DisplayName ,DM.MailingAddress,DM.MobileNo   
    FROM rvlfDriverAssignment DA   
     INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId   
    WHERE (@bigDriverId IS NULL OR @bigDriverId='' OR DA.DriverId=@bigDriverId)  
     AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR DM.OrganizationID=@bigOrganizationID)  
     AND (@dtFromDate IS NULL OR @dtTodate IS NULL OR AssignmentDate BETWEEN @dtFromDate AND @dtTodate)  
    GROUP BY DA.DriverId,DM.DisplayName,DM.MailingAddress,DM.MobileNo,DM.Active   
    ORDER BY DA.DriverId     
    
   SELECT DA.AssignmentId,DA.DriverId,VA.VehicleId,V.VehicleDescription AS DisplayName,CONVERT(varchar,DA.AssignmentDate,@DefaultDateFormat)as AssignmentDate,  
     ISNULL(CONVERT(varchar(5),DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,DA.FromTime)),108)+' - '+ CONVERT(VARCHAR(5),DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,DA.ToTime)),108),'-')AS ScheduledTime,  
     ISNULL(CONVERT(varchar(5),DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,DA.PunchIn)),108)+' - '+ CONVERT(VARCHAR(5),DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,DA.PunchOut)),108),'-')AS ActualDrivenTime,  
     CASE WHEN (NOT EXISTS(SELECT BoxId FROM rvlfMsgInHst WHERE BoxId=DA.BoxId AND OriginDateTime BETWEEN DA.FromTime AND DA.ToTime  
       AND BoxMsgInTypeId IN(1,2,3,4,5,6,9,11,14,15,16,17,24,51,76,96))   
      OR NOT EXISTS(SELECT BoxId FROM rvlfMsgInHst WHERE BoxId=DA.BoxId AND OriginDateTime BETWEEN DA.PunchIn AND DA.PunchOut  
       AND BoxMsgInTypeId IN(1,2,3,4,5,6,9,11,14,15,16,17,24,51,76,96))) AND GETUTCDATE() > CASE WHEN DA.ToTime IS NULL THEN DA.PunchOut ELSE DA.ToTime END   
      THEN 'Not Driven'  
       WHEN DA.AssignmentDate>CONVERT(DATE,GETDATE()) THEN 'Scheduled'         
       WHEN DA.AssignmentDate<CONVERT(DATE,GETDATE()) THEN 'Completed'  
       WHEN (GETUTCDATE()>=CASE WHEN DA.FromTime IS NULL THEN DA.PunchIn ELSE DA.FromTime END   
       AND GETUTCDATE()<=CASE WHEN DA.ToTime IS NULL THEN DA.PunchOut ELSE DA.ToTime END)       
       AND DA.AssignmentDate= CONVERT(DATE,GETDATE()) THEN  
        CASE WHEN EXISTS(SELECT * FROM rvlfMsgInHst WHERE BoxId=DA.BoxId AND OriginDateTime>=CASE WHEN DA.FromTime IS NULL THEN DA.PunchIn ELSE DA.FromTime END   
       AND OriginDateTime<=GETUTCDATE() AND BoxMsgInTypeId IN(1,2,3,4,5,6,9,11,14,15,16,17,24,51,76,96)) THEN 'Ongoing' ELSE  'Not Started' END  
       WHEN DA.AssignmentDate= CONVERT(DATE,GETDATE())  
       AND CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CASE WHEN DA.ToTime IS NULL THEN DA.PunchOut ELSE DA.ToTime END)))<CONVERT(TIME,GETDATE()) THEN 'Completed'  
       WHEN DM.Active=0 AND DA.AssignmentDate =CONVERT(DATE,DM.MODIFIEDDATE) AND CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CASE WHEN DA.FromTime IS NULL THEN DA.PunchIn ELSE DA.FromTime END)))>
       CONVERT(TIME,DM.MODIFIEDDATE) THEN 'Scheduled'  
       WHEN DM.Active=0 AND DA.AssignmentDate>CONVERT(DATE,DM.MODIFIEDDATE) THEN 'Scheduled'   
      ELSE 'Scheduled'  
       END AS VehStatus, ISNULL(DM1.DisplayName,'-') AS SecondDriver      
    FROM rvlfDriverAssignment DA  
     INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =DA.BOXID   
     INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId   
     INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId   
    -- LEFT OUTER JOIN rvlfDriverAssignment DA1 ON DA1.AssignmentId =CASE WHEN DA.TripId IS NOT NULL THEN (DA.TripId+1) ELSE NULL END  
     LEFT OUTER JOIN rvlfDriverAssignment DA1 ON DA1.AssignmentId =CASE WHEN DA.TripId IS NOT NULL THEN (SELECT AssignmentId FROM rvlfDriverAssignment WHERE TripId=DA.TripId AND AssignmentId !=DA.AssignmentId)  ELSE NULL END  
     LEFT OUTER JOIN rvlfDriverMaster DM1 ON DM1.DriverId=DA1.DriverId   
    WHERE (@bigDriverId IS NULL OR @bigDriverId='' OR DA.DriverId=@bigDriverId)  
     AND (@dtFromDate IS NULL OR @dtTodate IS NULL OR DA.AssignmentDate BETWEEN @dtFromDate AND @dtTodate)  
    ORDER BY DA.AssignmentDate,DA.FromTime    
  END  
 ELSE  
  BEGIN    
   SELECT VA.VehicleId,V.VehicleDescription AS DisplayName,V.LicensePlate,M.MakeName,MO.ModelName      
    FROM rvlfDriverAssignment DA   
     INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =DA.BOXID   
     INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId    
     LEFT OUTER JOIN rvlfMake M ON M.MakeId=V.MakeId   
     LEFT OUTER JOIN rvlfModel MO ON MO.ModelId=V.ModelId   
    WHERE (@bigVehicleId IS NULL OR @bigVehicleId='' OR VA.VehicleId=@bigVehicleId)  
     AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationID=@bigOrganizationID)  
     AND (@dtFromDate IS NULL OR @dtTodate IS NULL OR AssignmentDate BETWEEN @dtFromDate AND @dtTodate)  
    GROUP BY VA.VehicleId,V.VehicleDescription,V.LicensePlate,M.MakeName,MO.ModelName       
    ORDER BY VA.VehicleId   
      
   SELECT DA.AssignmentId,VA.VehicleId,DA.DriverId,CASE WHEN DM.Active=0 THEN DM.DisplayName + ' - (Inactive)' ELSE DM.DisplayName END AS DisplayName,CONVERT(varchar,DA.AssignmentDate,@DefaultDateFormat)as AssignmentDate,  
     ISNULL(CONVERT(varchar(5),DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,DA.FromTime)),108)+' - '+ CONVERT(VARCHAR(5),DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,DA.ToTime)),108),'-')AS ScheduledTime,  
     ISNULL(CONVERT(varchar(5),DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,DA.PunchIn)),108)+' - '+ CONVERT(VARCHAR(5),DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,DA.PunchOut)),108),'-')AS ActualDrivenTime,  
     CASE WHEN (NOT EXISTS(SELECT BoxId FROM rvlfMsgInHst WHERE BoxId=DA.BoxId AND OriginDateTime BETWEEN DA.FromTime AND DA.ToTime   
       AND BoxMsgInTypeId IN(1,2,3,4,5,6,9,11,14,15,16,17,24,51,76,96))   
      OR NOT EXISTS(SELECT BoxId FROM rvlfMsgInHst WHERE BoxId=DA.BoxId AND OriginDateTime BETWEEN DA.PunchIn AND DA.PunchOut  
       AND BoxMsgInTypeId IN(1,2,3,4,5,6,9,11,14,15,16,17,24,51,76,96))) AND GETUTCDATE() > CASE WHEN DA.ToTime IS NULL THEN DA.PunchOut ELSE DA.ToTime END   
      THEN 'Not Driven'  
      WHEN DA.AssignmentDate>CONVERT(DATE,GETDATE()) THEN 'Scheduled'  
       WHEN DA.AssignmentDate<CONVERT(DATE,GETDATE()) THEN 'Completed'        
       WHEN (GETUTCDATE()>=CASE WHEN DA.FromTime IS NULL THEN DA.PunchIn ELSE DA.FromTime END    
       AND GETUTCDATE()<=CASE WHEN DA.ToTime IS NULL THEN DA.PunchOut ELSE DA.ToTime END)           
       AND DA.AssignmentDate= CONVERT(DATE,GETDATE()) THEN   
        CASE WHEN EXISTS(SELECT * FROM rvlfMsgInHst WHERE BoxId=DA.BoxId AND OriginDateTime>=CASE WHEN DA.FromTime IS NULL THEN DA.PunchIn ELSE DA.FromTime END   
       AND OriginDateTime<=GETUTCDATE() AND BoxMsgInTypeId IN(1,2,3,4,5,6,9,11,14,15,16,17,24,51,76,96)) THEN 'Ongoing' ELSE  'Not Started' END  
       WHEN DA.AssignmentDate= CONVERT(DATE,GETDATE())  
       AND CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CASE WHEN DA.ToTime IS NULL THEN DA.PunchOut ELSE DA.ToTime END))) <CONVERT(TIME,GETDATE()) THEN 'Completed'  
       WHEN DM.Active=0 AND DA.AssignmentDate  =CONVERT(DATE,DM.MODIFIEDDATE) AND CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CASE WHEN DA.FromTime IS NULL THEN DA.PunchIn ELSE DA.FromTime END)))>CONVERT(TIME,DM.MODIFIEDDATE) THEN 'Scheduled'  
       WHEN DM.Active=0 AND DA.AssignmentDate>CONVERT(DATE,DM.MODIFIEDDATE) THEN 'Scheduled'          
      ELSE 'Scheduled'  
      END AS VehStatus,ISNULL(DM1.DisplayName,'-')  AS SecondDriver     
    FROM rvlfDriverAssignment DA  
     INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =DA.BOXID   
     INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId    
     --LEFT OUTER JOIN rvlfDriverAssignment DA1 ON DA1.AssignmentId =CASE WHEN DA.TripId IS NOT NULL THEN (DA.TripId+1) ELSE NULL END  
     LEFT OUTER JOIN rvlfDriverAssignment DA1 ON DA1.AssignmentId =CASE WHEN DA.TripId IS NOT NULL THEN (SELECT AssignmentId FROM rvlfDriverAssignment WHERE TripId=DA.TripId AND AssignmentId !=DA.AssignmentId)  ELSE NULL END  
     LEFT OUTER JOIN rvlfDriverMaster DM1 ON DM1.DriverId=DA1.DriverId   
    WHERE (@bigVehicleId IS NULL OR @bigVehicleId ='' OR VA.VehicleId =@bigVehicleId)  
     AND (@dtFromDate IS NULL OR @dtTodate IS NULL OR DA.AssignmentDate BETWEEN @dtFromDate AND @dtTodate)  
    ORDER BY DA.AssignmentDate,DA.FromTime   
  END  
   
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverPunchDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetDriverPunchDetails]
	@dtStartDate datetime = null,    
	@dtEndDate datetime =null,     
	@bigOrganizationID bigint = null,    
	@bigDriverID bigint = NULL,
	@vcDrivers varchar(100) = null,
	@bigQueryingUser bigint = null    
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_GetDriverPunchDetails] '2011-01-17 08:00:00 AM','2011-01-19  08:00:00 PM',6,null,null,62
--	Description	:	To get the driver punch details
--	Author		:	V. Narayanasamy.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>>  Initial Reason
--				:	15-Feb-2011	VN	Created Intial Version 
/******************************************************************************/
BEGIN    
    
SET NOCOUNT ON      
  
 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 = @bigQueryingUser    
     
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))    
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))    
     
 DECLARE @tblDriverPunchDetails TABLE(    
	  TripId int identity(1,1),
	  DriverId bigint,
	  VehicleName varchar(50),
	  PunchIn  datetime,
	  PunchInAddress varchar(200),	  
	  PunchOut datetime,
	  PunchOutAddress varchar(200),
	  Boxid int,
	  OdoStart bigint,
	  MaxSpeed int,
	  Distance int  
 )  
 IF EXISTS(SELECT MessageInID FROM rvlfMsgInHst M
				INNER JOIN rvlfDriverMaster DM ON DM.DriverId =CASE WHEN CustomProp LIKE '%MAPID=%' 
					THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))ELSE 0  END
				INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =M.BoxId 
				INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId 	
				WHERE (V.OrganizationId = @bigOrganizationID)
					AND(DM.OrganizationID =@bigOrganizationID) 
					AND OriginDateTime BETWEEN @dtStartDate and @dtEndDate
					AND (M.BoxId IN(SELECT BoxId FROM rvlfBoxId WHERE OrganizationId=@bigOrganizationID))
					AND BoxMsgInTypeId=76
					AND	(@bigDriverID IS NULL OR DM.DriverId = @bigDriverID)	
					AND (@vcDrivers IS NULL OR DM.DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDrivers,',')))
					AND (CASE WHEN CustomProp LIKE '%Driver Status=%' 
						THEN SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,
						(CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,1))-(CHARINDEX('Driver Status=',CustomProp,1)+14))) ELSE 'NI' END)='IN')
		BEGIN
			INSERT INTO @tblDriverPunchDetails 
				(DriverID, VehicleName, PunchIn, PunchInAddress,OdoStart,Boxid)
			SELECT DriverId,V.VehicleDescription,M.OriginDateTime,M.StreetAddress,CASE WHEN CustomProp LIKE '%Odometer=%' 
				THEN CAST(SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,1)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) AS BIGINT) ELSE 0 END,
				M.BoxId 
			FROM rvlfMsgInHst M
				INNER JOIN rvlfDriverMaster DM ON DM.DriverId =CASE WHEN CustomProp LIKE '%MAPID=%' 
					THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))ELSE 0  END
				INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =M.BoxId 
				INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId 	
				WHERE (V.OrganizationId = @bigOrganizationID)
					AND(DM.OrganizationID =@bigOrganizationID) 
					AND OriginDateTime BETWEEN @dtStartDate and @dtEndDate
					AND (M.BoxId IN(SELECT BoxId FROM rvlfBoxId WHERE OrganizationId=@bigOrganizationID))
					AND BoxMsgInTypeId=76
					AND	(@bigDriverID IS NULL OR CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) AS BIGINT) ELSE 0 END = @bigDriverID)	
					AND (@vcDrivers IS NULL OR CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) AS BIGINT) ELSE 0 END IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDrivers,',')))	 
					AND (CASE WHEN CustomProp LIKE '%Driver Status=%' 
						THEN SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,
						(CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,1))-(CHARINDEX('Driver Status=',CustomProp,1)+14))) ELSE 'NI' END)='IN'

			DECLARE @bigTripLoop bigint=null
			SELECT @bigTripLoop=MIN(TripId) FROM @tblDriverPunchDetails 						
			WHILE @bigTripLoop IS NOT NULL
				BEGIN
					DECLARE @bigDriver bigint=null,@dtStart datetime =null,@dtEnd datetime=null,
						@intBoxidLoop int=null,@vcEndAddress varchar(200)=null,@bigDistance bigint=null,@intMaxSpeed INT=null,@INTDistance INT=null
					SELECT @bigDriver=DriverID,@dtStart =PunchIn,@intBoxidLoop=Boxid,@bigDistance=ISNULL(OdoStart,0)  FROM @tblDriverPunchDetails WHERE TripId=@bigTripLoop AND PunchOut IS NULL
					
					--GET THE PUNCH OUT TIME					
				 	 SELECT TOP 1 @dtEnd=OriginDateTime,@vcEndAddress =StreetAddress,
				 		@INTDistance= (((CASE WHEN CustomProp LIKE '%Odometer=%' 
							THEN CAST(SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,1)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) AS BIGINT) ELSE 0 END)-@bigDistance)* @ConversionFactor) 
						FROM rvlfMsgInHst 
							WHERE BoxId =@intBoxidLoop
								AND OriginDateTime >@dtStart
								AND	OriginDateTime <= @dtEndDate
								AND BoxMsgInTypeId =76
								AND	(CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) AS BIGINT) ELSE 0 END = @bigDriver)		 
								AND (CASE WHEN CustomProp LIKE '%Driver Status=%' 
									THEN SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,
									(CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,1))-(CHARINDEX('Driver Status=',CustomProp,1)+14))) ELSE 'NI' END)='OUT'
								ORDER BY OriginDateTime 									
					IF(@dtEnd IS NOT NULL)
						BEGIN
							SELECT @intMaxSpeed= MAX(Speed) FROM rvlfMsgInHst WHERE BoxId=@intBoxidLoop AND OriginDateTime BETWEEN @dtStart AND @dtEnd 
						END
					UPDATE @tblDriverPunchDetails SET PunchOut =@dtEnd,PunchOutAddress =@vcEndAddress,Distance =@INTDistance,MaxSpeed=@intMaxSpeed WHERE DriverID=@bigDriver AND PunchIn =@dtStart AND BoxId=@intBoxidLoop AND PunchOut IS NULL
					
					SELECT @bigTripLoop =MIN(TripId) FROM @tblDriverPunchDetails  WHERE TripId  > @bigTripLoop 								
				END		
						
		END  
		
		SELECT DriverId,VehicleName,PunchIn,PunchInAddress,PunchOut,PunchOutAddress,dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(DATEDIFF(S,PunchOut,PunchIn),0))AS TotDuration FROM @tblDriverPunchDetails 	
			
	SET NOCOUNT OFF  
END 


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverRating]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetDriverRating]  
 @bigFleetID bigint = null,  
 @intBoxID int = null,  
 @bigVehicleID bigint = null,  
 @bigOrganizationID bigint = null  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_GetDriverRating] @bigOrganizationID=2  
-- Description : To get the driver rating with messages  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 17-Jun-2010 VN Created Intial Version   
--    : 21-Jun-2010 MJJC Included another select to have the default rating in row format  
/******************************************************************************/  
BEGIN  
 SELECT VR.RATINGID,VR.BoxMsgInTypeID,BM.BoxMsgInTypeDesc,VR.Rating,BM.BoxMsgInTypeDesc     
  FROM rvlfViolationRating VR  
   INNER JOIN rvlfBoxMsgInType BM ON BM.BoxMsgInTypeId=VR.BoxMsgInTypeID   
  WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR VR.OrganizationID=@bigOrganizationID)  
   AND(@intBoxID IS NULL OR @intBoxID='' OR VR.BoxMsgInTypeID=@intBoxID)  
   AND(@bigVehicleID IS NULL OR @bigVehicleID='' OR VR.VehicleID=@bigVehicleID)  
    
 /************ Added by MJJC **************/  
 SELECT [4] as SP,[14] as HBP, [15] as EBP, [16] as HAP, [17] as EAP,[66] as ACC FROM (  
   SELECT mt.BoxMsgInTypeId, vr.Rating FROM rvlfViolationRating vr   
    INNER JOIN rvlfOrganization g ON vr.OrganizationID= g.OrganizationId  
    INNER JOIN rvlfBoxMsgInType mt ON mt.BoxMsgInTypeId = vr.BoxMsgInTypeID  
   WHERE vr.OrganizationID = @bigOrganizationID) as d   
  PIVOT (sum(rating) FOR Boxmsgintypeid in ([4],[14],[15],[16],[17],[66])) as p  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverShiftsAndGroups]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetDriverShiftsAndGroups]  
(  
  @bigOrganizationId bigint=null,  
  @bigShiftId bigint=null,  
  @bigDriverGroupId bigint=null  
)  
AS  
/****************************************************************************************/  
-- Name    : rvlf_sp_GetDriverShiftsAndGroups 6,null,1  
-- Description   : To get the driver shift and group details  
-- Author    : Narayanasamy.V  
-- Created Date  : 25-Sep-2010  
--  Modified Date :  
/***************************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
 SELECT * FROM rvlfOrgShifts   
  WHERE (@bigOrganizationId IS NULL OR @bigOrganizationId='' OR OrganizationID=@bigOrganizationId)  
   AND(@bigShiftId IS NULL OR @bigShiftId='' OR ShiftID=@bigShiftId)  
   
 SELECT * FROM rvlfDRIVERGROUPMASTER   
  WHERE (@bigOrganizationId IS NULL OR @bigOrganizationId='' OR OrganizationID=@bigOrganizationId)  
   AND(@bigDriverGroupId IS NULL OR @bigDriverGroupId='' OR DRIVERGROUPID=@bigDriverGroupId)  
     
 SELECT * FROM rvlfIButtonMapping   
  WHERE (@bigOrganizationId IS NULL OR @bigOrganizationId='' OR OrganizationID=@bigOrganizationId)       
    
 SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverTripDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetDriverTripDetails]
	@bigFleetID bigint = null,
	@intBoxID int = null,
	@dtStartDate datetime = NULL,
	@dtEndDate datetime = NULL,
	@bigOrganizationID bigint = NULL,
	@bigQueryingUser bigint = NULL,
	@bigDriverID bigint = NULL,
	@vcDrivers varchar(100) = null
AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetDriverTripDetails 8,NULL, '2011-01-17 08:00:00 AM', '2011-01-17 08:00:00 PM', 6,62,null
--	Description	:	To get the trip summary details or Driver
--				:   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	29-Jun-2010	MJJC	Created Intial Version 
--				:	06-Aug-2010	SJ	Retrieved Odometer fields
--				:	
/******************************************************************************/


BEGIN
	SET NOCOUNT ON		
	IF @bigFleetID IS NULL
		BEGIN
			SELECT @bigFleetID=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 = @bigQueryingUser
	
	SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))
	SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))
	
	DECLARE @tblDriverTrips TABLE(
		[DriverTripId] [bigint] Identity(1,1) NOT NULL,
		[BoxId] [int] NOT NULL,
		[AssignedFrom] [datetime] NOT NULL,
		[AssignedTo] [datetime] NULL,
		[OdometerStart] [bigint] NOT NULL,
		[OdometerEnd] [bigint] NULL,
		[IsTripClosed] [bit] NULL,
		[IdlingDuration] [int] NULL,
		[StopTime] [int] NULL,
		[StartAddress] varchar(300) NULL,
		[EndAddress] varchar(300) NULL,
		[DriverID] [bigint] NULL,
		Speed int		NULL,
		VehicleID bigint,
		VehDisplayName varchar(50)
	)

	DECLARE @intDuration int
	DECLARE @dtOriginDateTime datetime
	DECLARE @bigOdoMeterReading int
	DECLARE @bitIgnitionStatus bit
	DECLARE @vcStreetAddress varchar(250)
	DECLARE @tiBoxMsgInTypeId tinyint
	DECLARE @tiSensorNo tinyint
	DECLARE @bigTripID bigint
	DECLARE @intIterator int
	DECLARE @canShowFuelMessage bit = 0
	

	IF EXISTS (SELECT * FROM rvlfPackageOperations r
		INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId
		INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId
		WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)
			BEGIN
				SET @canShowFuelMessage = 1
			END

	DECLARE @tblMessageForProcessingTrip TABLE(
		[ProcessorID] [bigint] identity(1,1) NOT NULL,	
		[Boxid] [int] NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[OdoMeterReading] [int] NULL,
		[IgnitionStatus] [bit] NULL,
		[StreetAddress] [varchar](250) NOT NULL,
		[VehicleId] [bigint] NOT NULL,		
		[CustomProp] [varchar](600) NULL,	
		[Speed] int NULL,
		[SensorMask] varchar(250) NULL,
		[TripId] [bigint] NULL,
		[Duration] [int] NULL,
		[SensorNo] [tinyint] NULL,
		[DriverID] [bigint] NULL
	)

	--CHECK IF THE DRIVER HAVE IBUTTON
	IF EXISTS(SELECT MessageInID FROM rvlfMsgInHst M
				INNER JOIN rvlfDriverMaster DM ON DM.DriverId =CASE WHEN CustomProp LIKE '%MAPID=%' 
					THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))ELSE 0  END
				INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =M.BoxId 
				INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId 	
				WHERE (V.OrganizationId = @bigOrganizationID)
					AND(DM.OrganizationID =@bigOrganizationID) 
					AND OriginDateTime BETWEEN @dtStartDate and @dtEndDate
					AND (@intBoxID is null OR M.BoxId = @intBoxID)
					AND BoxMsgInTypeId=76
					AND	(@bigDriverID IS NULL OR DM.DriverId  = @bigDriverID)	
					AND (@vcDrivers IS NULL OR DM.DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDrivers,',')))
					AND (CASE WHEN CustomProp LIKE '%Driver Status=%' 
						THEN SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,
						(CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,1))-(CHARINDEX('Driver Status=',CustomProp,1)+14))) ELSE 'NI' END)='IN')
		BEGIN
			INSERT INTO @tblDriverTrips 
				(DriverID, VehicleID, AssignedFrom, AssignedTo, VehDisplayName, BoxId,StartAddress,OdometerStart,speed)
			SELECT DriverId,V.VehicleId,M.OriginDateTime,NULL,V.VehicleDescription,M.BoxId,M.StreetAddress,
			CASE WHEN CustomProp LIKE '%Odometer=%' THEN SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END,
			M.Speed 
			FROM rvlfMsgInHst M
				INNER JOIN rvlfDriverMaster DM ON DM.DriverId =CASE WHEN CustomProp LIKE '%MAPID=%' 
					THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))ELSE 0  END
				INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =M.BoxId 
				INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId 	
				WHERE (V.OrganizationId = @bigOrganizationID)
					AND(DM.OrganizationID =@bigOrganizationID) 
					AND OriginDateTime BETWEEN @dtStartDate and @dtEndDate
					AND (@intBoxID is null OR M.BoxId = @intBoxID)
					AND BoxMsgInTypeId=76
					AND	(@bigDriverID IS NULL OR CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) AS BIGINT) ELSE 0 END = @bigDriverID)	
					AND (@vcDrivers IS NULL OR CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) AS BIGINT) ELSE 0 END IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDrivers,',')))	 
					AND (CASE WHEN CustomProp LIKE '%Driver Status=%' 
						THEN SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,
						(CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,1))-(CHARINDEX('Driver Status=',CustomProp,1)+14))) ELSE 'NI' END)='IN'
				
			DECLARE @bigBehaviourLoop bigint=null
			SELECT @bigBehaviourLoop=MIN(DriverTripId) FROM @tblDriverTrips						
			WHILE @bigBehaviourLoop IS NOT NULL
				BEGIN
					DECLARE @bigDriver bigint=null,@dtStart datetime =null,@dtEnd datetime=null,@bitTripClosed bit=1,
						@intBoxidLoop int=null,@vcEndAddress varchar(200)=null,@intIdling int=null,@bigOdoEnd bigint=null,
						@tintSpeed tinyint=null
					SELECT @bigDriver=DriverID,@dtStart =AssignedFrom,@intBoxidLoop=BoxId  FROM @tblDriverTrips WHERE DriverTripId=@bigBehaviourLoop AND AssignedTo IS NULL
					
					--GET THE PUNCH OUT TIME					
				 	 SELECT TOP 1 @dtEnd=OriginDateTime,@vcEndAddress=StreetAddress,
				 		@bigOdoEnd=(CASE WHEN CustomProp LIKE '%Odometer=%' THEN SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END),
				 		@tintSpeed=Speed
						FROM rvlfMsgInHst 
							WHERE BoxId =@intBoxidLoop
								AND OriginDateTime >@dtStart
								AND	OriginDateTime <= @dtEndDate
								AND BoxMsgInTypeId =76
								AND	(CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) AS BIGINT) ELSE 0 END = @bigDriver)		 
								AND (CASE WHEN CustomProp LIKE '%Driver Status=%' 
									THEN SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,
									(CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,1))-(CHARINDEX('Driver Status=',CustomProp,1)+14))) ELSE 'NI' END)='OUT'
								ORDER BY OriginDateTime 
					IF(@dtEnd IS NULL OR @dtEnd ='')
						BEGIN
							SET @bitTripClosed =0
							SET @dtEnd =@dtEndDate 
							SELECT TOP 1 @bigOdoEnd=(CASE WHEN CustomProp LIKE '%Odometer=%' THEN SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END)
							FROM rvlfMsgInHst WHERE BoxId =@intBoxidLoop AND OriginDateTime<=@dtEnd AND CustomProp LIKE '%Odometer=%' ORDER BY OriginDateTime DESC
						END
					SET @intIdling=(SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)as int)),0)
								FROM rvlfMsgInHst  
								WHERE BoxMsgInTypeId=9 AND BoxId=@intBoxidLoop 
									AND OriginDateTime BETWEEN @dtStart and @dtEnd
									GROUP BY BoxId)
					UPDATE @tblDriverTrips SET AssignedTo =@dtEnd,EndAddress=@vcEndAddress,IdlingDuration=@intIdling,IsTripClosed=@bitTripClosed,
						OdometerEnd=@bigOdoEnd,Speed =@tintSpeed,StopTime=DATEDIFF(S,@dtEnd,(SELECT AssignedFrom FROM @tblDriverTrips WHERE DriverTripId=(@bigBehaviourLoop+1)))    					
					WHERE DriverID=@bigDriver AND AssignedFrom =@dtStart AND BoxId=@intBoxidLoop AND AssignedTo IS NULL
					
					INSERT INTO @tblMessageForProcessingTrip (
					Boxid, OriginDateTime, BoxMsgInTypeId, OdoMeterReading, IgnitionStatus, StreetAddress,
					VehicleId,CustomProp,  Speed,
					SensorMask, Duration, SensorNo,DriverID,TripId)
						SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,
							CAST( SUBSTRING (h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)+9,CHARINDEX(';',h.CustomProp,
								CHARINDEX('Odometer=',h.CustomProp,1)) - (CHARINDEX('Odometer=',h.CustomProp,1)+9)) as int) as OdoMeterReading,
							cast( SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,
							ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,va.VehicleId,h.CustomProp, Speed 
							,Case
								WHEN h.BoxMsgInTypeId=76 AND CustomProp LIKE '%Driver Status=IN%' THEN 'Driver Login'
								WHEN h.BoxMsgInTypeId=76 AND CustomProp LIKE '%Driver Status=OUT%' THEN 'Driver Logout' 
								WHEN h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc 
								WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +
								CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +
								dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'
								ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID, 
								h.OriginDateTime, @canShowFuelMessage)END, 
							CASE WHEN h.BoxMsgInTypeID = 9 THEN 
								CAST(dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeID, h.BoxId,0) as int) ELSE 0 END,
							CASE WHEN h.BoxMsgInTypeId = 2 THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,
								CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END, @bigDriver,@bigBehaviourLoop
								from rvlfMsgInHst h 
									INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId
									INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
									INNER JOIN rvlfFleetVehicles fv ON va.VehicleId = fv.VehicleId
									INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId
									INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId
								where h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)
								AND 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 ( @bigFleetID IS NULL  OR f.FleetId = @bigFleetID) 										
										 AND h.OriginDateTime between @dtStart and @dtEnd           
										AND (h.BoxID = @intBoxidLoop)
									order by h.origindatetime asc
					SELECT @bigBehaviourLoop =MIN(DriverTripId) FROM @tblDriverTrips WHERE DriverTripId > @bigBehaviourLoop 								
				END													
		END				
	ELSE
		BEGIN			
			INSERT INTO @tblDriverTrips 
				(DriverID, VehicleID, AssignedFrom, AssignedTo, VehDisplayName, BoxId,StartAddress,OdometerStart,speed)
				SELECT DriverId,V.VehicleId,da.FromTime,da.ToTime,V.VehicleDescription,M.BoxId,M.StreetAddress,
					CASE WHEN CustomProp LIKE '%Odometer=%' THEN SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END,
					M.Speed FROM rvlfDriverAssignment da 
						INNER JOIN rvlfVehicleAssignment va ON vA.BoxId  = Da.BOXID 
						INNER JOIN rvlfVehicle v ON v.VehicleId = Va.VehicleId						
						INNER JOIN rvlfMsgInHst M ON M.BoxId=VA.BoxId 
					WHERE (@bigDriverID IS NULL OR da.DriverId = @bigDriverID)
						AND OrganizationId = @bigOrganizationID 
						AND (da.FromTime Between @dtStartDate and @dtEndDate)
						AND (M.OriginDateTime BETWEEN @dtStartDate and @dtEndDate)
						AND (@intBoxID is null OR M.BoxId = @intBoxID)
						--AND da.AssignmentID = 10
						ORDER by da.FromTime asc
						
				WHILE @bigBehaviourLoop IS NOT NULL
				BEGIN
					SET @bigDriver=null;SET @dtStart=null;SET @dtEnd=null;SET @bitTripClosed=1;
						SET @intBoxidLoop=NULL;SET @vcEndAddress=null;SET @intIdling =null;SET @bigOdoEnd =null;
						SET @tintSpeed =null
					SELECT @bigDriver=DriverID,@dtStart =AssignedFrom,@intBoxidLoop=BoxId,@dtEnd=AssignedTo   FROM @tblDriverTrips WHERE DriverTripId=@bigBehaviourLoop AND AssignedTo IS NULL
					
					IF(@dtEnd IS NULL OR @dtEnd ='')
						BEGIN
							SET @bitTripClosed =0
							SET @dtEnd =@dtEndDate 
						END
					--GET THE PUNCH OUT TIME					
				 	 SELECT TOP 1 @vcEndAddress=StreetAddress,
				 		@bigOdoEnd=(CASE WHEN CustomProp LIKE '%Odometer=%' THEN SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END),
				 		@tintSpeed=Speed
						FROM rvlfMsgInHst 
							WHERE BoxId =@intBoxidLoop
								AND OriginDateTime >@dtStart
								AND	OriginDateTime <= @dtEnd								
								ORDER BY OriginDateTime DESC 
					
					SET @intIdling=(SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)as int)),0)
								FROM rvlfMsgInHst  
								WHERE BoxMsgInTypeId=9 AND BoxId=@intBoxidLoop 
									AND OriginDateTime BETWEEN @dtStart and @dtEnd
									GROUP BY BoxId)
					UPDATE @tblDriverTrips SET AssignedTo =@dtEnd,EndAddress=@vcEndAddress,IdlingDuration=@intIdling,IsTripClosed=@bitTripClosed,
						OdometerEnd=@bigOdoEnd,Speed =@tintSpeed,StopTime=DATEDIFF(S,@dtEnd,(SELECT AssignedFrom FROM @tblDriverTrips WHERE DriverTripId=(@bigBehaviourLoop+1)))    					
					WHERE DriverID=@bigDriver AND AssignedFrom =@dtStart AND BoxId=@intBoxidLoop AND AssignedTo IS NULL
					
					INSERT INTO @tblMessageForProcessingTrip (
					Boxid, OriginDateTime, BoxMsgInTypeId, OdoMeterReading, IgnitionStatus, StreetAddress,
					VehicleId,CustomProp,  Speed,
					SensorMask, Duration, SensorNo,DriverID,TripId)
						SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,
							CAST( SUBSTRING (h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)+9,CHARINDEX(';',h.CustomProp,
								CHARINDEX('Odometer=',h.CustomProp,1)) - (CHARINDEX('Odometer=',h.CustomProp,1)+9)) as int) as OdoMeterReading,
							cast( SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,
							ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,va.VehicleId,h.CustomProp, Speed 
							,Case WHEN h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc 
								WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +
								CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +
								dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'
								ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID, 
								h.OriginDateTime, @canShowFuelMessage)END, 
							CASE WHEN h.BoxMsgInTypeID = 9 THEN 
								CAST(dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeID, h.BoxId,0) as int) ELSE 0 END,
							CASE WHEN h.BoxMsgInTypeId = 2 THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,
								CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END, @bigDriver,@bigBehaviourLoop
								from rvlfMsgInHst h 
									INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId
									INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
									INNER JOIN rvlfFleetVehicles fv ON va.VehicleId = fv.VehicleId
									INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId
									INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId
								where h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)
								AND 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 ( @bigFleetID IS NULL  OR f.FleetId = @bigFleetID) 										
										 AND h.OriginDateTime between @dtStart and @dtEnd           
										AND (h.BoxID = @intBoxidLoop)
									order by h.origindatetime asc					
					SELECT @bigBehaviourLoop =MIN(DriverTripId) FROM @tblDriverTrips WHERE DriverTripId > @bigBehaviourLoop 								
				END								
						
		END
		UPDATE @tblDriverTrips SET StopTime = DATEDIFF(ss, AssignedTo, @dtEndDate) WHERE DriverTripId =(SELECT MAX(DriverTripId) FROM @tblDriverTrips)		
	
DECLARE @TBLMAXSPEED TABLE( TRIPID BIGINT,PEAKSPEED INT)
INSERT INTO @TBLMAXSPEED (TRIPID,PEAKSPEED)
	SELECT TripId,MAX(SPEED) FROM @tblMessageForProcessingTrip GROUP BY TripId 

	
		Select TripId,VehicleDescription,VIN,LicensePlate,MakeName,ModelName,ModelYear,A.BoxId,OriginDateTime,
		SensorMask,CASE WHEN Ceiling(Speed)=0 THEN '-' ELSE Ceiling(Speed) END AS Speed,StreetAddress,StartAddress,EndAddress,StartDate,EndDate,
		CASE WHEN Cast(OdometerEnd as Int) < Cast(OdometerStart as int) Then 0 
		ELSE Cast((Cast(OdometerEndReading as Int)-Cast(OdometerStartReading as int)) as nvarchar(20)) END Distance,Duration,	
		IdilingDuration,IdlingTime,StopTime,DistanceCaption,SpeedCaption,DriverID,DriverName,LicenseNo,MobileNo,
		/*OdometerStart,*/Odometer OdometerStart,OdometerEnd,PEAKSPEED,		
		CAST(A.OdometerStartReading as nvarchar(10)) + ' - ' +  CAST(A.OdometerEndReading as nvarchar(10)) As OdometerReading 
		FROM 
		(SELECT t.DriverTripId as TripId,t.BoxId, 
			DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,p.OriginDateTime)) as OriginDateTime, p.SensorMask, p.Speed, p.StreetAddress,
			t.StartAddress, t.EndAddress,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,t.AssignedFrom)) as StartDate,
			CASE WHEN T.IsTripClosed =0 THEN 'OnGoing Trip' ELSE CAST(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,t.AssignedTo)) AS VARCHAR) END as EndDate,
			CAST(CAST((ABS(t.OdometerEnd - t.OdometerStart)*@ConversionFactor) AS numeric(7,2)) as varchar(20)) as Distance,	 
			Convert(varchar,t.AssignedTo - t.AssignedFrom,108) as Duration, dbo.rvlf_fn_GetTimeFromSeconds(t.IdlingDuration) AS IdilingDuration,
			t.IdlingDuration as IdlingTime,t.IsTripClosed, 
			NULL AS StopTime,S.PEAKSPEED,
				@DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption, t.DriverId,
			d.DisplayName as DriverName, d.LicenseNo, d.MobileNo,
			CEILING(CAST (t.OdometerStart*@ConversionFactor as numeric(9,2)))as OdometerStart, 
			CEILING(CAST (t.OdometerEnd*@ConversionFactor as numeric(9,2)))as OdometerEnd,
			(SELECT TOP 1 CEILING(CAST (tt.OdometerStart*@ConversionFactor as numeric(9,2))) FROM @tblDriverTrips tt WHERE tt.BoxId = t.BoxId and tt.DriverTripId = p.TripId ORDER BY OdometerStart ASC) As OdometerStartReading, 
			(SELECT TOP 1 CEILING(CAST(tt.OdometerEnd * @ConversionFactor as numeric(9,2))) FROM @tblDriverTrips tt WHERE tt.BoxId = t.BoxId and tt.DriverTripId = p.TripId and tt.DriverID=p.DriverID ORDER BY OdometerEnd DESC) AS OdometerEndReading	,
			CEILING(CAST((ABS(ISNULL(p.OdoMeterReading, 0)) * @ConversionFactor) as varchar(20)))as Odometer
		FROM @tblMessageForProcessingTrip p 
			INNER JOIN rvlfdriverMaster d ON p.DriverID = d.DriverID
			LEFT OUTER JOIN @tblDriverTrips t ON p.TripId = t.DriverTripId  
			LEFT OUTER JOIN @TBLMAXSPEED S ON S.TripId = P.TripId
		WHERE t.DriverTripId is not null-- IsTripClosed = 1
	    )A
	    INNER JOIN rvlfVehicleAssignment va ON A.BoxId = va.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId
		LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId
		ORDER BY A.TripId, OriginDateTime


	
	SET NOCOUNT OFF

END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverTripDetails_Opt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    
CREATE  PROCEDURE [dbo].[rvlf_sp_GetDriverTripDetails_Opt]    
 @bigFleetID bigint = null,            
 @intBoxID varchar(max) = null,            
 @dtStartDate datetime = null,            
 @dtEndDate datetime = null,            
 @bigOrganizationID bigint = null,            
 @bigQueryingUser bigint = null,            
 @bigDriverID bigint = NULL,            
 @bigDriverGroupId bigint= null            
AS            
/******************************************************************************/            
-- Name  : [rvlf_sp_GetDriverTripDetails] 519,'4481','2015-05-26 08:00:00 AM','2015-05-26 08:00:00 PM',257,502,null,null            
-- Description : To get the driver trip details            
-- Author  : V.Narayanasamy.            
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--    : 23-Apr-2011 VN Created Intial Version             
--          : 10-Aug-2011 Ranjith Date format Included          
/******************************************************************************/            
            
BEGIN            
 Declare @dtFDate datetime =@dtStartDate          
 Declare @dtEDate datetime =@dtEndDate          
 IF @bigFleetID IS NULL            
  BEGIN            
   SELECT @bigFleetID=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)            
 DECLARE @canShowFuelMessage bit = 0            
 DECLARE @DefaultDateFormat INT = 0          
             
    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,          
     @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 = @bigQueryingUser            
             
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))            
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))            
             
 IF EXISTS (SELECT * FROM rvlfPackageOperations r            
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId            
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId            
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)            
   BEGIN            
    SET @canShowFuelMessage = 1            
   END            
             
             
 --GET THE BOXIDS FOR THE FLEET            
 DECLARE @vcBoxIds VARCHAR(MAX)=NULL            
  SELECT @vcBoxIds=COALESCE(@vcBoxIds,'')+CONVERT(VARCHAR,VA.BoxId)+',' FROM rvlfFleetVehicles FV             
   INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=FV.VehicleId             
  WHERE FV.FleetId=@bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0'  OR VA.BOXID in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))             
 -------------------------------------            
             
             
             
 --GET THE DRIVERS FOR THE ORGANIZATION            
 DECLARE @vcDriverIds VARCHAR(MAX)=NULL            
  SELECT @vcDriverIds=COALESCE(@vcDriverIds,'')+CONVERT(VARCHAR,DM.DriverId)+','  FROM rvlfDriverMaster DM            
    LEFT OUTER JOIN rvlfDriverGroupAssignment DG ON DG.DriverId=DM.DriverId             
   WHERE OrganizationID=@bigOrganizationID             
    AND (@bigDriverID IS NULL OR @bigDriverID='' OR DM.DriverId=@bigDriverID)             
    AND (@bigDriverGroupId IS NULL OR @bigDriverGroupId='' OR DG.DriverGroupId=@bigDriverGroupId)            
                
 --GET THE DRIVER TRIPS            
 DECLARE @tblDriverTrips TABLE            
 (            
  ProcessId bigint identity(1,1),            
  Boxid int null,            
  DriverId bigint null,            
  TripTime datetime null,            
  TripStatus varchar(5)null,            
  Customprop varchar(600) null,            
  BoxmsgTypeId tinyint null,            
  Speed int null,            
  StreetAddress varchar(300) null,            
  MsgDetails varchar(300) null             
 )                
             
 --GET THE FIRST PUNCH DETAILS FROM DRIVER ASSIGNMENT            
 DECLARE @DTFIRSTPUNCH DATETIME =NULL,@bitIsIbutton bit=null ,@bitIsRFID bit=null    
            
 SELECT TOP 1 @DTFIRSTPUNCH=PunchIn FROM rvlfDriverAssignment             
  WHERE BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))            
   AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))             
   AND PunchIn IS NOT NULL AND PunchOut IS NOT NULL            
    AND PunchIn BETWEEN @dtStartDate  AND @dtEndDate           
  ORDER BY PunchIn             
              
 --CHECK IF THE PUNCH IS BEFORE THE STATDATEANDTIME              
 IF(@DTFIRSTPUNCH IS NOT NULL AND @DTFIRSTPUNCH<@dtStartDate)            
 BEGIN SET @DTFIRSTPUNCH=@dtStartDate END          
 ELSE IF (@DTFIRSTPUNCH IS NULL) BEGIN SET @DTFIRSTPUNCH=@dtStartDate END          
              
 --GET THE IBUTTON RIGHTS FOR THE ORGANIZATION            
 SELECT @bitIsIbutton= CASE WHEN PO.PackageId IS NULL OR PO.PackageId ='' THEN 0 ELSE 1 END             
  FROM rvlfPackageOperations PO            
   INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId             
  WHERE OperationID =147 AND IsActive =1 AND OrganizationID=@bigOrganizationID             
        
 IF (@bitIsIbutton=1)            
  BEGIN            
   INSERT INTO @tblDriverTrips (Boxid,DriverId,TripTime,TripStatus)            
    SELECT BoxId,CASE WHEN CustomProp LIKE'%MAPID=%' THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,            
      (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))) ELSE 0 END,OriginDateTime,            
      SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,0)+14,            
    (CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,0))-(CHARINDEX('Driver Status=',CustomProp,0)+14)))            
     FROM rvlfMsgInHst             
      WHERE BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))            
       AND BoxMsgInTypeId =76            
       AND SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,            
        (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))) IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))            
       AND CustomProp LIKE'%Driver Status=%' AND CustomProp LIKE '%MAPID=%'                  
       --AND OriginDateTime BETWEEN @dtStartDate AND CASE WHEN @DTFIRSTPUNCH IS NOT NULL THEN CASE WHEN @DTFIRSTPUNCH BETWEEN @dtStartDate AND @dtEndDate THEN @DTFIRSTPUNCH ELSE @dtEndDate END ELSE @dtEndDate END            
       AND OriginDateTime BETWEEN @dtStartDate AND  @dtEndDate             
       AND BoxMsgInTypeId IN(SELECT DISTINCT MT.BoxMsgInTypeId  FROM rvlfUserGroupSecurity UGS             
        INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId             
        INNER JOIN rvlfBoxMsgInType MT ON MT.OperationTypeID=UGS.OperationTypeId             
       WHERE UGA.UserId=@bigQueryingUser)            
      ORDER BY BoxId, SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,            
        (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))),OriginDateTime            
  END            
    
 SELECT  @bitIsRFID = CASE WHEN PO.OperationID=188 AND (PO.PackageId IS NULL OR PO.PackageId ='') THEN 0 WHEN PO.OperationID=188 THEN 1  END  FROM rvlfPackageOperations PO INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId               
 WHERE OperationID IN (188) AND IsActive =1 AND OrganizationID=@bigOrganizationID     
      
 IF (@bitIsRFID =1) --RFID 29-may15       
  BEGIN         INSERT INTO @tblDriverTrips (Boxid,DriverId,TripTime,TripStatus)      
   SELECT h.BoxId,DM.DriverId,h.OriginDateTime,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Punch:',';')      
   FROM rvlfMsgInHst h       
   INNER JOIN rvlfIButtonMapping BM ON (IButtonKey=dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'RF_ID=',';')) AND BM.KeyType=3         
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=BM.DriverId        
   WHERE h.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))        
   AND ((h.BoxMsgInTypeId=100 AND h.CustomProp like '%RF_ID=%') )        
   AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate          
   AND BoxMsgInTypeId IN(100)   AND DM.DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))    
   ORDER BY h.BoxId,h.MessageInID,DM.DriverId,h.OriginDateTime          
  END    
       
        
 --GET THE TRIPS            
 DECLARE @tblDriverTripDetails TABLE            
 (              
  TripId bigint identity(1,1),            
  Boxid int null,            
  DriverId bigint null,            
  StartTime datetime null,            
  EndTime datetime null,            
  TripInStatus varchar(5) null,            
  TripOutStatus varchar(5) null,            
  RunningTime int null,            
  IdlingTime int null,            
  Speed int null,            
  OdoStart bigint null,            
  OdoEnd bigint null,            
  StartAddress varchar(300) null,            
  EndAddress varchar(300) null            
 )             
 INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)           
 SELECT MT.Boxid,MT.DriverId,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus            
   FROM @tblDriverTrips AS MT             
    LEFT OUTER JOIN @tblDriverTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'IN' and MT.DriverId=ST.DriverId     and MT.TripStatus='OUT'             
              
 --DELETE THE INVALID TRIPS              
 DELETE FROM @tblDriverTripDetails WHERE StartTime IS NULL --OR TripInStatus=TripOutStatus             
 DELETE FROM @tblDriverTrips             
             
 --GET THE MANUEL AND AUTOMATIC SCHEDULES            
 IF(@DTFIRSTPUNCH IS NOT NULL)            
  BEGIN            
   INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)            
   SELECT BoxId,DriverId,CASE WHEN PunchOut IS NULL THEN ToTime ELSE PunchOut END,'OUT',            
    CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END,'IN'              
    FROM rvlfDriverAssignment              
    WHERE @DTFIRSTPUNCH BETWEEN (CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END)          
 AND (CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END)          
    --@DTFIRSTPUNCH <= CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END             
    --AND @dtEndDate >= CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END            
     AND BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))            
     AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))             
  END            
 ELSE            
  BEGIN            
   INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)            
   SELECT BoxId,DriverId,CASE WHEN PunchOut IS NULL THEN ToTime ELSE PunchOut END,'OUT',            
    CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END,'IN'              
    FROM rvlfDriverAssignment              
     WHERE @dtStartDate BETWEEN (CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END)          
   AND (CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END)          
      --@dtStartDate <= CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END             
      --AND @dtEndDate >= CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END            
      AND BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))            
      AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))             
  END            
              
             
 --GET THE TRIP DETAILS            
 DECLARE @bigTripid bigint=null            
 SELECT @bigTripid = MIN(TripId) FROM @tblDriverTripDetails            
 WHILE (@bigTripid IS NOT NULL)            
  BEGIN            
   DECLARE @dtTripStart datetime=null,@dtTripEnd datetime=null            
   SET @intBoxID=NULL            
   SET @bigDriverID =NULL            
   SELECT @intBoxID=Boxid,@bigDriverID=DriverId,@dtTripStart =StartTime,@dtTripEnd=EndTime FROM @tblDriverTripDetails WHERE TripId=@bigTripid             
               
   INSERT INTO @tblDriverTrips (Boxid,DriverId,BoxmsgTypeId,Customprop,Speed,TripTime,StreetAddress,MsgDetails,TripStatus)            
    SELECT BoxId,@bigDriverID, H.BoxMsgInTypeId,CustomProp,Speed,OriginDateTime,            
    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 h.BoxMsgInTypeId=76 AND CustomProp LIKE '%Driver Status=IN%' THEN ISNULL(DM.DisplayName,'Unknown Driver')+ ' - Login'            
      WHEN h.BoxMsgInTypeId=76 AND CustomProp LIKE '%Driver Status=OUT%' THEN ISNULL(DM.DisplayName,'Unknown Driver')+ ' - Logout'             
      WHEN h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc             
      WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +            
      CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +            
         dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'            
      ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID,             
     h.OriginDateTime, @canShowFuelMessage)END,CAST(@bigTripid AS VARCHAR)                       
    FROM rvlfMsgInHst H            
     INNER JOIN rvlfBoxMsgInType M ON M.BoxMsgInTypeId=H.BoxMsgInTypeId             
     LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID              
     LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId =CASE WHEN CustomProp LIKE '%MAPID=%' THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) ELSE '0' END            
    WHERE BoxId=@intBoxID AND OriginDateTime BETWEEN @dtTripStart AND @dtTripEnd             
     AND H.BoxMsgInTypeId IN(SELECT DISTINCT MT.BoxMsgInTypeId  FROM rvlfUserGroupSecurity UGS             
        INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId             
        INNER JOIN rvlfBoxMsgInType MT ON MT.OperationTypeID=UGS.OperationTypeId             
       WHERE UGA.UserId=@bigQueryingUser)ORDER BY OriginDateTime              
           
           
   UPDATE @tblDriverTripDetails SET Speed=(SELECT ISNULL(MAX(Speed),0) FROM @tblDriverTrips             
     WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd AND DriverId=@bigDriverID AND Speed!=0 AND Speed IS NOT NULL),  --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 @tblDriverTrips  WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd             
    --     AND DriverId=@bigDriverID AND BoxmsgTypeId =9 AND CustomProp NOT LIKE '%Idling:0;%'),            
    RunningTime=(SELECT ISNULL(SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,            
        (CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60,0)                         
        FROM @tblDriverTrips  WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart             
         AND @dtTripEnd AND DriverId=@bigDriverID AND  BoxmsgTypeId =3 AND Customprop NOT LIKE '%SENSOR_DURATION=0;%'),            
    OdoStart=(SELECT TOP 1 CASE WHEN CustomProp LIKE '%Odometer=%' THEN             
      SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,            
      CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END             
      FROM @tblDriverTrips WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd AND DriverId=@bigDriverID   
      AND BoxmsgTypeId in(76,100)),            
    OdoEnd=(SELECT TOP 1 CASE WHEN CustomProp LIKE '%Odometer=%' THEN             
      SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,            
      CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END             
      FROM @tblDriverTrips WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd AND DriverId=@bigDriverID   
      AND BoxmsgTypeId in(76,100) ORDER BY TripTime DESC),            
    StartAddress =(SELECT TOP 1 StreetAddress  FROM @tblDriverTrips WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd AND DriverId=@bigDriverID AND BoxmsgTypeId in(76,100) ORDER BY TripTime),            
    EndAddress =(SELECT TOP 1 StreetAddress  FROM @tblDriverTrips WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd AND DriverId=@bigDriverID AND BoxmsgTypeId in(76,100) ORDER BY TripTime DESC)                                     
   WHERE TripId=@bigTripid             
               
   --CALCULTE THE IDLING TIME            
   DECLARE @DTIDLINGEND DATETIME =NULL,@DTIDLINGSTART DATETIME =NULL            
            
   SELECT @DTIDLINGEND= CASE WHEN (SELECT TOP 1 Customprop FROM @tblDriverTrips WHERE BoxId=@intBoxID             
     AND TripTime BETWEEN @dtTripStart AND @dtTripEnd            
     AND BoxmsgTypeId  =9 ORDER BY TripTime) NOT LIKE '%Idling:0;%' THEN             
      (SELECT TOP 1 TripTime FROM @tblDriverTrips WHERE BoxId=@intBoxID             
     AND TripTime BETWEEN @dtTripStart AND @dtTripEnd            
     AND BoxmsgTypeId =9 AND CustomProp NOT LIKE '%Idling:0;%' ORDER BY TripTime) ELSE @dtTripStart END            
            
   SELECT @DTIDLINGSTART= CASE WHEN (SELECT TOP 1 CustomProp FROM @tblDriverTrips WHERE BoxId=@intBoxID             
     AND TripTime BETWEEN @dtTripStart AND @dtTripEnd            
     AND BoxmsgTypeId =9 ORDER BY TripTime DESC)  LIKE '%Idling:0;%' THEN             
      (SELECT TOP 1 TripTime FROM @tblDriverTrips WHERE BoxId=@intBoxID             
     AND TripTime BETWEEN @dtTripStart AND @dtTripEnd            
     AND BoxmsgTypeId =9 AND CustomProp LIKE '%Idling:0;%' ORDER BY TripTime DESC) ELSE @dtTripEnd END            
                     
   UPDATE @tblDriverTripDetails             
    SET IdlingTime=(ISNULL((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 @tblDriverTrips  WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd             
         AND DriverId=@bigDriverID AND BoxmsgTypeId =9 AND CustomProp NOT LIKE '%Idling:0;%'            
         AND TripTime > @DTIDLINGEND AND TripTime< @DTIDLINGSTART),0)+(DATEDIFF (S,@dtTripStart,@DTIDLINGEND))+(DATEDIFF (S,@DTIDLINGSTART,@dtTripEnd)))               
   WHERE TripId=@bigTripid             
               
   SELECT @bigTripid =MIN(TripId) FROM @tblDriverTripDetails WHERE TripId >@bigTripid                 
  END            
              
  --IF THE IDLING TIME IS EXCEED TO RUNNING TIME            
  UPDATE @tblDriverTripDetails SET RunningTime=IdlingTime WHERE IdlingTime>RunningTime             
 --GET THE SUMMARY DETAILS             
 DECLARE @tblSummary TABLE            
 (            
  Boxid int null,            
  DriverId bigint null,            
  TotDistance int null,            
  TotShiftDuration int null,            
  TotRunning int null,            
  TotIdling int null            
 )             
 INSERT INTO @tblSummary (Boxid,DriverId,TotDistance,TotIdling,TotRunning,TotShiftDuration)            
  SELECT Boxid,DriverId,SUM((OdoEnd-OdoStart)),SUM(IdlingTime),SUM(RunningTime),SUM(DATEDIFF(S,StartTime,EndTime))   FROM @tblDriverTripDetails GROUP BY Boxid,DriverId             
            
 --GET THE RESULT SET             
 SELECT distinct TD.TripId, TD.Boxid,TD.DriverId,V.VehicleId, DM.DisplayName AS DriverName,DM.LicenseNo,DM.MobileNo,V.VehicleDescription,V.LicensePlate,V.Vin,            
  CASE WHEN S.TotShiftDuration IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(S.TotShiftDuration) END AS TotShiftDuration,            
  ISNULL(S.TotDistance,'-') AS TotDistance,            
  CASE WHEN S.TotRunning IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(S.TotRunning) END AS TotRunning,            
  CASE WHEN S.TotIdling IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(S.TotIdling) END AS TotIdling,            
  StartDate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,TD.StartTime),          
  EndDate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,TD.EndTime),          
  --Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.StartTime)),@DefaultDateFormat)+ ' ' + Convert(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.StartTime))as time),22) AS StartDate,            
  --Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.EndTime)),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.EndTime)) as time),22) AS EndDate,            
  ISNULL(TD.StartAddress,'N/A') AS StartAddress,ISNULL(TD.EndAddress,'N/A')AS EndAddress,            
  dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(S,StartTime,EndTime))AS ShiftDuration,            
  ISNULL(OdoEnd-OdoStart,'-')AS Distance,            
  CASE WHEN TD.RunningTime IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(TD.RunningTime) END AS RunningTime,            
  CASE WHEN TD.IdlingTime IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(TD.IdlingTime) END AS IdlingTime,            
  TripDate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DT.TripTime),          
  --Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,DT.TripTime)),@DefaultDateFormat)+ ' ' + Convert(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,DT.TripTime))as Time),22) AS TripDate,          
  DT.StreetAddress, DT.MsgDetails,DT.Speed,          
  Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,          
  PasGenerateddate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())          
  --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate        
 
    
      
  FROM @tblDriverTripDetails TD            
   INNER JOIN @tblDriverTrips DT ON DT.DriverId=TD.DriverId AND DT.Boxid=TD.Boxid AND TD.TripId=DT.TripStatus             
   INNER JOIN @tblSummary S ON S.DriverId=TD.DriverId AND S.Boxid =TD.Boxid              
   INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =TD.Boxid             
   INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId             
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=TD.DriverId               
  ORDER BY DriverId,StartDate,EndDate,TripDate              
              
SELECT * FROM @tblDriverTripDetails ORDER BY DriverId            
SELECT * FROM @tblDriverTrips  ORDER BY DriverId               
--select * from @tblSummary                   
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverTripDetails_Opt_test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetDriverTripDetails_Opt_test]    
 @bigFleetID bigint = null,            
 @intBoxID varchar(max) = null,            
 @dtStartDate datetime = null,            
 @dtEndDate datetime = null,            
 @bigOrganizationID bigint = null,            
 @bigQueryingUser bigint = null,            
 @bigDriverID bigint = NULL,            
 @bigDriverGroupId bigint= null            
AS            
/******************************************************************************/            
-- Name  : [rvlf_sp_GetDriverTripDetails_Opt] 519,'0','2015-06-03 08:00:00 AM','2015-06-04 10:00:00 AM',257,502,null,null     
-- [rvlf_sp_GetDriverTripDetails_Opt_test] 519,'4481','2015-05-25 08:00:00 AM','2015-05-29 08:00:00 PM',257,502,649,null  
-- Description : To get the driver trip details            
-- Author  : V.Narayanasamy.            
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--    : 23-Apr-2011 VN Created Intial Version             
--          : 10-Aug-2011 Ranjith Date format Included          
/******************************************************************************/            
            
BEGIN            
 Declare @dtFDate datetime =@dtStartDate          
 Declare @dtEDate datetime =@dtEndDate          
 IF @bigFleetID IS NULL            
  BEGIN            
   SELECT @bigFleetID=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)            
 DECLARE @canShowFuelMessage bit = 0            
 DECLARE @DefaultDateFormat INT = 0          
             
    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,          
     @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 = @bigQueryingUser            
             
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))            
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))            
             
 IF EXISTS (SELECT * FROM rvlfPackageOperations r            
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId            
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId            
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)            
   BEGIN            
    SET @canShowFuelMessage = 1            
   END            
             
 --GET THE BOXIDS FOR THE FLEET            
 DECLARE @vcBoxIds VARCHAR(MAX)=NULL            
  SELECT @vcBoxIds=COALESCE(@vcBoxIds,'')+CONVERT(VARCHAR,VA.BoxId)+',' FROM rvlfFleetVehicles FV             
   INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=FV.VehicleId             
  WHERE FV.FleetId=@bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0'  OR VA.BOXID in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))             
 -------------------------------------            
             
 --GET THE DRIVERS FOR THE ORGANIZATION            
 DECLARE @vcDriverIds VARCHAR(MAX)=NULL            
  SELECT @vcDriverIds=COALESCE(@vcDriverIds,'')+CONVERT(VARCHAR,DM.DriverId)+','  FROM rvlfDriverMaster DM            
    LEFT OUTER JOIN rvlfDriverGroupAssignment DG ON DG.DriverId=DM.DriverId             
   WHERE OrganizationID=@bigOrganizationID             
    AND (@bigDriverID IS NULL OR @bigDriverID='' OR DM.DriverId=@bigDriverID)             
    AND (@bigDriverGroupId IS NULL OR @bigDriverGroupId='' OR DG.DriverGroupId=@bigDriverGroupId)            
                
 --GET THE DRIVER TRIPS            
 DECLARE @tblDriverTrips TABLE            
 (            
  ProcessId bigint identity(1,1),            
  Boxid int null,            
  DriverId bigint null,            
  TripTime datetime null,            
  TripStatus varchar(5)null,            
  Customprop varchar(600) null,            
  BoxmsgTypeId tinyint null,            
  Speed int null,            
  StreetAddress varchar(300) null,            
  MsgDetails varchar(300) null             
 )                
             
 --GET THE FIRST PUNCH DETAILS FROM DRIVER ASSIGNMENT            
 DECLARE @DTFIRSTPUNCH DATETIME =NULL,@bitIsIbutton bit=null ,@bitIsRFID bit=null    
            
 SELECT TOP 1 @DTFIRSTPUNCH=PunchIn FROM rvlfDriverAssignment             
  WHERE BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))            
   AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))             
   AND PunchIn IS NOT NULL AND PunchOut IS NOT NULL            
    AND PunchIn BETWEEN @dtStartDate  AND @dtEndDate           
  ORDER BY PunchIn             
              
 --CHECK IF THE PUNCH IS BEFORE THE STATDATEANDTIME              
 IF(@DTFIRSTPUNCH IS NOT NULL AND @DTFIRSTPUNCH<@dtStartDate)            
 BEGIN SET @DTFIRSTPUNCH=@dtStartDate END          
 ELSE IF (@DTFIRSTPUNCH IS NULL) BEGIN SET @DTFIRSTPUNCH=@dtStartDate END          
              
 --GET THE IBUTTON RIGHTS FOR THE ORGANIZATION            
 SELECT @bitIsIbutton= CASE WHEN PO.PackageId IS NULL OR PO.PackageId ='' THEN 0 ELSE 1 END             
  FROM rvlfPackageOperations PO            
   INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId             
  WHERE OperationID =147 AND IsActive =1 AND OrganizationID=@bigOrganizationID             
        
 IF (@bitIsIbutton=1)            
  BEGIN            
   INSERT INTO @tblDriverTrips (Boxid,DriverId,TripTime,TripStatus)            
    SELECT BoxId,CASE WHEN CustomProp LIKE'%MAPID=%' THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,            
      (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))) ELSE 0 END,OriginDateTime,            
      SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,0)+14,            
    (CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,0))-(CHARINDEX('Driver Status=',CustomProp,0)+14)))            
     FROM rvlfMsgInHst             
      WHERE BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))            
       AND BoxMsgInTypeId =76            
       AND SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,            
        (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))) IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))            
       AND CustomProp LIKE'%Driver Status=%' AND CustomProp LIKE '%MAPID=%'                  
       --AND OriginDateTime BETWEEN @dtStartDate AND CASE WHEN @DTFIRSTPUNCH IS NOT NULL THEN CASE WHEN @DTFIRSTPUNCH BETWEEN @dtStartDate AND @dtEndDate THEN @DTFIRSTPUNCH ELSE @dtEndDate END ELSE @dtEndDate END            
       AND OriginDateTime BETWEEN @dtStartDate AND  @dtEndDate             
       AND BoxMsgInTypeId IN(SELECT DISTINCT MT.BoxMsgInTypeId  FROM rvlfUserGroupSecurity UGS             
        INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId             
        INNER JOIN rvlfBoxMsgInType MT ON MT.OperationTypeID=UGS.OperationTypeId             
       WHERE UGA.UserId=@bigQueryingUser)            
      ORDER BY BoxId, SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,            
        (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))),OriginDateTime            
  END            
    
 SELECT  @bitIsRFID = CASE WHEN PO.OperationID=188 AND (PO.PackageId IS NULL OR PO.PackageId ='') THEN 0 WHEN PO.OperationID=188 THEN 1  END  FROM rvlfPackageOperations PO INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId               
 WHERE OperationID IN (188) AND IsActive =1 AND OrganizationID=@bigOrganizationID     
      
 IF (@bitIsRFID =1) --RFID 29-may15     
  BEGIN        
   INSERT INTO @tblDriverTrips (Boxid,DriverId,TripTime,TripStatus)      
   SELECT h.BoxId,DM.DriverId,h.OriginDateTime,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Punch:',';')      
   FROM rvlfMsgInHst h       
   INNER JOIN rvlfIButtonMapping BM ON (IButtonKey=dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'RF_ID=',';')) AND BM.KeyType=3         
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=BM.DriverId        
   WHERE h.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))        
   AND ((h.BoxMsgInTypeId=100 AND h.CustomProp like '%RF_ID=%') )        
   AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate          
   AND BoxMsgInTypeId IN(100)    AND DM.DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))  
   ORDER BY h.BoxId,h.MessageInID,DM.DriverId,h.OriginDateTime          
  END    
        
 --GET THE TRIPS            
 DECLARE @tblDriverTripDetails TABLE            
 (              
  TripId bigint identity(1,1),            
  Boxid int null,            
  DriverId bigint null,            
  StartTime datetime null,            
  EndTime datetime null,            
  TripInStatus varchar(5) null,            
  TripOutStatus varchar(5) null,            
  RunningTime int null,            
  IdlingTime int null,            
  Speed int null,            
  OdoStart bigint null,            
  OdoEnd bigint null,            
  StartAddress varchar(300) null,            
  EndAddress varchar(300) null            
 )             
 INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)           
 SELECT MT.Boxid,MT.DriverId,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus            
   FROM @tblDriverTrips AS MT             
    LEFT OUTER JOIN @tblDriverTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'IN' and MT.DriverId=ST.DriverId   and MT.TripStatus='OUT'               
    
select @dtStartDate , @dtEndDate  ,'F',* from @tblDriverTrips    
    
 --DELETE THE INVALID TRIPS              
 DELETE FROM @tblDriverTripDetails WHERE StartTime IS NULL --OR TripInStatus=TripOutStatus             
 DELETE FROM @tblDriverTrips             
       select  * from @tblDriverTripDetails       
 --GET THE MANUEL AND AUTOMATIC SCHEDULES            
 IF(@DTFIRSTPUNCH IS NOT NULL)            
  BEGIN            
   INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)            
   SELECT BoxId,DriverId,CASE WHEN PunchOut IS NULL THEN ToTime ELSE PunchOut END,'OUT',            
    CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END,'IN'              
    FROM rvlfDriverAssignment              
    WHERE @DTFIRSTPUNCH BETWEEN (CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END)          
 AND (CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END)          
    --@DTFIRSTPUNCH <= CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END             
    --AND @dtEndDate >= CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END            
     AND BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))            
     AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))             
  END            
 ELSE            
  BEGIN            
   INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)            
   SELECT BoxId,DriverId,CASE WHEN PunchOut IS NULL THEN ToTime ELSE PunchOut END,'OUT',            
    CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END,'IN'              
    FROM rvlfDriverAssignment              
     WHERE @dtStartDate BETWEEN (CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END)          
   AND (CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END)          
      --@dtStartDate <= CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END             
      --AND @dtEndDate >= CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END            
      AND BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))            
      AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))             
  END            
 --  select 'A',@vcDriverIds,* from @tblDriverTripDetails           
             
 --GET THE TRIP DETAILS            
 DECLARE @bigTripid bigint=null          
 SELECT @bigTripid = MIN(TripId) FROM @tblDriverTripDetails              
 WHILE (@bigTripid IS NOT NULL)            
  BEGIN            
   DECLARE @dtTripStart datetime=null,@dtTripEnd datetime=null            
   SET @intBoxID=NULL            
   SET @bigDriverID =NULL            
   SELECT @intBoxID=Boxid,@bigDriverID=DriverId,@dtTripStart =StartTime,@dtTripEnd=EndTime FROM @tblDriverTripDetails WHERE TripId=@bigTripid             
               
   INSERT INTO @tblDriverTrips (Boxid,DriverId,BoxmsgTypeId,Customprop,Speed,TripTime,StreetAddress,MsgDetails,TripStatus)            
    SELECT BoxId,@bigDriverID, H.BoxMsgInTypeId,CustomProp,Speed,OriginDateTime,            
    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 h.BoxMsgInTypeId=76 AND CustomProp LIKE '%Driver Status=IN%' THEN ISNULL(DM.DisplayName,'Unknown Driver')+ ' - Login'            
      WHEN h.BoxMsgInTypeId=76 AND CustomProp LIKE '%Driver Status=OUT%' THEN ISNULL(DM.DisplayName,'Unknown Driver')+ ' - Logout'             
      WHEN h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc             
      WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +            
      CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +            
         dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'            
      ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID,             
     h.OriginDateTime, @canShowFuelMessage)END,CAST(@bigTripid AS VARCHAR)                       
    FROM rvlfMsgInHst H            
     INNER JOIN rvlfBoxMsgInType M ON M.BoxMsgInTypeId=H.BoxMsgInTypeId             
     LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID              
     LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId =CASE WHEN CustomProp LIKE '%MAPID=%' THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) ELSE '0' END            
    WHERE BoxId=@intBoxID AND OriginDateTime BETWEEN @dtTripStart AND @dtTripEnd             
     AND H.BoxMsgInTypeId IN(SELECT DISTINCT MT.BoxMsgInTypeId  FROM rvlfUserGroupSecurity UGS             
        INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId             
        INNER JOIN rvlfBoxMsgInType MT ON MT.OperationTypeID=UGS.OperationTypeId             
       WHERE UGA.UserId=@bigQueryingUser)ORDER BY OriginDateTime              
           
           
   UPDATE @tblDriverTripDetails SET Speed=(SELECT ISNULL(MAX(Speed),0) FROM @tblDriverTrips             
     WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd AND DriverId=@bigDriverID AND Speed!=0 AND Speed IS NOT NULL),  --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 @tblDriverTrips  WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd             
    --     AND DriverId=@bigDriverID AND BoxmsgTypeId =9 AND CustomProp NOT LIKE '%Idling:0;%'),            
    RunningTime=(SELECT ISNULL(SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,            
   (CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60,0)    
        FROM @tblDriverTrips  WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart             
         AND @dtTripEnd AND DriverId=@bigDriverID AND  BoxmsgTypeId =3 AND Customprop NOT LIKE '%SENSOR_DURATION=0;%'),            
    OdoStart=(SELECT TOP 1 CASE WHEN CustomProp LIKE '%Odometer=%' THEN             
      SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,            
      CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END             
   FROM @tblDriverTrips WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd AND DriverId=@bigDriverID     
      AND BoxmsgTypeId in(76,100)    
      ),            
    OdoEnd=(SELECT TOP 1 CASE WHEN CustomProp LIKE '%Odometer=%' THEN             
      SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,            
      CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END             
      FROM @tblDriverTrips WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd AND DriverId=@bigDriverID     
      AND BoxmsgTypeId in (76,100)    
      ORDER BY TripTime DESC),            
    StartAddress =(SELECT TOP 1 StreetAddress  FROM @tblDriverTrips WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd AND DriverId=@bigDriverID AND BoxmsgTypeId in(76,100) ORDER BY TripTime),            
    EndAddress =(SELECT TOP 1 StreetAddress  FROM @tblDriverTrips WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd AND DriverId=@bigDriverID AND BoxmsgTypeId in (76,100) ORDER BY TripTime DESC)                                     
   WHERE TripId=@bigTripid             
               
   --CALCULTE THE IDLING TIME            
   DECLARE @DTIDLINGEND DATETIME =NULL,@DTIDLINGSTART DATETIME =NULL            
            
   SELECT @DTIDLINGEND= CASE WHEN (SELECT TOP 1 Customprop FROM @tblDriverTrips WHERE BoxId=@intBoxID             
     AND TripTime BETWEEN @dtTripStart AND @dtTripEnd            
     AND BoxmsgTypeId  =9 ORDER BY TripTime) NOT LIKE '%Idling:0;%' THEN             
      (SELECT TOP 1 TripTime FROM @tblDriverTrips WHERE BoxId=@intBoxID             
     AND TripTime BETWEEN @dtTripStart AND @dtTripEnd            
     AND BoxmsgTypeId =9 AND CustomProp NOT LIKE '%Idling:0;%' ORDER BY TripTime) ELSE @dtTripStart END            
            
   SELECT @DTIDLINGSTART= CASE WHEN (SELECT TOP 1 CustomProp FROM @tblDriverTrips WHERE BoxId=@intBoxID             
     AND TripTime BETWEEN @dtTripStart AND @dtTripEnd            
     AND BoxmsgTypeId =9 ORDER BY TripTime DESC)  LIKE '%Idling:0;%' THEN             
      (SELECT TOP 1 TripTime FROM @tblDriverTrips WHERE BoxId=@intBoxID             
     AND TripTime BETWEEN @dtTripStart AND @dtTripEnd            
     AND BoxmsgTypeId =9 AND CustomProp LIKE '%Idling:0;%' ORDER BY TripTime DESC) ELSE @dtTripEnd END            
                     
   UPDATE @tblDriverTripDetails             
    SET IdlingTime=(ISNULL((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 @tblDriverTrips  WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd             
         AND DriverId=@bigDriverID AND BoxmsgTypeId =9 AND CustomProp NOT LIKE '%Idling:0;%'            
         AND TripTime > @DTIDLINGEND AND TripTime< @DTIDLINGSTART),0)+(DATEDIFF (S,@dtTripStart,@DTIDLINGEND))+(DATEDIFF (S,@DTIDLINGSTART,@dtTripEnd)))               
   WHERE TripId=@bigTripid             
               
   SELECT @bigTripid =MIN(TripId) FROM @tblDriverTripDetails WHERE TripId >@bigTripid                 
  END            
  -- select 'T', * from @tblDriverTrips    
  -- select 'TT', * from @tblDriverTripDetails           
  --IF THE IDLING TIME IS EXCEED TO RUNNING TIME            
  UPDATE @tblDriverTripDetails SET RunningTime=IdlingTime WHERE IdlingTime>RunningTime             
 -- GET THE SUMMARY DETAILS             
 DECLARE @tblSummary TABLE            
 (            
  Boxid int null,            
  DriverId bigint null,            
  TotDistance int null,            
  TotShiftDuration int null,            
  TotRunning int null,            
  TotIdling int null            
 )             
 INSERT INTO @tblSummary (Boxid,DriverId,TotDistance,TotIdling,TotRunning,TotShiftDuration)            
  SELECT Boxid,DriverId,SUM((OdoEnd-OdoStart)),SUM(IdlingTime),SUM(RunningTime),SUM(DATEDIFF(S,StartTime,EndTime))   FROM @tblDriverTripDetails GROUP BY Boxid,DriverId             
            
 --GET THE RESULT SET             
 SELECT distinct TD.TripId, TD.Boxid,TD.DriverId,V.VehicleId, DM.DisplayName AS DriverName,DM.LicenseNo,DM.MobileNo,V.VehicleDescription,V.LicensePlate,V.Vin,            
  CASE WHEN S.TotShiftDuration IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(S.TotShiftDuration) END AS TotShiftDuration,            
  ISNULL(S.TotDistance,'-') AS TotDistance,            
  CASE WHEN S.TotRunning IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(S.TotRunning) END AS TotRunning,            
  CASE WHEN S.TotIdling IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(S.TotIdling) END AS TotIdling,            
  StartDate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,TD.StartTime),          
  EndDate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,TD.EndTime),          
  --Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.StartTime)),@DefaultDateFormat)+ ' ' + Convert(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.StartTime))as time),22) AS StartDate,            
  --Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.EndTime)),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.EndTime)) as time),22) AS EndDate,            
  ISNULL(TD.StartAddress,'N/A') AS StartAddress,ISNULL(TD.EndAddress,'N/A')AS EndAddress,            
  dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(S,StartTime,EndTime))AS ShiftDuration,            
  ISNULL(OdoEnd-OdoStart,'-')AS Distance,            
  CASE WHEN TD.RunningTime IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(TD.RunningTime) END AS RunningTime,            
  CASE WHEN TD.IdlingTime IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(TD.IdlingTime) END AS IdlingTime,            
  TripDate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DT.TripTime),          
  --Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,DT.TripTime)),@DefaultDateFormat)+ ' ' + Convert(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,DT.TripTime))as Time),22) AS TripDate,          
  DT.StreetAddress, DT.MsgDetails,DT.Speed,          
  Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,          
  PasGenerateddate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())          
  --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate        
 
    
      
  FROM @tblDriverTripDetails TD            
INNER JOIN @tblDriverTrips DT ON DT.DriverId=TD.DriverId AND DT.Boxid=TD.Boxid AND TD.TripId=DT.TripStatus             
   INNER JOIN @tblSummary S ON S.DriverId=TD.DriverId AND S.Boxid =TD.Boxid              
   INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =TD.Boxid             
   INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId             
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=TD.DriverId               
  ORDER BY DriverId,StartDate,EndDate,TripDate              
              
SELECT * FROM @tblDriverTripDetails ORDER BY DriverId            
SELECT * FROM @tblDriverTrips  ORDER BY DriverId               
--select * from @tblSummary                   
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverTripSheet]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetDriverTripSheet]  
 @bigTripId bigint=null,  
 @bitIsDayHalt bit=null,  
 @bitIsNightHalt bit=null,  
 @bitIsHelper bit=null,  
 @bitIsLocalTrip bit=null,  
 @bitIsTeamVeh bit=null,  
 @bigOrganizationId bigint=null,  
 @intHoursToBeAdded INT = 0,  
 @intMinsToBeAdded INT = 0,  
 @bitIsNightDrive bit=1  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_GetDriverTripSheet]147,0,0,0,0,0,19,5,30  
-- Description : To get the driver trip sheet details  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 24-July-2010 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
   
 DECLARE @bigDriverId bigint=null  
 DECLARE @bigVehicleId bigint=null  
 DECLARE @vcVehicleType varchar(10)=null  
 DECLARE @dtDate datetime=null  
 DECLARE @dtFromDateTime datetime=null  
 DECLARE @dtToDateTime datetime=null   
 DECLARE @bigFromLandmark bigint=null  
 DECLARE @bigToLandmark bigint=null  
 DECLARE @bigOdometerStart bigint=0  
 DECLARE @bigOdometerEnd bigint=0  
 DECLARE @DISTANCE NUMERIC(7,2)=0  
 DECLARE @BATTAID BIGINT=null  
 DECLARE @RATEPERKM NUMERIC(5,2)=0  
 DECLARE @NOOFDRIVERS TINYINT=0  
 DECLARE @BREAKFAST NUMERIC(5,2)=0  
 DECLARE @OTHERS NUMERIC(5,2)=0  
 DECLARE @LUNCH NUMERIC(5,2)=0   
 DECLARE @AMT NUMERIC(7,2)=0  
 DECLARE @NightAMT NUMERIC(7,2)=0  
 DECLARE @DayAMT NUMERIC(7,2)=0  
 DECLARE @TeamAMT NUMERIC(7,2)=0  
 DECLARE @LocalTripAMT NUMERIC(7,2)=0  
 DECLARE @BattaAMT NUMERIC(7,2)=0   
 DECLARE @FoodAMt NUMERIC(7,2)=0   
 DECLARE @HELPERAMt NUMERIC(7,2)=0   
 DECLARE @NIGHTDUTYAMt NUMERIC(7,2)=0   
 DECLARE @BIGSECONDDRIVERID BIGINT=NULL   
 DECLARE @BIGTRIP BIGINT=NULL  
   
 SELECT @bigDriverId=DriverId,@bigVehicleId=VA.VehicleId,@dtDate=CONVERT(DATE,AssignmentDate),@dtFromDateTime=FromTime,  
   @dtToDateTime=ToTime,@bigFromLandmark=FromLandmarkId,@bigToLandmark=ToLandmarkId,@BIGTRIP=TRIPID   
  FROM rvlfDriverAssignment DA  
   INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=DA.BOXID WHERE AssignmentId=@bigTripId   
   
 IF(@BIGTRIP IS NOT NULL)  
  BEGIN  
   SELECT @NOOFDRIVERS=COUNT(DriverId) FROM rvlfDriverAssignment WHERE TRIPID=@bigTripId    
   SELECT @BIGTRIP=AssignmentId FROM rvlfDriverAssignment WHERE TRIPID=@BIGTRIP AND AssignmentId !=@bigTripId  
   SELECT @BIGSECONDDRIVERID=DriverId FROM rvlfDriverAssignment WHERE AssignmentId =@BIGTRIP  
  END  
    
   
 SELECT @vcVehicleType=Category FROM rvlfVehicle WHERE VehicleId=@bigVehicleId   
   
  --GET THE ODOMETER READING AT POINT POINT OF TRIP START  
  SELECT TOP 1 @bigOdometerStart = CAST( SUBSTRING (MIH.CustomProp,CHARINDEX('Odometer=',MIH.CustomProp,1)+9,CHARINDEX(';',MIH.CustomProp,  
        CHARINDEX('Odometer=',MIH.CustomProp,1)) - (CHARINDEX('Odometer=',MIH.CustomProp,1)+9)) as bigint)   
    FROM rvlfMsgInHst MIH  
    INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=MIH.BoxId   
    --INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId   
    INNER JOIN rvlfDriverAssignment DA ON DA.BOXID =VA.BoxId    
    INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId   
   WHERE VA.VehicleId =@bigVehicleId   
    AND DA.DriverId=@bigDriverId   
    AND (@bigOrganizationId IS NULL OR @bigOrganizationId='' OR (DM.OrganizationID=@bigOrganizationId))  
    AND (@dtDate IS NULL OR @dtDate='' OR CONVERT(DATE,AssignmentDate)=CONVERT(DATE,@dtDate))  
    AND (@dtFromDateTime IS NULL OR @dtFromDateTime='' OR MIH.OriginDateTime>=@dtFromDateTime )  
    AND (@dtToDateTime IS NULL OR @dtToDateTime='' OR MIH.OriginDateTime<=@dtToDateTime)  
    AND MIH.CustomProp  LIKE '%Odometer%'  
    AND BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)  
    AND BoxMsgInTypeId=2  
    ORDER BY OriginDateTime   
  IF(@bigOdometerStart IS NULL OR @bigOdometerStart='')  
   BEGIN  
    SELECT TOP 1 @bigOdometerStart = CAST( SUBSTRING (MIH.CustomProp,CHARINDEX('Odometer=',MIH.CustomProp,1)+9,CHARINDEX(';',MIH.CustomProp,  
        CHARINDEX('Odometer=',MIH.CustomProp,1)) - (CHARINDEX('Odometer=',MIH.CustomProp,1)+9)) as bigint) FROM rvlfMsgInHst MIH  
     INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=MIH.BoxId   
     --INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId   
     INNER JOIN rvlfDriverAssignment DA ON DA.BOXID =VA.BoxId    
     INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId   
    WHERE VA.VehicleId =@bigVehicleId   
     AND DA.DriverId=@bigDriverId   
     AND (@bigOrganizationId IS NULL OR @bigOrganizationId='' OR (DM.OrganizationID=@bigOrganizationId ))  
     AND (@dtDate IS NULL OR @dtDate='' OR CONVERT(DATE,AssignmentDate)=CONVERT(DATE,@dtDate))  
     AND (@dtFromDateTime IS NULL OR @dtFromDateTime='' OR MIH.OriginDateTime>=@dtFromDateTime )  
     AND (@dtToDateTime IS NULL OR @dtToDateTime='' OR MIH.OriginDateTime<=@dtToDateTime)  
     AND MIH.CustomProp  LIKE '%Odometer%'  
     AND BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)  
     ORDER BY OriginDateTime   
   END  
     
 --GET THE ODOMETER READING AT THE POINT OF TRIP END  
   
  SELECT TOP 1 @bigOdometerEnd  = CAST( SUBSTRING (MIH.CustomProp,CHARINDEX('Odometer=',MIH.CustomProp,1)+9,CHARINDEX(';',MIH.CustomProp,  
        CHARINDEX('Odometer=',MIH.CustomProp,1)) - (CHARINDEX('Odometer=',MIH.CustomProp,1)+9)) as bigint) FROM rvlfMsgInHst MIH  
    INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=MIH.BoxId   
    --INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId   
    INNER JOIN rvlfDriverAssignment DA ON DA.BOXID =VA.BOXID   
    INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId   
   WHERE VA.BoxId  =@bigVehicleId   
    AND DA.DriverId=@bigDriverId   
    AND (@bigOrganizationId IS NULL OR @bigOrganizationId='' OR (DM.OrganizationID=@bigOrganizationId))  
    AND (@dtDate IS NULL OR @dtDate='' OR CONVERT(DATE,AssignmentDate)=CONVERT(DATE,@dtDate))  
    AND (@dtFromDateTime IS NULL OR @dtFromDateTime='' OR MIH.OriginDateTime>=@dtFromDateTime )  
    AND (@dtToDateTime IS NULL OR @dtToDateTime='' OR MIH.OriginDateTime<=@dtToDateTime)  
    AND MIH.CustomProp  LIKE '%Odometer%'  
    AND BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)  
    AND BoxMsgInTypeId=3  
    ORDER BY OriginDateTime DESC  
  IF(@bigOdometerEnd IS NULL OR @bigOdometerEnd='')  
   BEGIN  
    SELECT TOP 1 @bigOdometerEnd = CAST( SUBSTRING (MIH.CustomProp,CHARINDEX('Odometer=',MIH.CustomProp,1)+9,CHARINDEX(';',MIH.CustomProp,  
        CHARINDEX('Odometer=',MIH.CustomProp,1)) - (CHARINDEX('Odometer=',MIH.CustomProp,1)+9)) as bigint) FROM rvlfMsgInHst MIH  
     INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=MIH.BoxId   
     --INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId   
     INNER JOIN rvlfDriverAssignment DA ON DA.BOXID =VA.BoxId    
     INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId   
    WHERE VA.VehicleId =@bigVehicleId   
     AND DA.DriverId=@bigDriverId   
     AND (@bigOrganizationId IS NULL OR @bigOrganizationId='' OR (DM.OrganizationID=@bigOrganizationId))  
     AND (@dtDate IS NULL OR @dtDate='' OR CONVERT(DATE,AssignmentDate)=CONVERT(DATE,@dtDate))  
     AND (@dtFromDateTime IS NULL OR @dtFromDateTime='' OR MIH.OriginDateTime>=@dtFromDateTime )  
     AND (@dtToDateTime IS NULL OR @dtToDateTime='' OR MIH.OriginDateTime<=@dtToDateTime)  
     AND MIH.CustomProp  LIKE '%Odometer%'  
     AND BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)  
     ORDER BY OriginDateTime DESC  
   END  
     
 SET @DISTANCE=@bigOdometerEnd-@bigOdometerStart    
  
  
 SET @dtFromDateTime=DATEADD(HOUR,(@intHoursToBeAdded),DATEADD(MINUTE,(@intMinsToBeAdded),@dtFromDateTime))  
 SET @dtToDateTime=DATEADD(HOUR,(@intHoursToBeAdded),DATEADD(MINUTE,(@intMinsToBeAdded),@dtToDateTime))  
    
  
 IF(@vcVehicleType IS NOT NULL)  
  BEGIN  
   --CALCULATE THE BREAKFAST AMOUNT  
   IF(CONVERT(TIME,@dtFromDateTime) <='08:00:00')  
    BEGIN  
     SET @BREAKFAST =@BREAKFAST+(SELECT OtherAmt FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='BreakFast')  
     SET @AMT=@AMT+@BREAKFAST   
    END  
      
   --CALCULATE THE LUNCH AMOUNT  
   IF(CONVERT(TIME,@dtToDateTime) >='14:00:00')  
    BEGIN  
     SET @LUNCH =@LUNCH+(SELECT OtherAmt FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Lunch')  
     SET @AMT=@AMT+@LUNCH   
    END  
     
   --CALCULATE THE DAYHALT AMOUNT  
   IF(@bitIsDayHalt=1 AND @vcVehicleType!='LMV')  
    BEGIN  
     SET @DayAMT =@DayAMT+(SELECT OtherAmt FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Dayhalt')  
     SET @AMT=@AMT+@DayAMT   
    END  
      
   --CALCULATE THE NIGHTHALT AMOUNT  
   IF(@bitIsNightHalt=1 AND @vcVehicleType!='LMV')  
    BEGIN  
     SET @NightAMT =@NightAMT+(SELECT OtherAmt FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='NightHalt')  
     SET @AMT=@AMT+@NightAMT   
    END  
     
   --CALCULATE THE HELPER AMOUNT  
   IF(@bitIsHelper=1)  
    BEGIN  
     SET @HELPERAMt=@HELPERAMt+(SELECT OtherAmt FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Helper')  
     SET @AMT=@AMT+@HELPERAMt   
    END  
      
   --CALCULATE THE NIGHT DRIVE AMOUNT  
   IF(@bitIsNightDrive=1)  
    BEGIN  
     SET @NIGHTDUTYAMt=@NIGHTDUTYAMt+(SELECT OtherAmt FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Nightduty')  
     SET @AMT=@AMT+@NIGHTDUTYAMt   
    END  
      
   --CALCULATE THE LOCAL TRIP AMOUNT  
   IF(@bitIsLocalTrip=1)  
    BEGIN  
     SET @LocalTripAMT=@LocalTripAMT+(SELECT OtherAmt FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='LocalTrip')  
     SET @AMT=@AMT+@LocalTripAMT        
    END  
   --CALCULATE THE BATTA AMOUNT FOR HMV DRIVERS  
   IF(@vcVehicleType='HMV')  
    BEGIN  
     IF(@DISTANCE >=200 AND @DISTANCE<=600)  
      BEGIN  
       IF(@NOOFDRIVERS=1)  
        BEGIN  
         SET @BattaAMT=@BattaAMT+@DISTANCE* (SELECT RatePerKM FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Batta' AND NoOfDrivers=@NOOFDRIVERS AND @DISTANCE>=FromRange AND @DISTANCE <=ToRange)  
         SET @AMT=@AMT+@BattaAMT              
        END  
       ELSE  
        BEGIN  
         SET @BattaAMT=@BattaAMT+@DISTANCE* (SELECT RatePerKM FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Batta' AND NoOfDrivers=@NOOFDRIVERS AND @DISTANCE>=FromRange AND @DISTANCE <=ToRange)  
         SET @AMT=@AMT+@BattaAMT   
        END  
      END  
     ELSE IF(@DISTANCE>=600 AND @DISTANCE<=650)  
      BEGIN  
       SET @BattaAMT=@BattaAMT+(@DISTANCE* (SELECT RatePerKM FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Batta' AND @DISTANCE>=FromRange AND @DISTANCE <=ToRange))+(SELECT OtherAmt FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Batta' AND @DISTANCE>=FromRange AND @DISTANCE <=ToRange)  
         SET @AMT=@AMT+@BattaAMT   
      END  
       
     ELSE IF(@DISTANCE>=650)  
      BEGIN  
       SET @BattaAMT=@BattaAMT+@DISTANCE* (SELECT RatePerKM FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Batta' AND @DISTANCE>=FromRange)+(SELECT OtherAmt FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Batta' AND @DISTANCE>=FromRange)  
         SET @AMT=@AMT+@BattaAMT   
      END  
    END  
   --CALCULATE THE BATTA AMOUNT FOR MMV DRIVERS      
   ELSE IF(@vcVehicleType='MMV')  
    BEGIN  
     IF(@DISTANCE>=200 AND @DISTANCE<=600)  
      BEGIN  
       SET @BattaAMT=@BattaAMT+@DISTANCE* (SELECT RatePerKM FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Batta' AND @DISTANCE>=FromRange AND @DISTANCE <=ToRange)  
       SET @AMT=@AMT+@BattaAMT    
      END  
     ELSE IF(@DISTANCE>=600)  
      BEGIN  
       SET @BattaAMT=@BattaAMT+@DISTANCE* (SELECT RatePerKM FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Batta' AND @DISTANCE>=FromRange)+(SELECT OtherAmt FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Batta' AND @DISTANCE>=FromRange)  
       SET @AMT=@AMT+@BattaAMT   
      END  
    END  
   --CALCULATE THE BATTA AMOUNT FOR LMV DRIVERS      
   ELSE IF(@vcVehicleType='LMV')  
    BEGIN  
     IF(@DISTANCE>=200)  
      BEGIN  
       SET @BattaAMT=@BattaAMT+@DISTANCE* (SELECT RatePerKM FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='Batta' AND @DISTANCE>=FromRange)  
       SET @AMT=@AMT+@BattaAMT   
      END  
     IF(@vcVehicleType='LMV' AND @bitIsTeamVeh=1)  
      BEGIN  
       SET @TeamAMT=@TeamAMT+(SELECT OtherAmt FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='TeamVehicle')  
       SET @AMT=@AMT+@BattaAMT   
      END  
     ELSE IF(@vcVehicleType='LMV' AND @bitIsNightHalt=1 AND @bitIsTeamVeh=0)  
      BEGIN  
       SET @NightAMT =@NightAMT+(SELECT OtherAmt FROM rvlfDriverBattaDetails WHERE VehicleType=@vcVehicleType   
           AND Description='NightHalt')  
      END  
    END  
  END   
    
  SELECT DM.DisplayName as DriverName,DM1.DisplayName as DriverName1,DM.MobileNo,DM1.MobileNo as MobileNo1,  
    DM.LicenseNo,DM1.LicenseNo as LicenseNo1,V.DisplayName as VehName,V.Category,V.LicensePlate,  
    DA.AssignmentDate,l.LandmarkName as FromPlace,l1.LandmarkName as ToPlace,    
    @dtFromDateTime as StartTime,@dtToDateTime as EndTime,'trip via' AS TripVia,  
    @bigOdometerStart as Odostart, @bigOdometerEnd as OdoEnd,@DISTANCE as TotalDistance,  
    @DayAMT as DayAMT,@NightAMT as NightAMT,(@BREAKFAST+@LUNCH) as FoodAMT,@LocalTripAMT as LocalTripAMT,  
    @TeamAMT as TeamAMT,@BattaAMT as BattaAMT,(@HELPERAMt+@NIGHTDUTYAMt) as others,@AMT as TotalAmt,  
    @bigDriverId AS DriverId,@bigVehicleId as VehicleId,@vcVehicleType as VehicleType      
   FROM rvlfDriverAssignment DA  
    INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId   
    LEFT OUTER JOIN rvlfDriverMaster DM1 ON DM1.DriverId=@BIGSECONDDRIVERID   
    INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =DA.BOXID   
    INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId   
    LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=DA.FromLandmarkId   
    LEFT OUTER JOIN rvlfLandmark L1 ON L1.LandmarkID=DA.ToLandmarkId    
   WHERE AssignmentId=@bigTripId   
END  


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverTripSummary]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetDriverTripSummary]
	@bigFleetID bigint = null,
	@intBoxID int = null,
	@dtStartDate datetime = NULL,
	@dtEndDate datetime = NULL,
	@bigOrganizationID bigint = NULL,
	@bigQueryingUser bigint = NULL,
	@bigDriverID bigint = NULL,
	@vcDrivers varchar(100) = null
AS
--/******************************************************************************/
----	Name		:	rvlf_sp_GetDriverTripSummary 8,NULL, '2010-11-08', '2010-11-10', 6,62, null
----	Description	:	To get the trip summary details or Driver
----				:   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin
----	Author		:	M. Jebamalai Jaya Chitra.
----	Company		:	Angler Technologies
----	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
----				:	29-Jun-2010	MJJC	Created Intial Version 
----				:	05-Jul-2010	MJJC	Changed the script for getting the driver assignment dates
----				:	
--/******************************************************************************/

BEGIN
	
	SET NOCOUNT ON		
	IF @bigFleetID IS NULL
		BEGIN
			SELECT @bigFleetID=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 = @bigQueryingUser
	
	SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))
	SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))
	
	DECLARE @tblDriverTrips TABLE(
		[DriverTripId] [bigint] Identity(1,1) NOT NULL,
		[BoxId] [int] NOT NULL,
		[AssignedFrom] [datetime] NOT NULL,
		[AssignedTo] [datetime] NULL,
		[OdometerStart] [bigint] NOT NULL,
		[OdometerEnd] [bigint] NULL,
		[IsTripClosed] [bit] NULL,
		[IdlingDuration] [int] NULL,
		[StopTime] [int] NULL,
		[StartAddress] varchar(300) NULL,
		[EndAddress] varchar(300) NULL,
		[DriverID] [bigint] NULL,
		Speed int		NULL,
		VehicleID bigint,
		VehDisplayName varchar(50)
	)

	DECLARE @intDuration int
	DECLARE @dtOriginDateTime datetime
	DECLARE @bigOdoMeterReading int
	DECLARE @bitIgnitionStatus bit
	DECLARE @vcStreetAddress varchar(250)
	DECLARE @tiBoxMsgInTypeId tinyint
	DECLARE @bigTripID bigint
	DECLARE @intIterator int
	DECLARE @canShowFuelMessage bit = 0
	DECLARE @tiSensorNo tinyint
	
	IF EXISTS (SELECT * FROM rvlfPackageOperations r
		INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId
		INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId
		WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)
			BEGIN
				SET @canShowFuelMessage = 1
			END
	
	--CHECK IF THE DRIVER HAVE IBUTTON
	IF EXISTS(SELECT MessageInID FROM rvlfMsgInHst M
				INNER JOIN rvlfDriverMaster DM ON DM.DriverId =CASE WHEN CustomProp LIKE '%MAPID=%' 
					THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))ELSE 0  END
				INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =M.BoxId 
				INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId 	
				WHERE (V.OrganizationId = @bigOrganizationID)
					AND(DM.OrganizationID =@bigOrganizationID) 
					AND OriginDateTime BETWEEN @dtStartDate and @dtEndDate
					AND (@intBoxID is null OR M.BoxId = @intBoxID)
					AND BoxMsgInTypeId=76
					AND	(@bigDriverID IS NULL OR DM.DriverId  = @bigDriverID)	
					AND (@vcDrivers IS NULL OR DM.DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDrivers,',')))
					AND (CASE WHEN CustomProp LIKE '%Driver Status=%' 
						THEN SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,
						(CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,1))-(CHARINDEX('Driver Status=',CustomProp,1)+14))) ELSE 'NI' END)='IN')
		BEGIN
			INSERT INTO @tblDriverTrips 
				(DriverID, VehicleID, AssignedFrom, AssignedTo, VehDisplayName, BoxId,StartAddress,OdometerStart,speed)
			SELECT DriverId,V.VehicleId,M.OriginDateTime,NULL,V.VehicleDescription,M.BoxId,M.StreetAddress,
			CASE WHEN CustomProp LIKE '%Odometer=%' THEN SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END,
			M.Speed 
			FROM rvlfMsgInHst M
				INNER JOIN rvlfDriverMaster DM ON DM.DriverId =CASE WHEN CustomProp LIKE '%MAPID=%' 
					THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))ELSE 0  END
				INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =M.BoxId 
				INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId 	
				WHERE (V.OrganizationId = @bigOrganizationID)
					AND(DM.OrganizationID =@bigOrganizationID) 
					AND OriginDateTime BETWEEN @dtStartDate and @dtEndDate
					AND (@intBoxID is null OR M.BoxId = @intBoxID)
					AND BoxMsgInTypeId=76
					AND	(@bigDriverID IS NULL OR CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) AS BIGINT) ELSE 0 END = @bigDriverID)	
					AND (@vcDrivers IS NULL OR CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) AS BIGINT) ELSE 0 END IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDrivers,',')))	 
					AND (CASE WHEN CustomProp LIKE '%Driver Status=%' 
						THEN SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,
						(CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,1))-(CHARINDEX('Driver Status=',CustomProp,1)+14))) ELSE 'NI' END)='IN'
				
			DECLARE @bigBehaviourLoop bigint=null
			SELECT @bigBehaviourLoop=MIN(DriverTripId) FROM @tblDriverTrips						
			WHILE @bigBehaviourLoop IS NOT NULL
				BEGIN
					DECLARE @bigDriver bigint=null,@dtStart datetime =null,@dtEnd datetime=null,@bitTripClosed bit=1,
						@intBoxidLoop int=null,@vcEndAddress varchar(200)=null,@intIdling int=null,@bigOdoEnd bigint=null,
						@tintSpeed tinyint=null
					SELECT @bigDriver=DriverID,@dtStart =AssignedFrom,@intBoxidLoop=BoxId  FROM @tblDriverTrips WHERE DriverTripId=@bigBehaviourLoop AND AssignedTo IS NULL
					
					--GET THE PUNCH OUT TIME					
				 	 SELECT TOP 1 @dtEnd=OriginDateTime,@vcEndAddress=StreetAddress,
				 		@bigOdoEnd=(CASE WHEN CustomProp LIKE '%Odometer=%' THEN SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END),
				 		@tintSpeed=Speed
						FROM rvlfMsgInHst 
							WHERE BoxId =@intBoxidLoop
								AND OriginDateTime >@dtStart
								AND	OriginDateTime <= @dtEndDate
								AND BoxMsgInTypeId =76
								AND	(CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp)) AS BIGINT) ELSE 0 END = @bigDriver)		 
								AND (CASE WHEN CustomProp LIKE '%Driver Status=%' 
									THEN SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,
									(CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,1))-(CHARINDEX('Driver Status=',CustomProp,1)+14))) ELSE 'NI' END)='OUT'
								ORDER BY OriginDateTime 
					IF(@dtEnd IS NULL OR @dtEnd ='')
						BEGIN
							SET @bitTripClosed =0
							SET @dtEnd =@dtEndDate 
							SELECT TOP 1 @bigOdoEnd=(CASE WHEN CustomProp LIKE '%Odometer=%' THEN SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END)
							FROM rvlfMsgInHst WHERE BoxId =@intBoxidLoop AND OriginDateTime<=@dtEnd AND CustomProp LIKE '%Odometer=%' ORDER BY OriginDateTime DESC
						END
					SET @intIdling=(SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)as int)),0)
								FROM rvlfMsgInHst  
								WHERE BoxMsgInTypeId=9 AND BoxId=@intBoxidLoop 
									AND OriginDateTime BETWEEN @dtStart and @dtEnd
									GROUP BY BoxId)
					UPDATE @tblDriverTrips SET AssignedTo =@dtEnd,EndAddress=@vcEndAddress,IdlingDuration=@intIdling,IsTripClosed=@bitTripClosed,
						OdometerEnd=@bigOdoEnd,Speed =@tintSpeed,StopTime=DATEDIFF(S,@dtEnd,(SELECT AssignedFrom FROM @tblDriverTrips WHERE DriverTripId=(@bigBehaviourLoop+1)))    					
					WHERE DriverID=@bigDriver AND AssignedFrom =@dtStart AND BoxId=@intBoxidLoop AND AssignedTo IS NULL
					
					SELECT @bigBehaviourLoop =MIN(DriverTripId) FROM @tblDriverTrips WHERE DriverTripId > @bigBehaviourLoop 								
				END												
		END				
	ELSE
		BEGIN			
			INSERT INTO @tblDriverTrips 
				(DriverID, VehicleID, AssignedFrom, AssignedTo, VehDisplayName, BoxId,StartAddress,OdometerStart,speed)
				SELECT DriverId,V.VehicleId,da.FromTime,da.ToTime,V.VehicleDescription,M.BoxId,M.StreetAddress,
					CASE WHEN CustomProp LIKE '%Odometer=%' THEN SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END,
					M.Speed FROM rvlfDriverAssignment da 
						INNER JOIN rvlfVehicleAssignment va ON DA.BOXID = va.BoxId 
						INNER JOIN rvlfVehicle v ON v.VehicleId = Va.VehicleId						
						INNER JOIN rvlfMsgInHst M ON M.BoxId=VA.BoxId 
					WHERE (@bigDriverID IS NULL OR da.DriverId = @bigDriverID)
						AND OrganizationId = @bigOrganizationID 
						AND (da.FromTime Between @dtStartDate and @dtEndDate)
						AND (M.OriginDateTime BETWEEN @dtStartDate and @dtEndDate)
						AND (@intBoxID is null OR M.BoxId = @intBoxID)
						--AND da.AssignmentID = 10
						ORDER by da.FromTime asc
						
				WHILE @bigBehaviourLoop IS NOT NULL
				BEGIN
					SET @bigDriver=null;SET @dtStart=null;SET @dtEnd=null;SET @bitTripClosed=1;
						SET @intBoxidLoop=NULL;SET @vcEndAddress=null;SET @intIdling =null;SET @bigOdoEnd =null;
						SET @tintSpeed =null
					SELECT @bigDriver=DriverID,@dtStart =AssignedFrom,@intBoxidLoop=BoxId,@dtEnd=AssignedTo   FROM @tblDriverTrips WHERE DriverTripId=@bigBehaviourLoop AND AssignedTo IS NULL
					
					IF(@dtEnd IS NULL OR @dtEnd ='')
						BEGIN
							SET @bitTripClosed =0
							SET @dtEnd =@dtEndDate 
						END
					--GET THE PUNCH OUT TIME					
				 	 SELECT TOP 1 @vcEndAddress=StreetAddress,
				 		@bigOdoEnd=(CASE WHEN CustomProp LIKE '%Odometer=%' THEN SUBSTRING(CustomProp,CHARINDEX('Odometer=',CustomProp,0)+9,(CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,0))-(CHARINDEX('Odometer=',CustomProp,0)+9))) ELSE 0 END),
				 		@tintSpeed=Speed
						FROM rvlfMsgInHst 
							WHERE BoxId =@intBoxidLoop
								AND OriginDateTime >@dtStart
								AND	OriginDateTime <= @dtEnd								
								ORDER BY OriginDateTime DESC 
					
					SET @intIdling=(SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)as int)),0)
								FROM rvlfMsgInHst  
								WHERE BoxMsgInTypeId=9 AND BoxId=@intBoxidLoop 
									AND OriginDateTime BETWEEN @dtStart and @dtEnd
									GROUP BY BoxId)
					UPDATE @tblDriverTrips SET AssignedTo =@dtEnd,EndAddress=@vcEndAddress,IdlingDuration=@intIdling,IsTripClosed=@bitTripClosed,
						OdometerEnd=@bigOdoEnd,Speed =@tintSpeed,StopTime=DATEDIFF(S,@dtEnd,(SELECT AssignedFrom FROM @tblDriverTrips WHERE DriverTripId=(@bigBehaviourLoop+1)))    					
					WHERE DriverID=@bigDriver AND AssignedFrom =@dtStart AND BoxId=@intBoxidLoop AND AssignedTo IS NULL
					
					SELECT @bigBehaviourLoop =MIN(DriverTripId) FROM @tblDriverTrips WHERE DriverTripId > @bigBehaviourLoop 								
				END								
						
		END
			
		UPDATE @tblDriverTrips SET StopTime = DATEDIFF(ss, AssignedTo, @dtEndDate) WHERE DriverTripId =(SELECT MAX(DriverTripId) FROM @tblDriverTrips)		

		SELECT TripId,A.BoxId,Speed,StartDate,EndDate,TripStatus,Duration,TripDuration,TripDurationhrs,DriverID,
		case when Cast(IsNull(OdometerEnd,0) as Int) < Cast(IsNull(OdometerStart,0) as int) Then 0 
		else Cast((Cast(IsNull(OdometerEnd,0) as Int)- Cast(IsNull(OdometerStart,0) as int)) as nvarchar(20)) END Distance,	
		StartAddress,EndAddress,VIN,LicensePlate,VehicleDescription,MakeName,ModelName,ModelYear,
		IdlingTime,IdlingDuration,StopDuration,StopTime,DistanceCaption,SpeedCaption,DriverName,
		LicenseNo,MobileNo,OdometerStart,OdometerEnd,OdometerStartReading,OdometerEndReading,
		case when Cast(OdometerEndReading as Int) < Cast(OdometerStartReading as int) Then 0 
		ELSE ROUND(OdometerEndReading-OdometerStartReading,0,0) END DistanceSummary
		FROM 
		(
		SELECT t.DriverTripId as TripId,t.BoxId, Speed,DateAdd(MINUTE,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,AssignedFrom)) as StartDate,
			CASE WHEN T.IsTripClosed =0 THEN DateAdd(MINUTE,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,GETUTCDATE())) ELSE DateAdd(MINUTE,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,t.AssignedTo)) END as EndDate,
			CASE WHEN IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,
			dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,AssignedFrom,AssignedTo)) as Duration,
		 	ABS(DateDiff(SS,AssignedFrom,AssignedTo)) as TripDuration,(ABS(DateDiff(SS,AssignedFrom,AssignedTo))/3600) as TripDurationhrs, t.DriverId,
			CAST(CAST((ABS(t.OdometerEnd - t.OdometerStart)*@ConversionFactor) AS numeric(7,2)) as varchar(20)) as Distance,			
			StartAddress, CASE WHEN IsTripClosed = 0 THEN 'Ongoing' ELSE EndAddress  END AS EndAddress,
			dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(IdlingDuration,0)) AS IdlingTime, IdlingDuration,
			NULL AS StopDuration,
			NULL AS StopTime,
			@DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,
			d.DisplayName as DriverName, d.LicenseNo, d.MobileNo, 
			CEILING(CAST (t.OdometerStart*@ConversionFactor as numeric(9,2)))as OdometerStart, 
			CEILING(CAST (t.OdometerEnd*@ConversionFactor as numeric(9,2)))as OdometerEnd,
			(SELECT TOP 1 CEILING(CAST (tt.OdometerStart*@ConversionFactor as numeric(9,2))) FROM @tblDriverTrips tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerStart ASC) As OdometerStartReading, 
			(SELECT TOP 1 CEILING(CAST(tt.OdometerEnd * @ConversionFactor as numeric(9,2)))  FROM @tblDriverTrips tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerEnd DESC) AS OdometerEndReading	
		FROM @tblDriverTrips t INNER JOIN rvlfdriverMaster d ON t.DriverID = d.DriverID --order by DriverId 
		) A
		INNER JOIN rvlfVehicleAssignment va ON A.BoxId = va.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId
		LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId
		
		    
	    SELECT DriverName, Round(CAST(Distance as numeric),0)Distance
	    FROM
	    (
			SELECT DriverName, CAST((MAX(OdometerEnd)-MIN(OdometerStart))* @ConversionFactor as varchar(20))Distance
			FROM @tblDriverTrips t
			INNER JOIN rvlfdriverMaster D on D.DriverId=t.DriverId
			Group By DriverName
		)B
		WHERE CAST(Distance AS numeric(9,2)) > 0	 
			
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverTripSummary_Opt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
            
CREATE  PROCEDURE [dbo].[rvlf_sp_GetDriverTripSummary_Opt]              
 @bigFleetID bigint = null,              
 @intBoxID varchar(max) = NULL,              
 @dtStartDate datetime = null,              
 @dtEndDate datetime = null,              
 @bigOrganizationID bigint = null,              
 @bigQueryingUser bigint = null,              
 @bigDriverID bigint = NULL,              
 @bigDriverGroupId bigint= null              
AS                        
--/*************************************************************************************************************************/              
---- Name   : [rvlf_sp_GetDriverTripSummary_Opt] 519,'4479','2015-06-01 08:00:00 AM','2015-06-02 10:00:00 PM',257,502,null,null               
---- Description : To get the trip summary details or Driver              
---- Author   : V.Narayanasamy              
---- Company  : Angler Technologies              
---- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
----    : 22-Feb-2011 VN Created Intial Version               
----             : 10-Aug-2011 Ranjith Date format Included              
--/*************************************************************************************************************************/              
              
BEGIN              
 Declare @dtFDate datetime =@dtStartDate              
 Declare @dtEDate datetime =@dtEndDate              
               
 IF @bigFleetID IS NULL              
  BEGIN              
   SELECT @bigFleetID=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)              
 DECLARE @DefaultDateFormat INT = 0              
    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,              
     @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 = @bigQueryingUser              
               
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))              
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))              
               
 --GET THE BOXIDS FOR THE FLEET              
 DECLARE @vcBoxIds VARCHAR(MAX)=NULL              
  SELECT @vcBoxIds=COALESCE(@vcBoxIds,'')+CONVERT(VARCHAR,VA.BoxId)+',' FROM rvlfFleetVehicles FV               
   INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=FV.VehicleId               
  WHERE FV.FleetId=@bigFleetID AND (@intBoxID IS NULL OR @intBoxID='0' OR @intBoxID='' OR VA.BOXID in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))               
 -------------------------------------              
               
 --GET THE DRIVERS FOR THE ORGANIZATION              
 DECLARE @vcDriverIds VARCHAR(MAX)=NULL              
  SELECT @vcDriverIds=COALESCE(@vcDriverIds,'')+CONVERT(VARCHAR,DM.DriverId)+','  FROM rvlfDriverMaster DM              
    LEFT OUTER JOIN rvlfDriverGroupAssignment DG ON DG.DriverId=DM.DriverId               
   WHERE OrganizationID=@bigOrganizationID               
    AND (@bigDriverID IS NULL OR @bigDriverID='' OR DM.DriverId=@bigDriverID)               
    AND (@bigDriverGroupId IS NULL OR @bigDriverGroupId='' OR DG.DriverGroupId=@bigDriverGroupId)              
                  
 --GET THE DRIVER TRIPS              
 DECLARE @tblDriverTrips TABLE              
 (              
  ProcessId bigint identity(1,1),              
  Boxid int null,              
  DriverId bigint null,              
  TripTime datetime null,              
  TripStatus varchar(5)null,              
  Customprop varchar(600) null,             
  BoxmsgTypeId tinyint null,              
  Speed int null,              
  StreetAddress varchar(300) null,  
  Odometer bigint null             
 )                  
               
 --GET THE FIRST PUNCH DETAILS FROM DRIVER ASSIGNMENT              
 DECLARE @DTFIRSTPUNCH DATETIME =NULL,@bitIsIbutton bit=null,@bitIsRFID bit=null              
 SELECT TOP 1 @DTFIRSTPUNCH=PunchIn FROM rvlfDriverAssignment               
  WHERE BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))              
   AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))               
   AND PunchIn IS NOT NULL AND PunchOut IS NOT NULL             
   AND PunchIn BETWEEN @dtStartDate  AND @dtEndDate             
  ORDER BY PunchIn               
                
 --CHECK IF THE PUNCH IS BEFORE THE STATDATEANDTIME                
 IF(@DTFIRSTPUNCH IS NOT NULL AND @DTFIRSTPUNCH<@dtStartDate)              
 BEGIN SET @DTFIRSTPUNCH=@dtStartDate END              
 ELSE IF (@DTFIRSTPUNCH IS NULL) BEGIN SET @DTFIRSTPUNCH=@dtStartDate END              
                
 --GET THE IBUTTON RIGHTS FOR THE ORGANIZATION              
 SELECT @bitIsIbutton= CASE WHEN PO.PackageId IS NULL OR PO.PackageId ='' THEN 0 ELSE 1 END               
  FROM rvlfPackageOperations PO              
   INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId               
  WHERE OperationID =147 AND IsActive =1 AND OrganizationID=@bigOrganizationID               
               
 IF (@bitIsIbutton=1)              
  BEGIN              
   INSERT INTO @tblDriverTrips (Boxid,DriverId,TripTime,TripStatus)              
    SELECT BoxId,CASE WHEN CustomProp LIKE'%MAPID=%' THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,              
      (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))) ELSE 0 END,OriginDateTime,              
      SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,0)+14,              
    (CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,0))-(CHARINDEX('Driver Status=',CustomProp,0)+14)))              
     FROM rvlfMsgInHst               
      WHERE BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))              
       AND BoxMsgInTypeId =76              
       AND SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,              
        (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))) IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))              
       AND CustomProp LIKE'%Driver Status=%' AND CustomProp LIKE '%MAPID=%'                    
       --AND OriginDateTime BETWEEN @dtStartDate AND CASE WHEN @DTFIRSTPUNCH IS NOT NULL THEN CASE WHEN @DTFIRSTPUNCH BETWEEN @dtStartDate AND @dtEndDate THEN @DTFIRSTPUNCH ELSE @dtEndDate END ELSE @dtEndDate END                     
       AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                      
       AND BoxMsgInTypeId IN(SELECT DISTINCT MT.BoxMsgInTypeId  FROM rvlfUserGroupSecurity UGS               
        INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId               
        INNER JOIN rvlfBoxMsgInType MT ON MT.OperationTypeID=UGS.OperationTypeId               
       WHERE UGA.UserId=@bigQueryingUser)              
      ORDER BY BoxId, SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,              
        (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))),OriginDateTime              
  END              
              
 SELECT  @bitIsRFID = CASE WHEN PO.OperationID=188 AND (PO.PackageId IS NULL OR PO.PackageId ='') THEN 0 WHEN PO.OperationID=188 THEN 1  END  FROM rvlfPackageOperations PO INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId                
  
   
 WHERE OperationID IN (188) AND IsActive =1 AND OrganizationID=@bigOrganizationID         
          
 IF (@bitIsRFID =1) --RFID 29-may15         
  BEGIN            
   INSERT INTO @tblDriverTrips (Boxid,DriverId,TripTime,TripStatus)          
   SELECT h.BoxId,DM.DriverId,h.OriginDateTime,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Punch:',';')          
   FROM rvlfMsgInHst h           
   INNER JOIN rvlfIButtonMapping BM ON (IButtonKey=dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'RF_ID=',';')) AND BM.KeyType=3         
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=BM.DriverId            
   WHERE h.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))            
   AND ((h.BoxMsgInTypeId=100 AND h.CustomProp like '%RF_ID=%') )            
   AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate              
   AND BoxMsgInTypeId IN(100) AND DM.DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))         
   ORDER BY h.BoxId,h.MessageInID,DM.DriverId,h.OriginDateTime              
  END        
        
 --GET THE TRIPS              
 DECLARE @tblDriverTripDetails TABLE              
 (                
  TripId bigint identity(1,1),              
  Boxid int null,              
  DriverId bigint null,              
  StartTime datetime null,              
  EndTime datetime null,              
  TripInStatus varchar(5) null,              
  TripOutStatus varchar(5) null,              
  RunningTime int null,              
  IdlingTime int null,              
  Speed int null,              
  OdoStart bigint null,              
  OdoEnd bigint null,              
  StartAddress varchar(300) null,              
  EndAddress varchar(300) null              
 )               
 INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)              
 SELECT MT.Boxid,MT.DriverId,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus              
   FROM @tblDriverTrips AS MT               
    LEFT OUTER JOIN @tblDriverTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'IN' and MT.DriverId=ST.DriverId and MT.TripStatus='OUT'                    
                
 --DELETE THE INVALID TRIPS                
 DELETE FROM @tblDriverTripDetails WHERE StartTime IS NULL --OR TripInStatus=TripOutStatus               
               
 --GET THE MANUEL AND AUTOMATIC SCHEDULES              
 IF(@DTFIRSTPUNCH IS NOT NULL)              
  BEGIN              
   INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)              
   SELECT BoxId,DriverId,CASE WHEN PunchOut IS NULL THEN ToTime ELSE PunchOut END,'OUT',              
    CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END,'IN'                
    FROM rvlfDriverAssignment                
    WHERE @DTFIRSTPUNCH BETWEEN (CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END)              
    AND (CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END)              
        --@DTFIRSTPUNCH <= CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END               
     --AND @dtEndDate >= CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END              
     AND BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))              
     AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))               
  END              
 ELSE              
  BEGIN              
   INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)              
   SELECT BoxId,DriverId,CASE WHEN PunchOut IS NULL THEN ToTime ELSE PunchOut END,'OUT',              
    CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END,'IN'                
    FROM rvlfDriverAssignment                
     WHERE @dtStartDate BETWEEN (CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END)              
     AND (CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END)              
     --@dtStartDate <= CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END               
     --AND @dtEndDate >= CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END              
      AND BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))              
      AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))               
  END              
 --SELECT @dtStartDate,@dtEndDate,@DTFIRSTPUNCH,* FROM @tblDriverTripDetails                 
 --GET THE TRIP DETAILS              
 DECLARE @bigTripid bigint=null              
 SELECT @bigTripid = MIN(TripId) FROM @tblDriverTripDetails                
 WHILE (@bigTripid IS NOT NULL)              
  BEGIN              
   DECLARE @dtTripStart datetime=null,@dtTripEnd datetime=null              
   SET @intBoxID=NULL              
   SELECT @intBoxID=Boxid,@dtTripStart =StartTime,@dtTripEnd=EndTime FROM @tblDriverTripDetails WHERE TripId=@bigTripid               
   DELETE FROM @tblDriverTrips               
   INSERT INTO @tblDriverTrips (BoxmsgTypeId,Customprop,Speed,TripTime,StreetAddress,Odometer)              
    SELECT BoxMsgInTypeId,CustomProp,Speed,OriginDateTime,              
    CASE WHEN (H.LandMarkID IS NULL OR H.LandMarkID = 0) THEN               
       REPLACE(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''') ELSE L.LandmarkName END ,H.Odometer               
    FROM rvlfMsgInHst H              
     LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID                
    WHERE BoxId=@intBoxID AND OriginDateTime BETWEEN @dtTripStart AND @dtTripEnd               
     AND BoxMsgInTypeId IN(SELECT DISTINCT MT.BoxMsgInTypeId  FROM rvlfUserGroupSecurity UGS               
        INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId               
        INNER JOIN rvlfBoxMsgInType MT ON MT.OperationTypeID=UGS.OperationTypeId               
       WHERE UGA.UserId=@bigQueryingUser)ORDER BY OriginDateTime               
                 
   UPDATE @tblDriverTripDetails SET Speed=(SELECT ISNULL(MAX(Speed),0) FROM @tblDriverTrips WHERE Speed!=0 AND Speed IS NOT NULL),              
    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 @tblDriverTrips  WHERE BoxmsgTypeId =9 AND CustomProp NOT LIKE '%Idling:0;%'),              
    RunningTime=(SELECT ISNULL(SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,              
        (CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60,0)                           
        FROM @tblDriverTrips  WHERE BoxmsgTypeId =3 AND Customprop NOT LIKE '%SENSOR_DURATION=0;%'),              
    OdoStart=(SELECT TOP 1 min(Odometer) from @tblDriverTrips where Odometer >0 ),              
    OdoEnd=(SELECT TOP 1 max(Odometer) from @tblDriverTrips where Odometer >0 ),              
    StartAddress =(SELECT TOP 1 StreetAddress  FROM @tblDriverTrips ORDER BY TripTime),              
    EndAddress =(SELECT TOP 1 StreetAddress  FROM @tblDriverTrips  ORDER BY TripTime DESC)                                       
   WHERE TripId=@bigTripid               
                   
   --DECLARE @DTIDLINGEND DATETIME =NULL,@DTIDLINGSTART DATETIME =NULL              
   --SELECT @DTIDLINGEND= CASE WHEN (SELECT TOP 1 Customprop FROM @tblDriverTrips WHERE BoxId=@intBoxID               
   --  AND TripTime BETWEEN @dtTripStart AND @dtTripEnd              
   --  AND BoxmsgTypeId  =9 ORDER BY TripTime) NOT LIKE '%Idling:0;%' THEN               
   --   (SELECT TOP 1 TripTime FROM @tblDriverTrips WHERE BoxId=@intBoxID               
   --  AND TripTime BETWEEN @dtTripStart AND @dtTripEnd              
   --  AND BoxmsgTypeId =9 AND CustomProp NOT LIKE '%Idling:0;%' ORDER BY TripTime) ELSE @dtTripStart END              
              
   --SELECT @DTIDLINGSTART= CASE WHEN (SELECT TOP 1 CustomProp FROM @tblDriverTrips WHERE BoxId=@intBoxID               
   --  AND TripTime BETWEEN @dtTripStart AND @dtTripEnd              
   --  AND BoxmsgTypeId =9 ORDER BY TripTime DESC)  LIKE '%Idling:0;%' THEN               
   --   (SELECT TOP 1 TripTime FROM @tblDriverTrips WHERE BoxId=@intBoxID               
   --  AND TripTime BETWEEN @dtTripStart AND @dtTripEnd              
   --  AND BoxmsgTypeId =9 AND CustomProp LIKE '%Idling:0;%' ORDER BY TripTime DESC) ELSE @dtTripEnd END              
                       
   --UPDATE @tblDriverTripDetails               
   -- SET IdlingTime=(ISNULL((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 @tblDriverTrips  WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd               
   --      AND DriverId=@bigDriverID AND BoxmsgTypeId =9 AND CustomProp NOT LIKE '%Idling:0;%'              
   --      AND TripTime > @DTIDLINGEND AND TripTime< @DTIDLINGSTART),0)+(DATEDIFF (S,@dtTripStart,@DTIDLINGEND))+(DATEDIFF (S,@DTIDLINGSTART,@dtTripEnd)))                 
   --WHERE TripId=@bigTripid               
                 
   SELECT @bigTripid =MIN(TripId) FROM @tblDriverTripDetails WHERE TripId >@bigTripid                   
  END              
  
--select 'A',* from @tblDriverTripDetails   
           
  --IF THE IDLING TIME IS EXCEED TO RUNNING TIME              
  UPDATE @tblDriverTripDetails SET RunningTime=IdlingTime WHERE IdlingTime>RunningTime               
 --GET THE SUMMARY DETAILS               
 DECLARE @tblSummary TABLE              
 (              
  Boxid int null,              
  DriverId bigint null,              
  TotDistance int null,              
  TotShiftDuration int null,              
  TotRunning int null,              
  TotIdling int null              
 )               
 INSERT INTO @tblSummary (Boxid,DriverId,TotDistance,TotIdling,TotRunning,TotShiftDuration)              
  SELECT Boxid,DriverId,SUM((OdoEnd-OdoStart)),SUM(IdlingTime),SUM(RunningTime),SUM(DATEDIFF(S,StartTime,EndTime))   FROM @tblDriverTripDetails GROUP BY Boxid,DriverId               
              
 --GET THE RESULT SET               
 SELECT distinct TD.Boxid,TD.DriverId,V.VehicleId, DM.DisplayName AS DriverName,DM.LicenseNo,DM.MobileNo,V.VehicleDescription,V.LicensePlate,V.Vin,              
  CASE WHEN S.TotShiftDuration IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(S.TotShiftDuration) END AS TotShiftDuration,              
  ISNULL(S.TotDistance,'-') AS TotDistance,              
  CASE WHEN S.TotRunning IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(S.TotRunning) END AS TotRunning,              
  CASE WHEN S.TotIdling IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(S.TotIdling) END AS TotIdling,              
  StartDate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,TD.StartTime),              
  --Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.StartTime)),@DefaultDateFormat) + ' ' + Convert(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.StartTime)) as Time),22) AS StartDate,           
   
  TD.StartTime AS StartDateSort,              
  EndDate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,TD.EndTime),              
  --Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.EndTime)),@DefaultDateFormat) + ' '+ Convert(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.EndTime)) as time),22) AS EndDate,              
  ISNULL(TD.StartAddress,'N/A') AS StartAddress ,ISNULL(TD.EndAddress,'N/A') AS EndAddress,dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(S,StartTime,EndTime))AS ShiftDuration,              
  ISNULL(OdoEnd-OdoStart,'-')AS Distance,              
  CASE WHEN TD.RunningTime IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(TD.RunningTime) END AS RunningTime,              
  CASE WHEN TD.IdlingTime IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(TD.IdlingTime) END AS IdlingTime,              
  Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,              
  PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())              
  --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate       
   
          
  FROM @tblDriverTripDetails TD              
   INNER JOIN @tblSummary S ON S.DriverId=TD.DriverId AND S.Boxid =TD.Boxid                
   INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =TD.Boxid               
   INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId               
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=TD.DriverId                
                 
--select * from @tblDriverTrips               
--select * from @tblDriverTripDetails               
                     
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetDriverTripSummary_Opt_test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--rvlf_sp_GetDriverTripSummary_Opt
--rvlf_sp_GetDriverBehaviour_Opt
--rvlf_sp_GetDriverBehaviour_RAG
--rvlf_sp_GetDriverTripDetails_Opt_test
 
 
-- select * from rvlfvehicle where vehicledescription like '%81045%'
-- select * from rvlfVehicleAssignment where VehicleId=2439
 
-- select * from rvlfMsgInHst where BoxId=4480 and dateadd(MINUTE,330,OriginDateTime) between '02-jun-2015 6:50 PM' and '03-jun-2015 7:23 AM'
 
              
CREATE  PROCEDURE [dbo].[rvlf_sp_GetDriverTripSummary_Opt_test]                
 @bigFleetID bigint = null,                
 @intBoxID varchar(max) = NULL,                
 @dtStartDate datetime = null,                
 @dtEndDate datetime = null,                
 @bigOrganizationID bigint = null,                
 @bigQueryingUser bigint = null,                
 @bigDriverID bigint = NULL,                
 @bigDriverGroupId bigint= null                
AS                          
--/*************************************************************************************************************************/                
---- Name   : [rvlf_sp_GetDriverTripSummary_Opt_test] 519,'4480','02-jun-2015 6:50 PM','03-jun-2015 7:23 AM',257,502,null,null  
---- Description : To get the trip summary details or Driver                
---- Author   : V.Narayanasamy                
---- Company  : Angler Technologies                
---- History  : <<Date(dd-MON-yyyy)>> Initial Reason                
----    : 22-Feb-2011 VN Created Intial Version                 
----             : 10-Aug-2011 Ranjith Date format Included                
--/*************************************************************************************************************************/                
                
BEGIN                
 Declare @dtFDate datetime =@dtStartDate                
 Declare @dtEDate datetime =@dtEndDate                
                 
 IF @bigFleetID IS NULL                
  BEGIN                
   SELECT @bigFleetID=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)                
 DECLARE @DefaultDateFormat INT = 0                
    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,                
     @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 = @bigQueryingUser                
                 
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                
                 
 --GET THE BOXIDS FOR THE FLEET                
 DECLARE @vcBoxIds VARCHAR(MAX)=NULL                
  SELECT @vcBoxIds=COALESCE(@vcBoxIds,'')+CONVERT(VARCHAR,VA.BoxId)+',' FROM rvlfFleetVehicles FV                 
   INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=FV.VehicleId                 
  WHERE FV.FleetId=@bigFleetID AND (@intBoxID IS NULL OR @intBoxID='0' OR @intBoxID='' OR VA.BOXID in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                 
 -------------------------------------                
                 
 --GET THE DRIVERS FOR THE ORGANIZATION                
 DECLARE @vcDriverIds VARCHAR(MAX)=NULL                
  SELECT @vcDriverIds=COALESCE(@vcDriverIds,'')+CONVERT(VARCHAR,DM.DriverId)+','  FROM rvlfDriverMaster DM                
    LEFT OUTER JOIN rvlfDriverGroupAssignment DG ON DG.DriverId=DM.DriverId                 
   WHERE OrganizationID=@bigOrganizationID                 
    AND (@bigDriverID IS NULL OR @bigDriverID='' OR DM.DriverId=@bigDriverID)                 
    AND (@bigDriverGroupId IS NULL OR @bigDriverGroupId='' OR DG.DriverGroupId=@bigDriverGroupId)                
                    
 --GET THE DRIVER TRIPS                
 DECLARE @tblDriverTrips TABLE                
 (                
  ProcessId bigint identity(1,1),                
  Boxid int null,                
  DriverId bigint null,                
  TripTime datetime null,                
  TripStatus varchar(5)null,                
  Customprop varchar(600) null,               
  BoxmsgTypeId tinyint null,                
  Speed int null,                
  StreetAddress varchar(300) null,    
  Odometer bigint null               
 )                    
                 
 --GET THE FIRST PUNCH DETAILS FROM DRIVER ASSIGNMENT                
 DECLARE @DTFIRSTPUNCH DATETIME =NULL,@bitIsIbutton bit=null,@bitIsRFID bit=null                
 SELECT TOP 1 @DTFIRSTPUNCH=PunchIn FROM rvlfDriverAssignment                 
  WHERE BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                
   AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))                 
   AND PunchIn IS NOT NULL AND PunchOut IS NOT NULL               
   AND PunchIn BETWEEN @dtStartDate  AND @dtEndDate               
  ORDER BY PunchIn                 
                  
 --CHECK IF THE PUNCH IS BEFORE THE STATDATEANDTIME                  
 IF(@DTFIRSTPUNCH IS NOT NULL AND @DTFIRSTPUNCH<@dtStartDate)                
 BEGIN SET @DTFIRSTPUNCH=@dtStartDate END                
 ELSE IF (@DTFIRSTPUNCH IS NULL) BEGIN SET @DTFIRSTPUNCH=@dtStartDate END                
                  
 --GET THE IBUTTON RIGHTS FOR THE ORGANIZATION                
 SELECT @bitIsIbutton= CASE WHEN PO.PackageId IS NULL OR PO.PackageId ='' THEN 0 ELSE 1 END                 
  FROM rvlfPackageOperations PO                
   INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId                 
  WHERE OperationID =147 AND IsActive =1 AND OrganizationID=@bigOrganizationID                 
                 
 IF (@bitIsIbutton=1)                
  BEGIN                
   INSERT INTO @tblDriverTrips (Boxid,DriverId,TripTime,TripStatus)                
    SELECT BoxId,CASE WHEN CustomProp LIKE'%MAPID=%' THEN SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,                
      (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))) ELSE 0 END,OriginDateTime,                
      SUBSTRING(CustomProp,CHARINDEX('Driver Status=',CustomProp,0)+14,                
    (CHARINDEX(';',CustomProp,CHARINDEX('Driver Status=',CustomProp,0))-(CHARINDEX('Driver Status=',CustomProp,0)+14)))                
     FROM rvlfMsgInHst                 
      WHERE BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                
       AND BoxMsgInTypeId =76                
       AND SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,                
        (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))) IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))                
       AND CustomProp LIKE'%Driver Status=%' AND CustomProp LIKE '%MAPID=%'                      
       --AND OriginDateTime BETWEEN @dtStartDate AND CASE WHEN @DTFIRSTPUNCH IS NOT NULL THEN CASE WHEN @DTFIRSTPUNCH BETWEEN @dtStartDate AND @dtEndDate THEN @DTFIRSTPUNCH ELSE @dtEndDate END ELSE @dtEndDate END                       
       AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                        
       AND BoxMsgInTypeId IN(SELECT DISTINCT MT.BoxMsgInTypeId  FROM rvlfUserGroupSecurity UGS                 
        INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId                 
        INNER JOIN rvlfBoxMsgInType MT ON MT.OperationTypeID=UGS.OperationTypeId                 
       WHERE UGA.UserId=@bigQueryingUser)                
      ORDER BY BoxId, SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,                
        (LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+4))),OriginDateTime                
  END                
         
 SELECT  @bitIsRFID = CASE WHEN PO.OperationID=188 AND (PO.PackageId IS NULL OR PO.PackageId ='') THEN 0 WHEN PO.OperationID=188 THEN 1  END  FROM rvlfPackageOperations PO INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId                 
 
    
     
 WHERE OperationID IN (188) AND IsActive =1 AND OrganizationID=@bigOrganizationID           
            
 IF (@bitIsRFID =1) --RFID 29-may15           
  BEGIN              
   INSERT INTO @tblDriverTrips (Boxid,DriverId,TripTime,TripStatus)            
   SELECT h.BoxId,DM.DriverId,h.OriginDateTime,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Punch:',';')            
   FROM rvlfMsgInHst h             
   INNER JOIN rvlfIButtonMapping BM ON (IButtonKey=dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'RF_ID=',';')) AND BM.KeyType=3           
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=BM.DriverId              
   WHERE h.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))              
   AND ((h.BoxMsgInTypeId=100 AND h.CustomProp like '%RF_ID=%') )              
   AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                
   AND BoxMsgInTypeId IN(100) AND DM.DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))           
   ORDER BY h.BoxId,h.MessageInID,DM.DriverId,h.OriginDateTime                
  END          

select * from @tblDriverTrips     
 --GET THE TRIPS                
 DECLARE @tblDriverTripDetails TABLE                
 (                  
  TripId bigint identity(1,1),                
  Boxid int null,                
  DriverId bigint null,                
  StartTime datetime null,                
  EndTime datetime null,                
  TripInStatus varchar(5) null,                
  TripOutStatus varchar(5) null,                
  RunningTime int null,                
  IdlingTime int null,                
  Speed int null,                
  OdoStart bigint null,                
  OdoEnd bigint null,                
  StartAddress varchar(300) null,                
  EndAddress varchar(300) null                
 )                 
 INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)                
 SELECT MT.Boxid,MT.DriverId,MT.TripTime,MT.TripStatus,ST.TripTime,ST.TripStatus                
   FROM @tblDriverTrips AS MT                 
    LEFT OUTER JOIN @tblDriverTrips AS ST ON MT.Boxid = ST.Boxid and MT.ProcessId - 1 = ST.ProcessId AND ST.TripStatus = 'IN' and MT.DriverId=ST.DriverId and MT.TripStatus='OUT'                      
                  
 --DELETE THE INVALID TRIPS                  
 DELETE FROM @tblDriverTripDetails WHERE StartTime IS NULL --OR TripInStatus=TripOutStatus                 
                 
 --GET THE MANUEL AND AUTOMATIC SCHEDULES                
 IF(@DTFIRSTPUNCH IS NOT NULL)                
  BEGIN                
   INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)                
   SELECT BoxId,DriverId,CASE WHEN PunchOut IS NULL THEN ToTime ELSE PunchOut END,'OUT',                
    CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END,'IN'                  
    FROM rvlfDriverAssignment                  
    WHERE @DTFIRSTPUNCH BETWEEN (CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END)                
    AND (CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END)                
        --@DTFIRSTPUNCH <= CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END                 
     --AND @dtEndDate >= CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END                
     AND BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                
     AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))                 
  END                
 ELSE                
  BEGIN                
   INSERT INTO @tblDriverTripDetails (Boxid,DriverId,EndTime,TripOutStatus,StartTime,TripInStatus)                
   SELECT BoxId,DriverId,CASE WHEN PunchOut IS NULL THEN ToTime ELSE PunchOut END,'OUT',                
    CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END,'IN'                  
    FROM rvlfDriverAssignment                  
     WHERE @dtStartDate BETWEEN (CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END)                
     AND (CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END)                
     --@dtStartDate <= CASE WHEN PunchIn IS NULL THEN FromTime ELSE PunchIn END                 
     --AND @dtEndDate >= CASE WHEN PunchIn IS NULL THEN ToTime ELSE PunchOut END                
      AND BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))                
      AND DriverId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcDriverIds,','))                 
  END                
 --SELECT @dtStartDate,@dtEndDate,@DTFIRSTPUNCH,* FROM @tblDriverTripDetails                   
 --GET THE TRIP DETAILS                
 DECLARE @bigTripid bigint=null                
 SELECT @bigTripid = MIN(TripId) FROM @tblDriverTripDetails                  
 WHILE (@bigTripid IS NOT NULL)                
  BEGIN                
   DECLARE @dtTripStart datetime=null,@dtTripEnd datetime=null                
   SET @intBoxID=NULL                
   SELECT @intBoxID=Boxid,@dtTripStart =StartTime,@dtTripEnd=EndTime FROM @tblDriverTripDetails WHERE TripId=@bigTripid                 
   DELETE FROM @tblDriverTrips                 
   INSERT INTO @tblDriverTrips (BoxmsgTypeId,Customprop,Speed,TripTime,StreetAddress,Odometer)                
    SELECT BoxMsgInTypeId,CustomProp,Speed,OriginDateTime,                
    CASE WHEN (H.LandMarkID IS NULL OR H.LandMarkID = 0) THEN                 
       REPLACE(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''') ELSE L.LandmarkName END ,H.Odometer                 
    FROM rvlfMsgInHst H                
     LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID                  
    WHERE BoxId=@intBoxID AND OriginDateTime BETWEEN @dtTripStart AND @dtTripEnd                 
     AND BoxMsgInTypeId IN(SELECT DISTINCT MT.BoxMsgInTypeId  FROM rvlfUserGroupSecurity UGS                 
        INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId                 
        INNER JOIN rvlfBoxMsgInType MT ON MT.OperationTypeID=UGS.OperationTypeId                 
       WHERE UGA.UserId=@bigQueryingUser)ORDER BY OriginDateTime                 
                   
   UPDATE @tblDriverTripDetails SET Speed=(SELECT ISNULL(MAX(Speed),0) FROM @tblDriverTrips WHERE Speed!=0 AND Speed IS NOT NULL),                
    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 @tblDriverTrips  WHERE BoxmsgTypeId =9 AND CustomProp NOT LIKE '%Idling:0;%'),                
    RunningTime=(SELECT ISNULL(SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,                
        (CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60,0)                             
        FROM @tblDriverTrips  WHERE BoxmsgTypeId =3 AND Customprop NOT LIKE '%SENSOR_DURATION=0;%'),                
    OdoStart=(SELECT TOP 1 min(Odometer) from @tblDriverTrips where Odometer >0 ),                
    OdoEnd=(SELECT TOP 1 max(Odometer) from @tblDriverTrips where Odometer >0 ),                
    StartAddress =(SELECT TOP 1 StreetAddress  FROM @tblDriverTrips ORDER BY TripTime),                
    EndAddress =(SELECT TOP 1 StreetAddress  FROM @tblDriverTrips  ORDER BY TripTime DESC)                                         
   WHERE TripId=@bigTripid                 
        SELECT TOP 1 min(Odometer) from @tblDriverTrips where Odometer >0   
        SELECT TOP 1 max(Odometer) from @tblDriverTrips where Odometer >0          
   --DECLARE @DTIDLINGEND DATETIME =NULL,@DTIDLINGSTART DATETIME =NULL                
   --SELECT @DTIDLINGEND= CASE WHEN (SELECT TOP 1 Customprop FROM @tblDriverTrips WHERE BoxId=@intBoxID                 
   --  AND TripTime BETWEEN @dtTripStart AND @dtTripEnd                
   --  AND BoxmsgTypeId  =9 ORDER BY TripTime) NOT LIKE '%Idling:0;%' THEN                 
   --   (SELECT TOP 1 TripTime FROM @tblDriverTrips WHERE BoxId=@intBoxID                 
   --  AND TripTime BETWEEN @dtTripStart AND @dtTripEnd                
   --  AND BoxmsgTypeId =9 AND CustomProp NOT LIKE '%Idling:0;%' ORDER BY TripTime) ELSE @dtTripStart END                
                
   --SELECT @DTIDLINGSTART= CASE WHEN (SELECT TOP 1 CustomProp FROM @tblDriverTrips WHERE BoxId=@intBoxID                 
   --  AND TripTime BETWEEN @dtTripStart AND @dtTripEnd                
   --  AND BoxmsgTypeId =9 ORDER BY TripTime DESC)  LIKE '%Idling:0;%' THEN                 
   --   (SELECT TOP 1 TripTime FROM @tblDriverTrips WHERE BoxId=@intBoxID                 
   --  AND TripTime BETWEEN @dtTripStart AND @dtTripEnd                
   --  AND BoxmsgTypeId =9 AND CustomProp LIKE '%Idling:0;%' ORDER BY TripTime DESC) ELSE @dtTripEnd END                
                         
   --UPDATE @tblDriverTripDetails                 
   -- SET IdlingTime=(ISNULL((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 @tblDriverTrips  WHERE BoxId=@intBoxID AND TripTime BETWEEN @dtTripStart AND @dtTripEnd                 
   --      AND DriverId=@bigDriverID AND BoxmsgTypeId =9 AND CustomProp NOT LIKE '%Idling:0;%'                
   --      AND TripTime > @DTIDLINGEND AND TripTime< @DTIDLINGSTART),0)+(DATEDIFF (S,@dtTripStart,@DTIDLINGEND))+(DATEDIFF (S,@DTIDLINGSTART,@dtTripEnd)))                   
   --WHERE TripId=@bigTripid                 
                   
   SELECT @bigTripid =MIN(TripId) FROM @tblDriverTripDetails WHERE TripId >@bigTripid                     
  END                
    
--select 'A',* from @tblDriverTripDetails     
             
  --IF THE IDLING TIME IS EXCEED TO RUNNING TIME                
  UPDATE @tblDriverTripDetails SET RunningTime=IdlingTime WHERE IdlingTime>RunningTime                 
 --GET THE SUMMARY DETAILS                 
 DECLARE @tblSummary TABLE                
 (                
  Boxid int null,                
  DriverId bigint null,                
  TotDistance int null,                
  TotShiftDuration int null,                
  TotRunning int null,                
  TotIdling int null                
 )                 
 INSERT INTO @tblSummary (Boxid,DriverId,TotDistance,TotIdling,TotRunning,TotShiftDuration)                
  SELECT Boxid,DriverId,SUM((OdoEnd-OdoStart)),SUM(IdlingTime),SUM(RunningTime),SUM(DATEDIFF(S,StartTime,EndTime))   FROM @tblDriverTripDetails GROUP BY Boxid,DriverId                 
                
 --GET THE RESULT SET                 
 SELECT distinct TD.Boxid,TD.DriverId,V.VehicleId, DM.DisplayName AS DriverName,DM.LicenseNo,DM.MobileNo,V.VehicleDescription,V.LicensePlate,V.Vin,                
  CASE WHEN S.TotShiftDuration IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(S.TotShiftDuration) END AS TotShiftDuration,                
  ISNULL(S.TotDistance,'-') AS TotDistance,                
  CASE WHEN S.TotRunning IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(S.TotRunning) END AS TotRunning,                
  CASE WHEN S.TotIdling IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(S.TotIdling) END AS TotIdling,                
  StartDate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,TD.StartTime),                
  --Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.StartTime)),@DefaultDateFormat) + ' ' + Convert(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.StartTime)) as Time),22) AS StartDate,            
 
     
  TD.StartTime AS StartDateSort,          
  EndDate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,TD.EndTime),                
  --Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.EndTime)),@DefaultDateFormat) + ' '+ Convert(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,TD.EndTime)) as time),22) AS EndDate,                
  ISNULL(TD.StartAddress,'N/A') AS StartAddress ,ISNULL(TD.EndAddress,'N/A') AS EndAddress,dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(S,StartTime,EndTime))AS ShiftDuration,                
  ISNULL(OdoEnd-OdoStart,'-')AS Distance,                
  CASE WHEN TD.RunningTime IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(TD.RunningTime) END AS RunningTime,                
  CASE WHEN TD.IdlingTime IS NULL THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(TD.IdlingTime) END AS IdlingTime,                
  Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                
  PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())                
  --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate       
  
     
            
  FROM @tblDriverTripDetails TD                
   INNER JOIN @tblSummary S ON S.DriverId=TD.DriverId AND S.Boxid =TD.Boxid                  
   INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =TD.Boxid                 
   INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId                 
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=TD.DriverId                  
                   
--select * from @tblDriverTrips                 
--select * from @tblDriverTripDetails                 
                       
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetEmployeeDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetEmployeeDetails]
	@bigEmployeeID bigint

AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetEmployeeDetails 1
--	Description	:	To get the Employee details
--				:   Pass the values to @bigEmployeeID 
--	Author		:	V. Narayanasamy.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	06-Nov-2009	VN	Created Intial Version 
/******************************************************************************/
BEGIN
	SELECT e.EmployeeID, e.FirstName, e.LastName, e.DateOfBirth as Age, e.MobileNo, e.PhoneNo, e.EmailId,e.OrgId,
				e.FirstContactMobileNo,e.FirstContactName,e.FirstContactPhoneNo,e.FirstContactRelation,
				e.SecondContactMobileNo,e.SecondContactName,e.SecondContactPhoneNo,e.SecondContactRelation,
				e.Sex,e.StreetAddress,e.Latitude,e.Longitude,e.DateOfJoin,e.Available,e.DisplayName,e.Sex,
				e.ExtentionNumber,e.Building,e.CubicleNumber,e.LocalityId,LM.LocalityName,LM.Latitude AS Loclat
				,LM.Longitude AS Loclong,e.DisplayName AS EmployeeName,zm.ZoneId ,Zm.ZoneName,
				DV.OrgDivisionID, dv.OrgDivisionName,D.DepartmentID, d.DepartmentName,S.ShiftID ,s.ShiftName,
				S.ShiftInTime,S.ShiftOutTime,  
				L.LandmarkID,L.LandmarkName,T.TitleId,T.TitleName,ug.UserGroupId, ug.UserGroupDesc,e.ReportTo ,
				E1.EmailId as ReportEmailId,E1.DisplayName as ManagerName,e.UserName,e.[Password],e.employeecode       
	FROM rvlfEmployee e
				LEFT OUTER JOIN rvlfTitle T ON T.TitleId=E.Title 
				LEFT OUTER JOIN rvlfOrgShifts S ON S.ShiftID=E.ShiftID 				
				LEFT OUTER JOIN rvlfOrgDivision DV ON DV.OrgDivisionID=E.DivisionID 
				LEFT OUTER JOIN rvlfOrgDepartment D ON D.DepartmentID=E.DepartmentID 
				LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=E.NearestLandMark 
				LEFT OUTER JOIN rvlfEmployee E1 ON E1.EmployeeID=E.ReportTo 
				--LEFT OUTER JOIN rvlfUserGroupAssignment ua ON ua.UserId=e.EmployeeID 
				LEFT OUTER JOIN rvlfUserGroup ug ON ug.UserGroupId=e.usergroup
				LEFT OUTER JOIN RVLFZONEMASTER zm ON zm.ZONEID=e.ZONEID
				LEFT OUTER JOIN rvlfLocalityMaster LM ON LM.LocalityId=E.LocalityId 
	WHERE (e.EmployeeID= @bigEmployeeID) 
			 
	
				
		
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetEnergyConsumptionForShift]    Script Date: 02/01/2022 04:05:37 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 Procedure [dbo].[rvlf_sp_GetEnergyConsumptionForShift]
(
	-- Add the parameters for the function here
	@BoxId nvarchar(100) =null,
	@OriginDate datetime =null,
	@MessageInID uniqueidentifier=null
)
AS
BEGIN
	DECLARE @ResultVar bigint=0
	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)
	UPDATE p
		SET 
		p.odometer = t.WH1,
		p.duration=t.WH2
	FROM rvlfMsgInHst AS p
	INNER JOIN
	(
		SELECT @MessageInID as MessageInID, 
		(MAX(cast(isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'WH1=',';'),0) as int)) - min(cast(isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'WH1=',';'),0) as int))) as WH1,
		(MAX(cast(isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'WH2=',';'),0) as int)) - min(cast(isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'WH2=',';'),0) as int))) as WH2
		FROM rvlfMsgInHst
		WHERE BoxId=@BoxId and dateadd(MI,30,dateadd(HH,5,OriginDateTime)) between @StartDate and @OriginDate AND BoxMsgInTypeId=1
		--WHERE BoxId=@BoxId and dateadd(MI,30,dateadd(HH,5,OriginDateTime)) between @StartDate and @OriginDate and dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'WH1=',';') is not null and dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'WH2=',';') is not null
	) t
    ON t.MessageInID = p.MessageInID
WHERE p.MessageInID = @MessageInID


UPDATE p
		SET 
		p.WH3_EC = t.WH3,
		p.WH4_EC=t.WH4,
		p.WH5_EC=t.WH5
	FROM rvlfMsgInHst_Secondary AS p
	INNER JOIN
	(
		SELECT @MessageInID as MessageInID, 
		(MAX(isnull(WH3,0)) - min(isnull(WH3,0))) as WH3,
		(MAX(isnull(WH4,0)) - min(isnull(WH4,0))) as WH4,
		(MAX(isnull(WH5,0)) - min(isnull(WH5,0))) as WH5
		FROM rvlfMsgInHst_Secondary
		WHERE BoxId=@BoxId and dateadd(MI,30,dateadd(HH,5,OriginDateTime)) between @StartDate and @OriginDate
	) t
    ON t.MessageInID = p.MessageInID
WHERE p.MessageInID = @MessageInID

UPDATE p
		SET 
		p.WH6_EC = t.WH6,
		p.WH7_EC=t.WH7,
		p.WH8_EC=t.WH8,
		p.WH9_EC=t.WH9,
		p.WH10_EC=t.WH10,
		p.WH11_EC=t.WH11
	FROM rvlfMsgInHst_Primary AS p
	INNER JOIN
	(
		SELECT @MessageInID as MessageInID, 
		(MAX(isnull(WH6,0)) - min(isnull(WH6,0))) as WH6,
		(MAX(isnull(WH7,0)) - min(isnull(WH7,0))) as WH7,
		(MAX(isnull(WH8,0)) - min(isnull(WH8,0))) as WH8,
		(MAX(isnull(WH9,0)) - min(isnull(WH9,0))) as WH9,
		(MAX(isnull(WH10,0)) - min(isnull(WH10,0))) as WH10,
		(MAX(isnull(WH11,0)) - min(isnull(WH11,0))) as WH11
		FROM rvlfMsgInHst_Primary
		WHERE BoxId=@BoxId and dateadd(MI,30,dateadd(HH,5,OriginDateTime)) between @StartDate and @OriginDate
	) t
    ON t.MessageInID = p.MessageInID
WHERE p.MessageInID = @MessageInID


UPDATE p
		SET 
		p.WH12_EC = t.WH12,
		p.WH13_EC=t.WH13,
		p.WH14_EC=t.WH14,
		p.WH15_EC=t.WH15,
		p.WH16_EC=t.WH16,
		p.WH17_EC=t.WH17,
		p.WH18_EC=t.WH18,
		p.WH19_EC=t.WH19
	FROM rvlfMsgInHst_FibreCompactor AS p
	INNER JOIN
	(
		SELECT @MessageInID as MessageInID, 
		(MAX(isnull(WH12,0)) - min(isnull(WH12,0))) as WH12,
		(MAX(isnull(WH13,0)) - min(isnull(WH13,0))) as WH13,
		(MAX(isnull(WH14,0)) - min(isnull(WH14,0))) as WH14,
		(MAX(isnull(WH15,0)) - min(isnull(WH15,0))) as WH15,
		(MAX(isnull(WH16,0)) - min(isnull(WH16,0))) as WH16,
		(MAX(isnull(WH17,0)) - min(isnull(WH17,0))) as WH17,
		(MAX(isnull(WH18,0)) - min(isnull(WH18,0))) as WH18,
		(MAX(isnull(WH19,0)) - min(isnull(WH19,0))) as WH19
		FROM rvlfMsgInHst_FibreCompactor
		WHERE BoxId=@BoxId and dateadd(MI,30,dateadd(HH,5,OriginDateTime)) between @StartDate and @OriginDate
	) t
    ON t.MessageInID = p.MessageInID
WHERE p.MessageInID = @MessageInID
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetEquipmentItemList]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- rvlf_sp_GetEquipmentItemList @tag=N'A',@EquipmentID=N'65',@boxID=N'TestDeviceAsan',@ItemList=N'145,156,190,192,191,162,168,160,169,157,163,164,146,147,148,149,150,151,152,153,154,155,161,132,133,134,135,136,137,138',@bigUserid=N'457',@OrganizationId=N'6'
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetEquipmentItemList]
	-- Add the parameters for the stored procedure here
	@tag varchar(10),
	@EquipmentID bigint=null,
	@boxID varchar(200)=null,
	@ItemList varchar(MAX)=null,
	@bigUserid bigint=null,
	@OrganizationId bigint,
	@Remarks varchar(1500)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if(@tag='S')
		begin
			Select ITM.ItemTypeID as EquipmentID,ITM.ItemTypeName as EquipmentName,ITM.ItemtypeDesc as EquipmentDesc,IM.ItemSNo, IM.Itemcode,IM.ItemName,IM.ItemDesc  from rvlfItemTypeMaster ITM 
			inner join rvlfItemTypeDetails ITD on ITM.ItemTypeID=ITD.ItemTypeID 
			inner join rvlfInvItemMaster IM on ITD.ItemID=IM.ItemSNo
			WHERE (@EquipmentID IS NULL OR @EquipmentID='' OR @EquipmentID='0' OR ITM.ItemTypeID=@EquipmentID)
			and IM.OrganizatioID=@OrganizationId
			order by EquipmentID
			select ItemID,Remarks from rvlfEquipmentItemAssignment where EquipmentID=@EquipmentID and BoxID=@boxID
		end
	else if(@tag='A')
		begin
			--Select * from [dbo].[fn_Split](@ItemList,',')
			delete from rvlfEquipmentItemAssignment where BoxID=@boxID and EquipmentID=@EquipmentID
			insert into rvlfEquipmentItemAssignment(EquipmentID,ItemID,BoxID,CreatedBy,CreatedDate,Remarks)
			select @EquipmentID,value,@BoxID,@bigUserid,GETDATE(),@Remarks from [dbo].[fn_Split](@ItemList,',')
			
		end
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetEquipmentLocation]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE proc [dbo].[rvlf_sp_GetEquipmentLocation]
(      
--@OrgID bigint ,    
@ProductId tinyint = null    
)      
as      
/******************************************************************************/                                              
-- Name  : rvlf_sp_GetEquipmentLocation 
-- Description : Get Product and serial / boxid                                             
-- Author  : Gopal.R      
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--Created Date -19-jun-2014       
/******************************************************************************/        
begin      
select EquipmentLoca,EquipmentLocaName  from rvlfEquipmentLocation EL 
-- where --MD.OrganizationId=@OrgID  and    
--(@ProductId is null or @ProductId ='' or SP.ProductId=@ProductId)  and SP.Isdelete=0      
end


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetExpiredOrgDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetExpiredOrgDetails]
	@intDueWithinFrom int = -10,
	@intDueWithinTo int = 10
AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetExpiredOrgDetails
--	Description	:	To get update the street address from the background process
--	Author		:	M. Jebamalai Jaya Chitra
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	14-Nov-2009	MJJC Created initial version
--				:	09-MAY-2011 VN included the order by clause in the select statement.
--				:	21-Jun-2013 Sakthi GETDATE instead of UTC date for more clarity in date
/******************************************************************************/
BEGIN
	DECLARE @vcOrglist varchar(max)
	SELECT @vcOrglist = ISNULL(@vcOrglist+'','')+ ('<tr><td><font face="arial" size="2px">'+g.OrganizationDisplayName 
	+'</font></td><td><font face="arial" size="2px">'+ pg.PackageName +'</font></td><td><font face="arial" size="2px">'+
		convert(varchar, p.PurchasedOn,106)+'</font></td><td><font face="arial" size="2px">'+
		convert(varchar, g.ExpiresOn,106)+'</font></td><td><font face="arial" size="2px">'+
		CAST(ABS(DATEDIFF(DAY,GETDATE(),g.ExpiresOn)) as varchar(3))+' day(s)'+
		CASE WHEN DATEDIFF(DAY,GETDATE(),g.ExpiresOn)>0 then '' ELSE ' overdue' END
			+' </font></td></tr>')
	FROM rvlfOrganization g INNER JOIN rvlfOrganizationPackage p on p.OrganizationID = g.OrganizationId
		INNER JOIN rvlfPackage pg ON p.PackageId = pg.PackageId
	WHERE DATEDIFF(day, GETDATE(),g.ExpiresOn) between @intDueWithinFrom and @intDueWithinTo
		AND p.IsActive = 1 and g.OrganizationId=86 ORDER BY G.ExpiresOn
	IF @vcOrglist IS NOT NULL
	BEGIN
		SET @vcOrglist = '<font face="arial" size="2px"><p><strong>Dear All,</strong></p></font><font face="arial" size="2px"><p>'
			+'Below are the expiry details of license(s):</p><table style="width: 574px; height: 70px;" border=1><tr><td>'
			+'<strong><font face="arial" size="2px">Organization</font></strong></td><td>'
			+'<strong><font face="arial" size="2px">Package Name</font></strong></td><td>'
			+'<strong><font face="arial" size="2px">Purchased On</font></strong></td><td>'
			+'<strong><font face="arial" size="2px">Expires On</font></strong></td><td>'
			+'<strong><font face="arial" size="2px">Due in</font></strong></td></tr>'+@vcOrglist
			+'</table><p>This is for your information</p><p><b>Best Regards, </b></p></font><p>'
			+'<a border="0" href="http://www.trinetrawireless.com/">'
			+'<img border="0" src="http://www.trinetrawireless.com/images/logo.png" style="width: 100px; height: 36px;" />'
			+'</a></p><hr /><p><font face="arial" size="1px">This is system generated mail</font></p>'
	END
	SELECT @vcOrglist as OrgExpiryList, 'Gopalakrishnan@angleritech.com,shreeprakaash@angleritech.com' as OrgNotificationList
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFareDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
                             
CREATE Proc [dbo].[rvlf_sp_GetFareDetails]                                
@TripId bigint = null,                                
@VendorID int = Null,                                                          
@boxid int =Null,                                
@bigOrganizationId bigint = Null,                                                          
@bigUserId bigint = Null,                                                       
@StartDate datetime =null,                                
@EndDate datetime  =null                              
as                                
-- =============================================                                            
-- Name   : rvlf_sp_GetFareDetails 26547,1,null,6,12,null,null        
-- Author  : Gopal.R                                            
-- Create date : 24-Oct-2013                                            
-- Description :  Get Fare Details                                            
-- Company  : Angler Technologies                                            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                            
-- =============================================                                     
begin                                
SET NOCOUNT ON;                                
                                
DECLARE @HoursToBeAdded INT = 0                                                    
DECLARE @MinsToBeAdded INT = 0                                                    
DECLARE @ConversionFactor decimal(18,2) = 1.0                                                    
DECLARE @ConversionFactorSpeed decimal(18,2) = 1.0                                                    
DECLARE @DefaultDateFormat INT = 0                                                    
Declare @VendorContractFrom datetime            
Declare @venodrContractTo datetime            
                                                                     
SELECT @ConversionFactor = CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 END,                                            
@DefaultDateFormat=(case when  ISNULL(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end),                                                              
@ConversionFactorSpeed = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                                                           
@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded                                                                 
FROM [DBO].[rvlfUserPreferences] up INNER JOIN [DBO].[rvlfTimeZones] tz                                                                  
ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId                               
                                
--SET @StartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@StartDate))                                    
--SET @EndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@EndDate))               
            
if(@VendorID is not null or @VendorID <> '')                        
begin            
select @VendorContractFrom=ContractFrom,@venodrContractTo=ContractTo from rvlfVendors where VendorId=@VendorID            
end            
           
if(@TripId is not null or @VendorID <> '')                        
select @StartDate=StartDate,@EndDate=EndDate from rvlfTripDetails_AFC where TripId=@TripId        
            
if(@StartDate between @VendorContractFrom and @venodrContractTo) --check start date and end date between contract period            
begin            
            
  if(@EndDate >= @VendorContractFrom and @EndDate > @venodrContractTo)            
  begin            
  set @EndDate =@venodrContractTo            
  end            
            
  select trp.TripId,trp.BoxId, trp.StartDate as StartDate1 ,trp.EndDate as EndDate1,trp.OdometerStart,trp.OdometerEnd,isnull((trp.OdometerEnd - trp.OdometerStart),0) as totdistanceKm,                        
  ((trp.OdometerEnd - trp.OdometerStart) *@ConversionFactorSpeed)   as TotalDistance,trp.StartMessageInID,trp.EndMessageInID,trp.IsTripClosed,trp.IdlingDuration,                              
  trp.StopTime,isnull(trpf.PackageLocation,'-') as PackageLocation,isnull(trpf.UsersDepartment,'-') as UsersDepartment,                              
  ISNULL(CAST(cast((trpf.AddDistance * @ConversionFactorSpeed) as decimal(8,2)) as varchar(10)),'-')as AddDistance ,isnull(cast(cast((trpf.UwDistance* @ConversionFactorSpeed) as decimal(8,2)) as varchar(10)),'-') as UwDistance,                        
  isnull(cast(trpf.TollCharge as                        
   varchar(10)),'-') as TollCharge,                              
  isnull(cast(trpf.MaintFare as varchar(10)),'-') as MaintFare,isnull(cast(trpf.FuelRate as varchar(10)),'-')as FuelRate,isnull(cast(trpf.FuelHike as varchar(9)),'-')as FuelHike,                              
  veh.VehicleDescription,veh.VehicleId,v.VendorName,v.VendorId,v.ContractFrom,v.ContractTo,v.FxCostPerMonth,v.FxKMPerMonth,v.DutyHourType,v.FuelCostPerLit,v.LiterPerKm                              
  ,v.ExCostPerKm,v.ExCostPerHr ,(select COUNT(vm.VendorId) from rvlfVendorMDays vm where vm.VendorId=v.VendorId and (cast([Date] as date) =CAST(trp.StartDate as Date) or cast([Date] as date)=CAST(trp.EndDate as Date))) as ismaintenace ,                   
  
  isnull((trpf.MaintFare + trpf.TollCharge),0.00) as TotFareCost,
  --,case when trp.StartMessageInID IN (select MessageInId from rvlfMsgInHst) then dbo.rvlf_fn_DayLightSavings(trp.StartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,trp.StartDate) +'  -  ' +                          
  --(select isnull(l.LandmarkName,isnull(mh.StreetAddress,'N/A'))  from rvlfMsgInHst mh LEFT join rvlfLandmark l on mh.LandMarkID=l.LandmarkID where MessageInID=trp.StartMessageInID)             
  --else dbo.rvlf_fn_DayLightSavings(trp.StartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,trp.StartDate) end as StartDate,                          
  --case  when trp.EndMessageInID  IN (select MessageInId from rvlfMsgInHst) then dbo.rvlf_fn_DayLightSavings(trp.EndDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,trp.EndDate) + '  -  '+                          
  --(select isnull(l.LandmarkName,isnull(mh.StreetAddress,'N/A')) from rvlfMsgInHst mh LEFT join rvlfLandmark l on mh.LandMarkID=l.LandmarkID where MessageInID=trp.EndMessageInID)             
  --else dbo.rvlf_fn_DayLightSavings(trp.EndDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,trp.EndDate) end as EndDate                          
                             
  case when trp.StartMessageInID IN (select MessageInId from rvlfMsgInHst) then dbo.rvlf_fn_DayLightSavings(trp.StartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,trp.StartDate) +'  -  ' +                          
isnull((select a.GeozoneName from rvlfOrganizationGeozone a where a.OrganizationId=@bigOrganizationId and a.GeozoneId = cast((select SUBSTRING(SUBSTRING(CustomProp,CHARINDEX('GeozoneID=',CustomProp)+10,LEN(CustomProp)-CHARINDEX('GeozoneID=',CustomProp)),0
,  
  CHARINDEX(';',SUBSTRING(CustomProp,CHARINDEX('GeozoneID=',CustomProp)+10,LEN(CustomProp)-CHARINDEX('GeozoneID=',CustomProp))))  
  from rvlfMsgInHst h where MessageInID=trp.StartMessageInID and CustomProp like '%GeozoneID=%') as int))  
  ,(select isnull(l.LandmarkName,isnull(mh.StreetAddress,'N/A'))  from rvlfMsgInHst mh LEFT join rvlfLandmark l on mh.LandMarkID=l.LandmarkID where MessageInID=trp.StartMessageInID))             
  else dbo.rvlf_fn_DayLightSavings(trp.StartDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,trp.StartDate) end as StartDate,                          
  case  when trp.EndMessageInID  IN (select MessageInId from rvlfMsgInHst) then dbo.rvlf_fn_DayLightSavings(trp.EndDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,trp.EndDate) + '  -  '+                          
  isnull(  
  (select a.GeozoneName from rvlfOrganizationGeozone a where a.OrganizationId=@bigOrganizationId and a.GeozoneId = cast((select SUBSTRING(SUBSTRING(CustomProp,CHARINDEX('GeozoneID=',CustomProp)+10,LEN(CustomProp)-CHARINDEX('GeozoneID=',CustomProp)),0,  
  CHARINDEX(';',SUBSTRING(CustomProp,CHARINDEX('GeozoneID=',CustomProp)+10,LEN(CustomProp)-CHARINDEX('GeozoneID=',CustomProp))))  
  from rvlfMsgInHst h where MessageInID=trp.EndMessageInID and CustomProp like '%GeozoneID=%') as int))  
  ,(select isnull(l.LandmarkName,isnull(mh.StreetAddress,'N/A')) from rvlfMsgInHst mh LEFT join rvlfLandmark l on mh.LandMarkID=l.LandmarkID where MessageInID=trp.EndMessageInID))  
  else dbo.rvlf_fn_DayLightSavings(trp.EndDate,@bigUserId,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,trp.EndDate) end as EndDate                                 
                            
                            
  from rvlfTripDetails_AFC trp                                
  inner join rvlfTripFareDetails trpf on trp.TripId=trpf.TripId                                
  inner join rvlfVehicleAssignment va on trp.BoxId=va.BoxId                                
  inner join rvlfVehicle veh on va.VehicleId= veh.VehicleId                                
  inner join rvlfVendorVehicles vveh on va.VehicleId=vveh.VehicleId                                
  inner join  rvlfVendors v on vveh.VendorId=v.VendorId                           
                                 
    where (trp.BoxId = @boxid or @boxid is null or @boxid ='' )                              
    and (v.VendorId= @VendorID or @VendorID is null or @VendorID = '')                              
    and (v.OrganizationId=@bigOrganizationId or @bigOrganizationId is null or @bigOrganizationId = '')                              
    --and (trp.StartDate between @StartDate and @EndDate or @StartDate is null or @EndDate is null)                              
    and (trp.StartDate >= @StartDate or @StartDate is null or @StartDate ='')                              
    and (cast(trp.EndDate as DATE)<= cast(@EndDate as date) or @EndDate is null or @EndDate='')                              
    and (trp.TripId = @TripId or @TripId is null) and trp.IsTripClosed=1            
    order by trpf.TripId desc               
             
end            
                          
set Nocount off;                                
end 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFaultyDevices]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create proc [dbo].[rvlf_sp_GetFaultyDevices]
as
begin
select Boxid from rvlfFaultyDevices where Isfault=1
end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFirmware]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvlf_sp_GetFirmware]
AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetFirmware
--	Description	:	To list the firmware versions
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	21-Apr-2010	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
  SELECT FwId,BoxHwTypeId,FwTypeName,FwName,FwLocalPath,FwDateReleased,MaxGeozones,OAPPort FROM rvlfFirmwareType
  inner join rvlfFirmware ON rvlfFirmware.FwTypeId=rvlfFirmwareType.FwTypeId
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFirmwareVersions]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetFirmwareVersions] 
	@intBoxID int = null,
	@intFwCategoryID int=null
	--@bigVehicleID bigint = null,
	--@bigQueryingUser bigint = 0
AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetFirmwareVersions null,1
--	Description	:	To get the fleets based on the organization if specified.
--				:   Future impl:
--						If the user id is passed then basedon the user rights 
--						it has to query
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	28-May-2009	MJJC	Created Intial Version 
--				:   16-Nov-2010 SJ	Included Firmware Category ID 
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 
	
		SELECT Top 5 fv.FwId, fv.FwName, fv.FwLocalPath, fv.FwOAPPath, fv.OAPPort,
			ft.FwTypeName, rc.ChName,
			'filepath:'+ REPLACE(fv.FwOAPPath, ':', '@@')+',version:'+cast(fv.FwId as varchar(6)) as Paraminfo,
			FwCategoryID
			 FROM rvlfFirmware fv 
			INNER JOIN rvlfFirmwareType ft ON fv.FwTypeId = ft.FwTypeId
			INNER JOIN rvlfFirmwareChannels fc ON fv.FwId = fc.FwId
			INNER JOIN rvlfChannels rc ON fc.ChId = rc.ChId
			WHERE ((@intFwCategoryID IS NULL) OR 
			(FwCategoryID=@intFwCategoryID)) --OR fv.FwId in (36, 40, 35)
			--ORDER BY fv.FwId DESC
			ORDER BY fv.FwDateReleased DESC
		--WHERE rc.CommModeId = 
		--	(SELECT bs.CommModeId FROM rvlfBoxSettings bs WHERE bs.BoxId = @intBoxID )
	SET NOCOUNT OFF
END




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFleetByUser_Customer]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetFleetByUser_Customer]
@UserId BIGINT,@CustomerID bigint = null 
AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetFleetByUserId
--	Description	:	To get the fleet based on User Id
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	25-Dec-2009		Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 

DECLARE @varUserName AS Varchar(30)
DECLARE @bigOrganizationId AS BIGINT

SELECT @bigOrganizationId = u.OrganizationId, @varUserName = u.UserName FROM rvlfUser u
WHERE u.UserId = @UserId

IF(@varUserName = 'Administrator')
BEGIN
	SELECT distinct f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleet f inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
		inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
	WHERE f.OrganizationId = @bigOrganizationId
	 and  (@CustomerID IS NULL OR @CustomerID = 0 OR @CustomerID = '' OR  (md.CustomerId = @CustomerID and f.FleetName !='All')) 
END
ELSE
BEGIN
	SELECT distinct f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleetUsers fu
	INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
	inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
	inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
	WHERE UserId = @UserId 
	and  (@CustomerID IS NULL OR @CustomerID = 0 OR @CustomerID = '' OR  (md.CustomerId = @CustomerID and f.FleetName !='All') )
END	
SET NOCOUNT OFF
END

 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFleetByUserId]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetFleetByUserId]

@UserId BIGINT

AS

/******************************************************************************/
--	Name		:	rvlf_sp_GetFleetByUserId
--	Description	:	To get the fleet based on User Id
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	25-Dec-2009		Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 

DECLARE @varUserName AS Varchar(30)
DECLARE @bigOrganizationId AS BIGINT

SELECT @bigOrganizationId = u.OrganizationId, @varUserName = u.UserName FROM rvlfUser u
WHERE u.UserId = @UserId

IF(@varUserName = 'Administrator')
BEGIN

	SELECT f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleet f
	WHERE f.OrganizationId = @bigOrganizationId

END
ELSE
BEGIN

	SELECT f.FleetId, f.FleetName, f.IsDefault FROM rvlfFleetUsers fu
	INNER JOIN rvlfFleet f ON f.FleetId = fu.FleetId
	WHERE UserId = @UserId

END
	
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFleets]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetFleets]  
 @bigFleedID bigint = null,  
 @bigOrganizationID bigint = null,  
 @bigQueryingUser bigint = 0  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetFleets  
-- Description : To get the fleets based on the organization if specified.  
--    :   Future impl:  
--      If the user id is passed then basedon the user rights   
--      it has to query  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 28-May-2009 MJJC Created Intial Version   
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
 SELECT   
  f.FleetId, f.FleetName, f.OrganizationId, f.[Description], f.Email, f.SMS,  
  f.TimeZone, f.DayLightSaving, f.Notify, f.Warning, f.Critical,   
  f.AutoAdjustDayLightSaving, g.OrganizationName, --t.TimeZoneID, t.TimeZoneDesc, t.TimeZoneName,  
  ISNULL(dbo.rvlf_fn_GetNotificationsList(3, f.FleetId, 1,1,0),'') as EmailList,   
  ISNULL(dbo.rvlf_fn_GetNotificationsList(3, f.FleetId, 0,1,0),'') as SMSList,  
      
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(3, f.FleetId, 1,0,1),''),',',', ') as EmailUserNameList,  
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(3, f.FleetId, 0,0,1),''),',',', ') as SMSUserNameList,  
  f.IsDefault  
 FROM rvlfFleet f  
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
  --INNER JOIN rvlfTimeZones t ON f.TimeZone = t.TimeZoneID  
 WHERE  
 --((@bigFleedID is null AND @bigQueryingUser IS NULL) or (@bigFleedID = 0 AND @bigQueryingUser IS NULL) OR ((@bigFleedID IS NULL OR @bigFleedID = '' OR @bigFleedID = 0) AND @bigQueryingUser IS NOT NULL AND f.FleetId IN (SELECT fu.FleetId FROM rvlfFleetUsers fu WHERE fu.FleetId = f.FleetId AND fu.UserId = @bigQueryingUser))) and
  
  (@bigFleedID IS NULL OR @bigFleedID='' OR @bigFleedID = 0 or f.FleetId = @bigFleedID) AND  
  (@bigQueryingUser IS NULL OR @bigQueryingUser='' OR @bigQueryingUser = 0 or 
  f.FleetId IN (SELECT fu.FleetId FROM rvlfFleetUsers fu WHERE fu.FleetId = f.FleetId AND fu.UserId = @bigQueryingUser)) AND  
  (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR g.OrganizationId= @bigOrganizationID)  
 ORDER BY FleetName  
 SET NOCOUNT OFF  
END  
      
-- exec rvlf_sp_GetFleets null,null,0  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFleetUsers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetFleetUsers]  
 @bigFleetID bigint ,  
 @bigOrganizationID bigint = null,  
 @bitIsAssigned bit = 0,  
 @vcUserName varchar(50) = null,  
 @intUserGroupID int = null,
 @intUserid int = null    
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetFleetUsers 176,6,0,null,null,454  
-- Description : To get assinged and unassinged users  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 24-Jul-2009 MJJC Created Intial Version   
--              :   19-May-2011 TSK  Blocked the hidden user  
--          : 10-01-2012 Ranjith- Hidden user list for angler admin user
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
 DECLARE @tblUserList Table   
 (  
  UserID bigint  
 )  
 
 --declare @CheckUser int =null,@lastname nvarchar(100),@CheckUGid int
	--select @CheckUGid=UserGroupId from rvlfUserGroupAssignment where UserId=@intUserid
	--select @lastname=LastName from rvlfUser where UserId=@intUserid
	--if((@lastname like '%VXL%' or @lastname like '%trinetra%') or @CheckUGid=1)
	--begin
	--	set @CheckUser=null
	--end
	--else
	--begin
	--	set @CheckUser=1
	--end

  declare @Lang varchar(50)                   
  select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = (case when @intUserid is null then 0 else  @intUserid end)
      
 
   declare @usergrp int    
    set @usergrp=(SELECT g.UserGroupId FROM rvlfUserGroupAssignment ga         
    INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId        
    WHERE ga.UserId = @intUserid)    
         
   
 IF @bitIsAssigned = 1   
 BEGIN  
   
  IF @vcUserName IS NOT NULL   
  BEGIN  
   INSERT INTO @tblUserList select UserId from rvlfUser where (@vcUserName IS NULL OR @vcUserName='' OR UserName like @vcUserName +'%' )  
    AND IsHidden <> 1 AND  UserId in (SELECT UserId FROM rvlfFleetUsers WHERE FleetId = @bigFleetID) AND  
    OrganizationId = @bigOrganizationID   
  END  
    
  IF @intUserGroupID IS NOT NULL   
  BEGIN    
   INSERT INTO @tblUserList select UserId from rvlfUser where   
    UserId in (SELECT UserId FROM rvlfFleetUsers WHERE FleetId = @bigFleetID) AND  
    UserId IN (SELECT ga.UserId FROM rvlfUserGroupAssignment ga WHERE   
    (@intUserGroupID IS NULL OR @intUserGroupID='' OR ga.UserGroupId = @intUserGroupID)) AND  
    OrganizationId = @bigOrganizationID  
  END  
    
  IF @intUserGroupID IS NULL AND @vcUserName IS NULL   
  BEGIN  
   INSERT INTO @tblUserList select UserId from rvlfUser where   
    UserId in (SELECT UserId FROM rvlfFleetUsers WHERE FleetId = @bigFleetID) AND  
    OrganizationId = @bigOrganizationID  
  END  
  
  select distinct(v.UserId), v.UserName, v.DisplayName, v.Firstname,  
   v.LastName, v.IsActive, v.IsLocked, dbo.rvlf_fn_GetUserGroupsByUserID(v.UserId) AS GroupBelongsTo,  
   CASE WHEN v.IsActive = 1 THEN (case when @Lang='LanguageEn' then 'Active' when @Lang='LanguageHindi' then N'सक्रिय'  else N'نشط' end) 
   ELSE (case when @Lang='LanguageEn' then 'Inactive' when @Lang='LanguageHindi' then N'निष्क्रिय' else N'غير نشط' end) END as ActiveStatusDisp,          
   CASE WHEN v.IsLocked= 1 THEN (case when @Lang='LanguageEn' then 'Locked' when @Lang='LanguageHindi' then N'बंद' else N'مقفل' end) 
   ELSE (case when @Lang='LanguageEn' then 'Unlocked' when @Lang='LanguageHindi' then N'खुला' else N'غير مقفل' end) END as LockedStatusDisp,       
  
   CASE WHEN v.IsActive =1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus,  
   CASE WHEN v.IsLocked= 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,  
   CASE WHEN EXISTS(SELECT UP.DefaultFleetId FROM rvlfUserPreferences UP   
                    WHERE UP.DefaultFleetId = @bigFleetID AND UP.UserId = v.UserId)  
              THEN 1 ELSE 0 END AssignedStatus,V.IsHidden   
  from rvlfUser v  
   left JOIN rvlfUserGroupAssignment ga ON v.UserId = ga.UserId  
   INNER JOIN rvlfFleetUsers fv ON v.UserId = fv.UserId  
  WHERE v.UserId IN (SELECT UserId FROM @tblUserList ) AND V.IsHidden <> (case when @usergrp = 1 then 2 else 1 end)  AND V.IsDelete = 0 AND V.IsRegisteredUser IS NULL 
  --and ((@CheckUser is Null) or (v.LastName = @lastname))
  ORDER BY UserName ASC  
     
 END  
 ELSE  
 BEGIN  
  -- SELECT the users assinged to the fleet  
  IF @vcUserName IS NOT NULL   
  BEGIN  
   INSERT INTO @tblUserList select UserId from rvlfUser where (@vcUserName IS NULL OR @vcUserName='' OR UserName like @vcUserName +'%' )  
    AND UserId NOT in (SELECT UserId FROM rvlfFleetUsers WHERE FleetId = @bigFleetID) AND  
    OrganizationId = @bigOrganizationID  
  END  
     
  IF @intUserGroupID IS NOT NULL   
  BEGIN   
   INSERT INTO @tblUserList select UserId from rvlfUser where   
    UserId NOT IN (SELECT UserId FROM rvlfFleetUsers WHERE FleetId = @bigFleetID) AND  
    UserId IN (SELECT ga.UserId FROM rvlfUserGroupAssignment ga WHERE   
    (@intUserGroupID IS NULL OR @intUserGroupID='' OR ga.UserGroupId = @intUserGroupID)) AND  
    OrganizationId = @bigOrganizationID  
  END  
    
  IF @intUserGroupID IS NULL AND @vcUserName IS NULL  
  BEGIN   
   INSERT INTO @tblUserList select UserId from rvlfUser where   
    UserId NOT IN (SELECT UserId FROM rvlfFleetUsers WHERE FleetId = @bigFleetID) AND  
    OrganizationId = @bigOrganizationID  
  END  
  
  select distinct(v.UserId), v.UserName, v.DisplayName, v.Firstname,  
   v.LastName, v.IsActive, v.IsLocked, dbo.rvlf_fn_GetUserGroupsByUserID(v.UserId) AS GroupBelongsTo,  
   CASE WHEN v.IsActive = 1 THEN (case when @Lang='LanguageEn' then 'Active' when @Lang='LanguageHindi' then N'सक्रिय'  else N'نشط' end)
    ELSE (case when @Lang='LanguageEn' then 'Inactive' when @Lang='LanguageHindi' then N'निष्क्रिय' else N'غير نشط' end) END as ActiveStatusDisp,          
   CASE WHEN v.IsLocked= 1 THEN (case when @Lang='LanguageEn' then 'Locked' when @Lang='LanguageHindi' then N'बंद' else N'مقفل' end) 
   ELSE (case when @Lang='LanguageEn' then 'Unlocked' when @Lang='LanguageHindi' then N'खुला' else N'غير مقفل' end) END as LockedStatusDisp,       
  
   CASE WHEN v.IsActive =1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus,  
   CASE WHEN v.IsLocked= 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus ,V.IsHidden  
  from rvlfUser v  
   left JOIN rvlfUserGroupAssignment ga ON v.UserId = ga.UserId  
   --RIGHT OUTER JOIN rvlfFleetUsers fv ON v.UserId = fv.UserId  
  WHERE v.UserId IN (SELECT UserId FROM @tblUserList ) and V.IsHidden <> (case when @usergrp = 1 then 2 else 1 end)  AND V.IsDelete = 0 AND V.IsRegisteredUser  IS NULL 
  --and ((@CheckUser is Null) or (v.LastName = @lastname)) 
    
 END  
   
 SET NOCOUNT OFF  
END  
--exec rvlf_sp_GetFleetUsers @bigFleetID = 5,@bigOrganizationID =1,@bitIsAssigned =0, /*@intUserGroupID=4,*/ @vcUserName ='a'  
--exec rvlf_sp_GetFleetUsers @bigFleetID = 5,@bigOrganizationID =1,@bitIsAssigned =1, /*@intUserGroupID=4, */@vcUserName = 'j'  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFleetUsers1]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetFleetUsers1]  
 @bigFleetID bigint ,  
 @bigOrganizationID bigint = null,  
 @bitIsAssigned bit = 0,  
 @vcAssignedUserName varchar(50) = null,  
 @vcUnassignedUserName varchar(50) = null,  
 @intAssingedUserGroupID int = null,  
 @intUnassingedUserGroupID int = null  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetFleetUsers1  
-- Description : To get assinged and unassinged users  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 24-Jul-2009 MJJC Created Intial Version   
--              :     
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
 --DECLARE @vcUserGroupName varchar(50) = NULL  
 IF @bitIsAssigned = 0   
 BEGIN  
  --IF @intAssingedUserGroupID IS NOT NULL  
  --BEGIN  
  -- SELECT @vcUserGroupName = UserGroupName FROM rvlfUserGroup   
  --  WHERE UserGroupId = @intAssingedUserGroupID  
  --END  
    
  -- Select all the users who are all not assinged to the selected fleet  
  select v.UserId, v.UserName, v.DisplayName, v.Firstname, v.LastName,v.IsActive,v.IsLocked,  
   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) AS GroupBelongsTo  
  from rvlfUser v  
  WHERE v.UserId in (SELECT ag.UserId from rvlfUserGroupAssignment ag   
    WHERE (@intUnassingedUserGroupID  IS NULL OR @intUnassingedUserGroupID='' OR  ag.UserGroupId = @intUnassingedUserGroupID))  
   AND (@vcUnassignedUserName IS NULL OR @vcUnassignedUserName='' OR v.UserName like '%'+ @vcUnassignedUserName + '%')  
   AND v.UserId NOT in (SELECT vf.UserId from rvlfFleetUsers vf   
    WHERE vf.FleetId = @bigFleetID)  
  --SELECT v.UserId, v.UserName, v.DisplayName, v.Firstname, v.LastName,v.IsActive,v.IsLocked  
  -- FROM rvlfUser v   
  --WHERE (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID)  
  -- AND v.UserId NOT IN  
  --  ( SELECT rfv.UserId FROM rvlfFleetUsers rfv WHERE FleetId = @bigFleetID)  
  --ORDER BY UserName asc  
 END  
 ELSE  
 BEGIN  
  -- SELECT the users assinged to the fleet  
  select v.UserId, v.UserName, v.DisplayName, v.Firstname, v.LastName,v.IsActive,v.IsLocked,  
   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) AS GroupBelongsTo  
  from rvlfUser v  
   INNER JOIN rvlfFleetUsers fv ON v.UserId = fv.UserId   
   INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
  WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR f.OrganizationId = @bigOrganizationID)  
   AND f.FleetId = @bigFleetID AND   
   v.UserId in (SELECT ag.UserId from rvlfUserGroupAssignment ag   
    WHERE (@intAssingedUserGroupID  IS NULL OR @intAssingedUserGroupID='' OR  ag.UserGroupId = @intAssingedUserGroupID))  
   AND (@vcAssignedUserName IS NULL OR @vcAssignedUserName='' OR v.UserName like '%'+ @vcAssignedUserName + '%')  
   AND v.UserId in (SELECT vf.UserId from rvlfFleetUsers vf   
    WHERE vf.FleetId = @bigFleetID)  
  ORDER BY UserName asc  
 END  
   
 SET NOCOUNT OFF  
END  
--exec rvlf_sp_GetFleetUsers @bigFleetID = 5,@bigOrganizationID =1,@bitIsAssigned =0, /*@intUnAssingedUserGroupID=4,*/ @vcUnassignedUserName ='a'  
--exec rvlf_sp_GetFleetUsers @bigFleetID = 5,@bigOrganizationID =1,@bitIsAssigned =1, /*@intAssingedUserGroupID=4, */@vcAssignedUserName = 'j'  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFleetUtilizationDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetFleetUtilizationDetails]    
 @bigOrganizationID bigint=null,    
 @bigFleetID bigint =null,    
 @intBoxID varchar(max)=null,    
 @dtStartDate datetime=null,    
 @dtEndDate datetime=null,    
 @bigQueryingUser bigint=NULL    
     
AS    
/*****************************************************************************************************************/    
-- Name  : [rvlf_sp_GetFleetUtilizationDetails] 6,8,null,'2011-12-03 08:00:00 AM','2011-12-20 08:00:00 AM',341    
-- Description : To get the Fleet utiliozation details based onn the date ranges    
-- Author  : Narayanasamy    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--          : 27-Jan-2011 VN Created     
--          : 10-Aug-2011 Ranjith Date format Included  
--          : 30-Nov-2011 Sakthi Distance calculation based on organization  
/****************************************************************************************************************/     
    
BEGIN    
   
  Declare @dtFDate datetime =@dtStartDate  
 Declare @dtEDate datetime =@dtEndDate  
     
DECLARE @HoursToBeAdded INT = 0    
 DECLARE @MinsToBeAdded INT = 0    
 DECLARE @ConversionFactor numeric (10,2) = 1.0    
 DECLARE @DistanceCaptionPrefix varchar(15)    
 DECLARE @SpeedCaptionPrefix varchar(15)    
 DECLARE @DefaultDateFormat INT = 0  
    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,  
     @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 = @bigQueryingUser    
    
    
CREATE TABLE #tblVehicles    
(    
 ProcessId int identity(1,1),    
 VehicleId bigint,    
 VehicleDescription varchar(50),    
 LicensePlate varchar(50),    
 Vin varchar(50),    
 Boxid bigint,    
 NoofTrips int,    
 Distance int,    
 RunningTime INT,     
 DaysUtilizaed TINYINT,    
 FleetName varchar(50),    
 OrgName varchar(50),    
 WeekDays datetime,    
 ToWeekdays datetime,    
 MaxOdo bigint,    
)    
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    
  )    
DECLARE @dtFromDate DATETIME=@dtStartDate    
DECLARE @dtToDate DATETIME=@dtEndDate    
    
    
WHILE CONVERT(DATE,@dtFromDate)<=CONVERT(DATE,@dtToDate)    
 BEGIN    
  DECLARE @DTLOOPFROMDATE DATETIME =NULL,@DTLOOPTODATE DATETIME =NULL    
        
  SET @dtFromDate =CONVERT(DATE,@dtFromDate)    
      
  SELECT @DTLOOPFROMDATE= DATEADD(HOUR,@HoursToBeAdded*-1,DATEADD(MINUTE,@MinsToBeAdded*-1,@dtFromDate)),    
    @DTLOOPTODATE=DATEADD(HOUR,@HoursToBeAdded*-1,DATEADD(MINUTE,@MinsToBeAdded*-1,DATEADD(D,1,@dtFromDate)))    
      
  INSERT INTO #tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName,OrgName,WeekDays,ToWeekdays)    
   SELECT VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName,O.OrganizationName,@DTLOOPFROMDATE,@DTLOOPTODATE        
   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 (@bigFleetID IS NULL OR @bigFleetID='' OR F.FleetId=@bigFleetID)    
--AND (@intBoxID IS NULL OR @intBoxID='' OR VA.BoxId=@intBoxID)    
AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR VA.BoxId IN (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))
    ORDER BY BI.BOXID    
  SET @dtFromDate=DATEADD(D,1,@dtFromDate)    
 END     
     
 --GET THE TRIPS    
 DECLARE @tblTrips TABLE    
 (    
  ProcessId bigint identity(1,1),    
  Boxid int null,      
  TripTime datetime null,    
  TripStatus varchar(10)null    
 )     
     
 --GET THE TRIP DELTAILS    
 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    
 )      
DECLARE @DUPBOXID INT =NULL     
DECLARE @ProcessId int  =(SELECT MIN(ProcessId) FROM #tblVehicles)     
WHILE @ProcessId IS NOT NULL    
 BEGIN    
  DECLARE @intBoxLoop int = NULL,@dtDateEndLoop datetime=NULL,@dtDateLoop DATETIME =null    
  SELECT @intBoxLoop=Boxid,@dtDateEndLoop=ToWeekdays,@dtDateLoop=WeekDays  FROM #tblVehicles WHERE ProcessId=@ProcessId         
  -- GET THE MSGS FOR THE BOXID    
  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 @dtDateLoop and @dtDateEndLoop             
      AND h.BoxID = @intBoxLoop    
     ORDER BY h.origindatetime ASC      
        
  --CALCULATE THE DISTANCE    
 IF EXISTS(SELECT * FROM #tblVehicles WHERE MaxOdo IS NOT NULL AND Boxid=@intBoxLoop)    
  BEGIN    
   UPDATE #tblVehicles SET Distance =(SELECT ISNULL(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)) - (SELECT CAST( MAX(MaxOdo) AS BIGINT) FROM #tblVehicles WHERE Boxid=@intBoxLoop)) * @ConversionFactor),0)  AS DISTANCE    
   FROM @tblMessageForProcessingTrip M       
    WHERE  (M.BoxId= @intBoxLoop)        
     AND OriginDateTime BETWEEN @dtDateLoop AND @dtDateEndLoop     
     AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3))    
    WHERE Boxid =@intBoxLoop AND Distance IS NULL AND WeekDays =@dtDateLoop     
      
  END    
 ELSE    
  BEGIN    
   UPDATE #tblVehicles SET Distance =(SELECT ISNULL(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),0)  AS DISTANCE    
   FROM @tblMessageForProcessingTrip M       
    WHERE  (M.BoxId= @intBoxLoop)        
     AND OriginDateTime BETWEEN @dtDateLoop AND @dtDateEndLoop     
     AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3))    
    WHERE Boxid =@intBoxLoop AND Distance IS NULL AND WeekDays =@dtDateLoop     
      
  END      
     
     
      
  --CALCULATE THE UTILIZATED DAYS    
  UPDATE #tblVehicles SET DaysUtilizaed =(SELECT CAST(COUNT(Actions) as varchar) FROM (SELECT COUNT(BoxId) AS Actions     
   FROM @tblMessageForProcessingTrip      
    WHERE BoxId=@intBoxLoop          
     AND BoxMsgInTypeId IN (2,3)   
     AND OriginDateTime BETWEEN @dtDateLoop AND @dtDateEndLoop           
    GROUP BY CONVERT(DATE,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,OriginDateTime))))AS A)    
   WHERE Boxid =@intBoxLoop AND DaysUtilizaed IS NULL AND WeekDays =@dtDateLoop     
    
 IF EXISTS(SELECT Boxid  FROM #tblVehicles WHERE DaysUtilizaed=1 AND Boxid=@intBoxLoop AND WeekDays=@dtDateLoop)    
  BEGIN     
   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 @dtDateLoop and @dtDateEndLoop      
     ORDER BY BoxId,OriginDateTime     
   IF((SELECT TOP 1 TripStatus FROM @tblTrips ORDER BY ProcessId DESC)='START')      
   BEGIN    
    INSERT INTO @tblTrips (Boxid,TripTime,TripStatus)    
    SELECT TOP 1 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(3)              
       AND OriginDateTime >=@dtDateEndLoop      
      ORDER BY BoxId,OriginDateTime    
          
    --DELETE THE INVALID TRIPS    
    DELETE FROM @tblTrips WHERE TripTime >(SELECT MAX(ToWeekdays)FROM #tblVehicles)          
   END       
         
   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)    
       
   --UPDATE THE DETAILS TO MAIN TABLE    
   UPDATE #tblVehicles SET NoofTrips =(SELECT COUNT(TripId) FROM @tblTripDetails),    
     RunningTime=(SELECT SUM(RunningTime) FROM @tblTripDetails),    
     MaxOdo=(SELECT  MAX(CAST(ISNULL(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,    
      (CHARINDEX(';',CustomProp,CHARINDEX('Odometer=',CustomProp,1)))-    
      (CHARINDEX('Odometer=',CustomProp,1)+9)),0) AS BIGINT))    
  FROM @tblMessageForProcessingTrip M       
   WHERE  (M.BoxId= @intBoxLoop)        
    AND OriginDateTime BETWEEN @dtDateLoop AND @dtDateEndLoop     
    AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3))    
    WHERE Boxid=@intBoxLoop AND WeekDays=@dtDateLoop                 
  END       
        
  SELECT @ProcessId=MIN(ProcessId) FROM #tblVehicles WHERE ProcessId >@ProcessId     
 END     
    
DECLARE @tblResults table    
(    
 VehicleId bigint,    
 VehicleDescription varchar(50),    
 LicensePlate varchar(50),    
 FleetName varchar(50),    
 OrgName varchar(50),    
 Date1 varchar(50),    
 Date2 varchar(50),    
 Date3 varchar(50),    
 Date4 varchar(50),    
 Date5 varchar(50),    
 Date6 varchar(50),    
 Date7 varchar(50),    
 RepType tinyint,    
 Summary varchar(20)    
)    
    
DECLARE @sql NVARCHAR(MAX)    
    
DECLARE @dates NVARCHAR(MAX)    
    
SET @dates = STUFF((SELECT CAST(',' AS VARCHAR(MAX)) + QUOTENAME([dt])    
FROM (SELECT  WeekDays AS [dt] FROM #tblVehicles GROUP BY WeekDays) AS a    
ORDER BY [dt] FOR XML PATH('')), 1, 1, '')    
--get the Utilized days    
SET @sql = N'select * from (    
    select WeekDays AS [dt],[VehicleId], [VehicleDescription], CAST([DaysUtilizaed] as int)as [DaysUtilizaed],    
    [FleetName],[LicensePlate],[OrgName]    
    FROM #tblVehicles GROUP BY [VehicleId], [VehicleDescription], [WeekDays], [DaysUtilizaed],[FleetName],[LicensePlate],[OrgName]    
    ) as a    
    pivot    
    (    
  MAX([DaysUtilizaed]) for [dt] in (' + @dates + N')    
    ) as pvt ORDER BY pvt.VehicleDescription  '    
INSERT INTO @tblResults (VehicleId,VehicleDescription,FleetName,LicensePlate,OrgName,date1,date2,date3,date4,date5,date6,date7)    
EXEC sp_executesql @sql    
UPDATE @tblResults SET RepType =1 WHERE RepType IS NULL    
    
--get the number of trips    
SET @sql = N'select * from (    
    select  WeekDays AS [dt],[VehicleId], [VehicleDescription], CAST([NoofTrips] as int)as [NoofTrips],    
    [FleetName],[LicensePlate],[OrgName]    
    FROM #tblVehicles GROUP BY [VehicleId], [VehicleDescription], [WeekDays], [NoofTrips] ,[FleetName],[LicensePlate],[OrgName]    
    ) as a    
    pivot    
    (    
  sum([NoofTrips]) for [dt] in (' + @dates + N')    
    ) as pvt ORDER BY pvt.VehicleDescription  '    
INSERT INTO @tblResults (VehicleId,VehicleDescription,FleetName,LicensePlate,OrgName,date1,date2,date3,date4,date5,date6,date7)    
EXEC sp_executesql @sql    
UPDATE @tblResults SET RepType =2 WHERE RepType IS NULL    
    
--get the distance    
SET @sql = N'select * from (    
    select WeekDays AS [dt],[VehicleId], [VehicleDescription], CAST([Distance] as int)as [Distance],    
    [FleetName],[LicensePlate],[OrgName]    
    FROM #tblVehicles GROUP BY [VehicleId], [VehicleDescription], [WeekDays], [Distance],[FleetName],[LicensePlate],[OrgName]     
    ) as a    
    pivot    
    (    
  sum([Distance]) for [dt] in (' + @dates + N')    
    ) as pvt ORDER BY pvt.VehicleDescription  '    
INSERT INTO @tblResults (VehicleId,VehicleDescription,FleetName,LicensePlate,OrgName,date1,date2,date3,date4,date5,date6,date7)    
EXEC sp_executesql @sql    
UPDATE @tblResults SET RepType =3 WHERE RepType IS NULL    
    
--get the RUNNING TIME    
SET @sql = N'select * from (    
    select WeekDays AS [dt],[VehicleId], [VehicleDescription],ISNULL(dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(RunningTime,0)),0) as [FormatedRunning],    
    [FleetName],[LicensePlate],[OrgName]    
    FROM #tblVehicles GROUP BY [VehicleId], [VehicleDescription], [WeekDays], [RunningTime] ,[FleetName],[LicensePlate],[OrgName]    
    ) as a    
    pivot    
    (    
  MAX([FormatedRunning]) for [dt] in (' + @dates + N')    
    ) as pvt ORDER BY pvt.VehicleDescription  '    
INSERT INTO @tblResults (VehicleId,VehicleDescription,FleetName,LicensePlate,OrgName,date1,date2,date3,date4,date5,date6,date7)    
EXEC sp_executesql @sql    
UPDATE @tblResults SET RepType =4 WHERE RepType IS NULL    
DECLARE @INTINC TINYINT=0    
SET @dtFromDate=DATEADD(D,-7,@dtFromDate)    
WHILE EXISTS(SELECT VehicleId FROM @tblResults WHERE Summary IS NULL)    
BEGIN    
 DECLARE @REPTYPE TINYINT=NULL,@BIGVEHID BIGINT=NULL,@VCVALUE VARCHAR(20)=NULL    
 SELECT TOP 1 @REPTYPE=RepType,@BIGVEHID =VehicleId FROM @tblResults WHERE Summary IS NULL    
 --UPDATE THE UTILIZATION DAYS SUMMARY    
 IF(@REPTYPE=1)    
  BEGIN    
   SELECT @VCVALUE=ISNULL(SUM(DaysUtilizaed),0) FROM #tblVehicles WHERE VehicleId =@BIGVEHID GROUP BY VehicleId    
   UPDATE @tblResults SET Summary =@VCVALUE     
    WHERE RepType=@REPTYPE AND VehicleId =@BIGVEHID AND Summary IS NULL    
  END    
 --UPDATE THE NOOFTRIPS SUMMARY    
 ELSE IF(@REPTYPE=2)    
  BEGIN    
   SELECT @VCVALUE=ISNULL(SUM(NoofTrips),0) FROM #tblVehicles WHERE VehicleId =@BIGVEHID GROUP BY VehicleId    
   UPDATE @tblResults SET Summary = @VCVALUE    
    WHERE RepType=@REPTYPE AND VehicleId =@BIGVEHID AND Summary IS NULL    
  END    
 --UPDATE THE DISTANCE SUMMARY    
 ELSE IF(@REPTYPE=3)    
  BEGIN    
   SELECT @VCVALUE=ISNULL(SUM(Distance),0) FROM #tblVehicles WHERE VehicleId =@BIGVEHID GROUP BY VehicleId    
   UPDATE @tblResults SET Summary = @VCVALUE    
    WHERE RepType=@REPTYPE AND VehicleId =@BIGVEHID AND Summary IS NULL    
  END    
 --UPDATE THE RUNNING TIME SUMMARY    
 ELSE IF(@REPTYPE=4)    
  BEGIN    
   SELECT @VCVALUE=dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(SUM(RunningTime),0)) FROM #tblVehicles WHERE VehicleId =@BIGVEHID GROUP BY VehicleId    
   UPDATE @tblResults SET Summary = @VCVALUE    
    WHERE RepType=@REPTYPE AND VehicleId =@BIGVEHID AND Summary IS NULL        
   SET @INTINC=@INTINC+1     
  END     
      
END    
DECLARE @intDistance int=null,@intTrips int=null,@intVehicle int=null,@intDays int=null    
SELECT @intDays=SUM(ISNULL(CAST(Summary AS INT),0)) FROM @tblResults WHERE RepType=1    
SELECT @intTrips=SUM(ISNULL(CAST(Summary AS INT),0)) FROM @tblResults WHERE RepType=2    
SELECT @intDistance=SUM(ISNULL(CAST(Summary AS INT),0)) FROM @tblResults WHERE RepType=3    
SELECT @intVehicle=COUNT(ISNULL(VehicleId,0)) FROM @tblResults WHERE RepType=4    
    
SELECT @VCVALUE=dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(sum(RunningTime),0)) from #tblVehicles     
    
    
SELECT VehicleId,VehicleDescription,LicensePlate,FleetName,OrgName,ISNULL(Date1,0) as Date1,    
 ISNULL(date2 ,0) as Date2,ISNULL(Date3,0) as Date3 ,ISNULL(Date4,0) as Date4,ISNULL(Date5,0) as Date5,    
 ISNULL(Date6,0) as Date6,ISNULL(Date7,0) as Date7,RepType,Summary,@VCVALUE AS TotRunning,  
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,  
 PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@DTLOOPFROMDATE,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())  
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate     
  FROM @tblResults       
     
SELECT CONVERT(VARCHAR,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,WeekDays)),106) AS WeekDays,@DistanceCaptionPrefix AS DistanceCaption,@intDays AS TotDays,    
 @intTrips as TotTrips,  
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,@intDistance)) as TotDistance,  
 @intVehicle as TotVeh    
FROM #tblVehicles GROUP BY WeekDays     
    
SELECT dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(sum(RunningTime),0)) AS RunningTime FROM #tblVehicles GROUP BY WeekDays     
    
DROP TABLE #tblVehicles    
    
    
END    
    
    
--BEGIN    
    
--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 = @bigQueryingUser    
    
-- --SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))    
-- --SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))       
    
--CREATE TABLE #tblVehicles    
--(    
-- ProcessId int identity(1,1),    
-- VehicleId bigint,    
-- VehicleDescription varchar(50),    
-- LicensePlate varchar(50),    
-- Vin varchar(50),    
-- Boxid bigint,    
-- NoofTrips int,    
-- Distance int,    
-- RunningTime INT,     
-- DaysUtilizaed TINYINT,    
-- FleetName varchar(50),    
-- OrgName varchar(50),    
-- WeekDays datetime,    
-- ToWeekdays datetime    
--)    
--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    
--  )    
--DECLARE @dtFromDate DATETIME=@dtStartDate    
--DECLARE @dtToDate DATETIME=@dtEndDate    
    
    
--WHILE CONVERT(DATE,@dtFromDate)<=CONVERT(DATE,@dtToDate)    
-- BEGIN    
--  DECLARE @DTLOOPFROMDATE DATETIME =NULL,@DTLOOPTODATE DATETIME =NULL    
        
--  SET @dtFromDate =CONVERT(DATE,@dtFromDate)    
      
--  SELECT @DTLOOPFROMDATE= DATEADD(HOUR,@HoursToBeAdded*-1,DATEADD(MINUTE,@MinsToBeAdded*-1,@dtFromDate)),    
--    @DTLOOPTODATE=DATEADD(HOUR,@HoursToBeAdded*-1,DATEADD(MINUTE,@MinsToBeAdded*-1,DATEADD(D,1,@dtFromDate)))    
      
--  INSERT INTO #tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin,FleetName,OrgName,WeekDays,ToWeekdays)    
--   SELECT VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin,f.FleetName,O.OrganizationName,@DTLOOPFROMDATE,@DTLOOPTODATE        
--   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 V.OrganizationId =@bigOrganizationID AND F.OrganizationId =@bigOrganizationID)    
--    AND (@bigFleetID IS NULL OR F.FleetId=@bigFleetID)    
--    AND (@intBoxID IS NULL OR VA.BoxId=@intBoxID)    
--    ORDER BY BI.BOXID    
--  SET @dtFromDate=DATEADD(D,1,@dtFromDate)    
-- END     
     
    
     
--DECLARE @ProcessId int  =(SELECT MIN(ProcessId) FROM #tblVehicles)     
--WHILE @ProcessId IS NOT NULL    
-- BEGIN    
--  DECLARE @intBoxLoop int = NULL,@dtDateEndLoop datetime=NULL,@dtDateLoop DATETIME =null    
--  SELECT @intBoxLoop=Boxid,@dtDateEndLoop=ToWeekdays,@dtDateLoop=WeekDays  FROM #tblVehicles WHERE ProcessId=@ProcessId         
--  --CALCULATE THE DISTANCE    
--  UPDATE #tblVehicles SET Distance =(SELECT ISNULL(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),0)  AS DISTANCE    
--  FROM rvlfMsgInHst M       
--   WHERE  (M.BoxId= @intBoxLoop)        
--    AND OriginDateTime BETWEEN @dtDateLoop AND @dtDateEndLoop     
--    AND CustomProp LIKE '%Odometer%' AND BoxMsgInTypeId in(2,3))    
--   WHERE Boxid =@intBoxLoop AND Distance IS NULL AND WeekDays =@dtDateLoop     
       
--  --CALCULATE THE UTILIZATED DAYS    
--  UPDATE #tblVehicles SET DaysUtilizaed =(SELECT CAST(COUNT(Actions) as varchar) FROM (SELECT COUNT(BoxId) AS Actions     
--   FROM rvlfMsgInHst      
--    WHERE BoxId=@intBoxLoop          
--     AND BoxMsgInTypeId IN (2,3)    
--     AND OriginDateTime BETWEEN @dtDateLoop AND @dtDateEndLoop           
--    GROUP BY CONVERT(DATE,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,OriginDateTime))))AS A)    
--   WHERE Boxid =@intBoxLoop AND DaysUtilizaed IS NULL AND WeekDays =@dtDateLoop     
    
-- IF EXISTS(SELECT Boxid  FROM #tblVehicles WHERE DaysUtilizaed=1 AND Boxid=@intBoxLoop AND WeekDays=@dtDateLoop)    
--  BEGIN     
--  --CALCULATE THE NOOFTRIPS,RUNNING TIME AND IDLING TIME        
--  DELETE FROM @tblMessageForProcessingTrip     
--  DECLARE @DTFIRST DATETIME=NULL,@DTEND DATETIME=NULL    
--   --FIND THE FIRST IGNITION ON TIME BETWEEN THE FROM AND TO TIME    
--  SELECT TOP 1 @DTFIRST=OriginDateTime FROM rvlfMsgInHst WHERE Boxid=@intBoxLoop  AND BoxMsgInTypeId=2       
--    AND OriginDateTime BETWEEN @dtDateLoop AND @dtDateEndLoop     
--    AND cast( SUBSTRING(sensormask,6,1) as bit) = 1    
--    ORDER BY OriginDateTime ASC    
--  SELECT TOP 1 @DTEND=OriginDateTime FROM rvlfMsgInHst WHERE Boxid=@intBoxLoop AND BoxMsgInTypeId=3         
--    AND OriginDateTime BETWEEN @dtDateLoop AND @dtDateEndLoop     
--    AND cast( SUBSTRING(sensormask,6,1) as bit) = 0    
--    ORDER BY OriginDateTime DESC     
    
--  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 h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId IN (2,3,9)    
--      AND 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 @DTFIRST and @DTEND             
--      AND h.BoxID = @intBoxLoop    
--     ORDER BY h.origindatetime ASC         
         
-- DECLARE @intIterator int=NULL    
-- DECLARE @dtOriginDateTime datetime=NULL    
-- DECLARE @tiBoxMsgInTypeId tinyint=NULL    
-- DECLARE @bitIgnitionStatus bit=NULL    
-- DECLARE @bigTripID INT=0    
-- SELECT @intIterator = MIN(ProcessorID) FROM @tblMessageForProcessingTrip WHERE TripId is NULL    
-- WHILE @intIterator IS NOT NULL    
--  BEGIN    
--   SET @dtOriginDateTime = NULL; SET @tiBoxMsgInTypeId = NULL;     
--   SET @bitIgnitionStatus = NULL;     
--   DECLARE @dtEndTrip datetime=null;    
--   declare @bitIsTripClosed bit=0;declare @intIdlingDuration int=0;    
--   declare @dtNextStartTime datetime=null;declare @vcEndAddress varchar(300)=null    
--   SELECT  @dtOriginDateTime = OriginDateTime,    
--     @tiBoxMsgInTypeId = BoxMsgInTypeId,    
--     @bitIgnitionStatus = IgnitionStatus    
          
--   FROM @tblMessageForProcessingTrip WHERE ProcessorID=@intIterator and TripId is NULL    
    
--   IF(@bitIgnitionStatus=1 AND @tiBoxMsgInTypeId=2)    
--    BEGIN    
--     DECLARE @DTENDTIME DATETIME=NULL    
--    --NEXT IGNITION TIME         
--     SELECT TOP 1 @dtNextStartTime=OriginDateTime,@bitIsTripClosed=1 FROM @tblMessageForProcessingTrip     
--      WHERE BoxMsgInTypeId=2 AND Boxid =@intBoxLoop  AND OriginDateTime>@dtOriginDateTime     
          
--     IF(@dtNextStartTime IS NOT NULL)    
--      BEGIN    
--       SELECT TOP 1 @DTENDTIME=OriginDateTime,@bitIsTripClosed=1    
--        FROM @tblMessageForProcessingTrip     
--        WHERE BoxMsgInTypeId=3 AND Boxid =@intBoxLoop AND OriginDateTime>=@dtOriginDateTime     
--         AND OriginDateTime<@dtNextStartTime    
--      END    
--     ELSE    
--      BEGIN    
--       SELECT TOP 1 @DTENDTIME=OriginDateTime,@bitIsTripClosed=1    
--        FROM @tblMessageForProcessingTrip     
--        WHERE BoxMsgInTypeId=3 AND Boxid =@intBoxLoop AND OriginDateTime>@dtOriginDateTime    
--      END          
                    
--    SET @bigTripID=@bigTripID+1    
--    UPDATE #tblVehicles SET NoofTrips =ISNULL(NoofTrips,0)+CASE WHEN @DTENDTIME IS NULL THEN 0 ELSE 1 END,    
--     RunningTime=ISNULL(RunningTime,0)+ CASE WHEN @DTENDTIME IS NULL THEN 0 ELSE DATEDIFF(SS,@dtOriginDateTime,@DTENDTIME) END    
--    WHERE Boxid=@intBoxLoop AND WeekDays=@dtDateLoop     
--    END     
--    UPDATE @tblMessageForProcessingTrip SET TripId = @bigTripID where Boxid=@intBoxLoop AND OriginDateTime>=@dtOriginDateTime AND OriginDateTime<=@DTENDTIME     
       
--    SELECT @intIterator = MIN(ProcessorID) FROM @tblMessageForProcessingTrip WHERE ProcessorID > @intIterator and TripId is NULL    
--  END           
-- END          
--  SELECT @ProcessId=MIN(ProcessId) FROM #tblVehicles WHERE ProcessId >@ProcessId     
-- END    
     
--DECLARE @tblResults table    
--(    
-- VehicleId bigint,    
-- VehicleDescription varchar(50),    
-- LicensePlate varchar(50),    
-- FleetName varchar(50),    
-- OrgName varchar(50),    
-- Date1 varchar(50),    
-- Date2 varchar(50),    
-- Date3 varchar(50),    
-- Date4 varchar(50),    
-- Date5 varchar(50),    
-- Date6 varchar(50),    
-- Date7 varchar(50),    
-- RepType tinyint,    
-- Summary varchar(20)    
--)    
    
--DECLARE @sql NVARCHAR(MAX)    
    
--DECLARE @dates NVARCHAR(MAX)    
    
--SET @dates = STUFF((SELECT CAST(',' AS VARCHAR(MAX)) + QUOTENAME([dt])    
--FROM (SELECT  WeekDays AS [dt] FROM #tblVehicles GROUP BY WeekDays) AS a    
--ORDER BY [dt] FOR XML PATH('')), 1, 1, '')    
----get the Utilized days    
--SET @sql = N'select * from (    
--    select WeekDays AS [dt],[VehicleId], [VehicleDescription], CAST([DaysUtilizaed] as int)as [DaysUtilizaed],    
--    [FleetName],[LicensePlate],[OrgName]    
--    FROM #tblVehicles GROUP BY [VehicleId], [VehicleDescription], [WeekDays], [DaysUtilizaed],[FleetName],[LicensePlate],[OrgName]    
--    ) as a    
--    pivot    
--    (    
--  MAX([DaysUtilizaed]) for [dt] in (' + @dates + N')    
--    ) as pvt ORDER BY pvt.VehicleDescription  '    
--INSERT INTO @tblResults (VehicleId,VehicleDescription,FleetName,LicensePlate,OrgName,date1,date2,date3,date4,date5,date6,date7)    
--EXEC sp_executesql @sql    
--UPDATE @tblResults SET RepType =1 WHERE RepType IS NULL    
    
----get the number of trips    
--SET @sql = N'select * from (    
--    select  WeekDays AS [dt],[VehicleId], [VehicleDescription], CAST([NoofTrips] as int)as [NoofTrips],    
--    [FleetName],[LicensePlate],[OrgName]    
--    FROM #tblVehicles GROUP BY [VehicleId], [VehicleDescription], [WeekDays], [NoofTrips] ,[FleetName],[LicensePlate],[OrgName]    
--    ) as a    
--    pivot    
--    (    
--  sum([NoofTrips]) for [dt] in (' + @dates + N')    
--    ) as pvt ORDER BY pvt.VehicleDescription  '    
--INSERT INTO @tblResults (VehicleId,VehicleDescription,FleetName,LicensePlate,OrgName,date1,date2,date3,date4,date5,date6,date7)    
--EXEC sp_executesql @sql    
--UPDATE @tblResults SET RepType =2 WHERE RepType IS NULL    
    
----get the distance    
--SET @sql = N'select * from (    
--    select WeekDays AS [dt],[VehicleId], [VehicleDescription], CAST([Distance] as int)as [Distance],    
--    [FleetName],[LicensePlate],[OrgName]    
--    FROM #tblVehicles GROUP BY [VehicleId], [VehicleDescription], [WeekDays], [Distance],[FleetName],[LicensePlate],[OrgName]     
--    ) as a    
--    pivot    
--    (    
--  sum([Distance]) for [dt] in (' + @dates + N')    
--    ) as pvt ORDER BY pvt.VehicleDescription  '    
--INSERT INTO @tblResults (VehicleId,VehicleDescription,FleetName,LicensePlate,OrgName,date1,date2,date3,date4,date5,date6,date7)    
--EXEC sp_executesql @sql    
--UPDATE @tblResults SET RepType =3 WHERE RepType IS NULL    
    
----get the RUNNING TIME    
--SET @sql = N'select * from (    
--    select WeekDays AS [dt],[VehicleId], [VehicleDescription],ISNULL(dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(RunningTime,0)),0) as [FormatedRunning],    
--    [FleetName],[LicensePlate],[OrgName]    
--    FROM #tblVehicles GROUP BY [VehicleId], [VehicleDescription], [WeekDays], [RunningTime] ,[FleetName],[LicensePlate],[OrgName]    
--    ) as a    
--    pivot    
--    (    
--  MAX([FormatedRunning]) for [dt] in (' + @dates + N')    
--    ) as pvt ORDER BY pvt.VehicleDescription  '    
--INSERT INTO @tblResults (VehicleId,VehicleDescription,FleetName,LicensePlate,OrgName,date1,date2,date3,date4,date5,date6,date7)    
--EXEC sp_executesql @sql    
--UPDATE @tblResults SET RepType =4 WHERE RepType IS NULL    
--DECLARE @INTINC TINYINT=0    
--SET @dtFromDate=DATEADD(D,-7,@dtFromDate)    
--WHILE EXISTS(SELECT VehicleId FROM @tblResults WHERE Summary IS NULL)    
--BEGIN    
-- DECLARE @REPTYPE TINYINT=NULL,@BIGVEHID BIGINT=NULL,@VCVALUE VARCHAR(20)=NULL    
-- SELECT TOP 1 @REPTYPE=RepType,@BIGVEHID =VehicleId FROM @tblResults WHERE Summary IS NULL    
-- --UPDATE THE UTILIZATION DAYS SUMMARY    
-- IF(@REPTYPE=1)    
--  BEGIN    
--   SELECT @VCVALUE=ISNULL(SUM(DaysUtilizaed),0) FROM #tblVehicles WHERE VehicleId =@BIGVEHID GROUP BY VehicleId    
--   UPDATE @tblResults SET Summary =@VCVALUE     
--    WHERE RepType=@REPTYPE AND VehicleId =@BIGVEHID AND Summary IS NULL    
--  END    
-- --UPDATE THE NOOFTRIPS SUMMARY    
-- ELSE IF(@REPTYPE=2)    
--  BEGIN    
--   SELECT @VCVALUE=ISNULL(SUM(NoofTrips),0) FROM #tblVehicles WHERE VehicleId =@BIGVEHID GROUP BY VehicleId    
--   UPDATE @tblResults SET Summary = @VCVALUE    
--    WHERE RepType=@REPTYPE AND VehicleId =@BIGVEHID AND Summary IS NULL    
--  END    
-- --UPDATE THE DISTANCE SUMMARY    
-- ELSE IF(@REPTYPE=3)    
--  BEGIN    
--   SELECT @VCVALUE=ISNULL(SUM(Distance),0) FROM #tblVehicles WHERE VehicleId =@BIGVEHID GROUP BY VehicleId    
--   UPDATE @tblResults SET Summary = @VCVALUE    
--    WHERE RepType=@REPTYPE AND VehicleId =@BIGVEHID AND Summary IS NULL    
--  END    
-- --UPDATE THE RUNNING TIME SUMMARY    
-- ELSE IF(@REPTYPE=4)    
--  BEGIN    
--   SELECT @VCVALUE=dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(SUM(RunningTime),0)) FROM #tblVehicles WHERE VehicleId =@BIGVEHID GROUP BY VehicleId    
--   UPDATE @tblResults SET Summary = @VCVALUE    
--    WHERE RepType=@REPTYPE AND VehicleId =@BIGVEHID AND Summary IS NULL        
--   SET @INTINC=@INTINC+1     
--  END     
      
--END    
--DECLARE @intDistance int=null,@intTrips int=null,@intVehicle int=null,@intDays int=null    
--SELECT @intDays=SUM(ISNULL(CAST(Summary AS INT),0)) FROM @tblResults WHERE RepType=1    
--SELECT @intTrips=SUM(ISNULL(CAST(Summary AS INT),0)) FROM @tblResults WHERE RepType=2    
--SELECT @intDistance=SUM(ISNULL(CAST(Summary AS INT),0)) FROM @tblResults WHERE RepType=3    
--SELECT @intVehicle=COUNT(ISNULL(VehicleId,0)) FROM @tblResults WHERE RepType=4    
    
--SELECT @VCVALUE=dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(sum(RunningTime),0)) from #tblVehicles     
    
    
--SELECT VehicleId,VehicleDescription,LicensePlate,FleetName,OrgName,ISNULL(Date1,0) as Date1,    
-- ISNULL(date2 ,0) as Date2,ISNULL(Date3,0) as Date3 ,ISNULL(Date4,0) as Date4,ISNULL(Date5,0) as Date5,    
-- ISNULL(Date6,0) as Date6,ISNULL(Date7,0) as Date7,RepType,Summary,@VCVALUE AS TotRunning FROM @tblResults       
     
--SELECT CONVERT(VARCHAR,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,WeekDays)),106) AS WeekDays,@DistanceCaptionPrefix AS DistanceCaption,@intDays AS TotDays,    
-- @intTrips as TotTrips,@intDistance as TotDistance,@intVehicle as TotVeh    
--FROM #tblVehicles GROUP BY WeekDays     
    
--SELECT dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(sum(RunningTime),0)) AS RunningTime FROM #tblVehicles GROUP BY WeekDays     
    
--DROP TABLE #tblVehicles    
    
--END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFleetUtilizationSummary]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetFleetUtilizationSummary]        
 @bigOrganizationID bigint=null,        
 @bigFleetID bigint = NULL,        
 @intBoxID varchar(max)=null,        
 @dtStartDate datetime=null,        
 @dtEndDate datetime=null,        
 @bigQueryingUser bigint=null        
        
AS        
/****************************************************************************************************************/        
-- Name  : [rvlf_sp_GetFleetUtilizationSummary] 6,8,NULL,'2013-09-23 08:00:00 AM','2013-09-23 08:00:00 PM',94      
-- Description : To get the Fleet utiliozation summary details        
-- Author  : Narayanasamy        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--          : 20-Jan-2011 VN Created         
--          : 10-Aug-2011 Ranjith Date Format Included      
--          : 30-Nov-2011 Sakthi Distance calculation based on organization  
--			: 27-Sep-2013 Gopal Added Violations field
/****************************************************************************************************************/        
BEGIN        
SET NOCOUNT ON      
      
 Declare @dtFDate datetime =@dtStartDate      
 Declare @dtEDate datetime =@dtEndDate      
 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 = @bigQueryingUser        
          
 IF @bigFleetID IS NULL        
 BEGIN        
   SELECT @bigFleetID=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 = @bigQueryingUser        
            
            
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))        
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))            
        
DECLARE @tblVehicles TABLE        
(        
 VehicleId bigint,        
 VehicleDescription varchar(50),        
 LicensePlate varchar(50),        
 Vin varchar(50),        
 Boxid bigint,        
 NoofTrips int,        
 Distance int,        
 RunningTime INT,        
 IdlingTime INT,        
 DaysUtilizaed varchar(30),        
 FleetName varchar(50),
  Violations int         
)        
      
 DECLARE @TBLSTART TABLE        
 (        
  Processid bigint identity(1,1),        
  Boxid int,        
  StartTime datetime,        
  Running int,        
  tripId int        
 )        
         
 DECLARE @TBLSTOP TABLE        
 (        
  Boxid int,        
  StopTime datetime,        
  tripId 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 (@bigFleetID IS NULL OR @bigFleetID='' OR F.FleetId=@bigFleetID)        
 --AND (@intBoxID IS NULL OR @intBoxID='' OR VA.BoxId=@intBoxID)        
 AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR VA.BoxId IN (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))    
 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 DELTAILS        
 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       
              
    -- GET THE IGNITION ON DETAILS        
    DELETE FROM @TBLSTART             
    INSERT INTO @TBLSTART (Boxid,StartTime)        
    SELECT @intBoxLoop,OriginDateTime FROM @tblMessageForProcessingTrip               
    WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId IN(2)        
    AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip         
    WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)        
    AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip         
    WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)          
    AND IgnitionStatus=1 AND CustomProp LIKE '%SENSOR_NUM=3%'      
                
    --GET THE IGNITION OFF DETAILS           
    DELETE FROM @TBLSTOP         
    INSERT INTO @TBLSTOP (Boxid,StopTime)        
    SELECT @intBoxLoop,OriginDateTime FROM @tblMessageForProcessingTrip          
    WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate         
    AND BoxMsgInTypeId IN(3) AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip         
    WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)        
    AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip         
    WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)          
 AND CustomProp LIKE '%SENSOR_NUM=3%'      
         
    --CHECK THE ONGOING TRIPS             
   IF ((SELECT TOP 1 BoxMsgInTypeId FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) ORDER BY OriginDateTime DESC)=2)            
   BEGIN            
     INSERT INTO @TBLSTART (Boxid,StartTime)            
     SELECT TOP 1 @intBoxLoop,OriginDateTime      
     FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC                 
   IF EXISTS(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)            
        AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC)                    
      BEGIN                    
        INSERT INTO @TBLSTOP (Boxid,StopTime)            
        SELECT TOP 1 @intBoxLoop,OriginDateTime FROM @tblMessageForProcessingTrip       
        WHERE BoxMsgInTypeId NOT IN(19) AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime            
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC            
   END             
   ELSE            
     BEGIN            
        INSERT INTO @TBLSTOP (Boxid,StopTime)            
        SELECT TOP 1 @intBoxLoop,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END      
     END              
   END            
            
    --PREPARE THE TRIPS AND DETAILS         
   DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )         
   DECLARE @DTSTART DATETIME=null,@DTEND DATETIME=null          
   DECLARE @INC INT=1               
   WHILE @LOOP IS NOT NULL        
   BEGIN        
      SELECT TOP 1 @DTSTART=StartTime  FROM @TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR @DTEND='' OR StartTime >@DTEND)            
      SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART         
      UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART         
      UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND                     
      SET @INC =@INC +1              
      SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART              
   END       
             
  --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))  
  
  , Violations  = (select COUNT(*) from @tblMessageForProcessingTrip WHERE  (BoxId= @intBoxLoop and BoxMsgInTypeId in(4,14,15,16,17))      
    AND(OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  )
  WHERE Boxid =@intBoxLoop AND Distance IS NULL        
          
  --CALCULATE THE UTILIZATED 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,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@dtStartDate) AND dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@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 CustomProp LIKE '%SENSOR_NUM=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;%')        
          
  --CALCULATE THE NOOFTRIPS        
  UPDATE @tblVehicles SET NoofTrips =(SELECT COUNT(S.Boxid) FROM @TBLSTART S INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId)        
  WHERE Boxid =@intBoxLoop AND NoofTrips IS NULL        
        
  --RUNNING TIME         
  UPDATE @tblVehicles SET RunningTime=(SELECT SUM(DATEDIFF(S,S.StartTime,ST.StopTime))FROM @TBLSTART S INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId)        
  WHERE Boxid =@intBoxLoop AND RunningTime IS NULL        
          
  --IDLING TIME        
  UPDATE @tblVehicles SET IdlingTime =(SELECT SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7)))AS INT))        
    FROM @tblMessageForProcessingTrip          
    WHERE BoxId=@intBoxLoop         
     AND (OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)        
     AND BoxMsgInTypeId IN (9)        
     AND CustomProp NOT LIKE '%Idling:0%')         
  WHERE Boxid =@intBoxLoop AND IdlingTime IS NULL               
        
  UPDATE @tblVehicles SET IdlingTime =CASE WHEN ISNULL(IdlingTime,0) > ISNULL(RunningTime,0) THEN ISNULL(RunningTime,0) ELSE ISNULL(IdlingTime,0) END        
  WHERE Boxid =@intBoxLoop           
            
  SELECT @intBoxLoop = MIN(Boxid) FROM @tblVehicles WHERE Boxid >@intBoxLoop         
 END        
        
 DECLARE @totRunningTime int=null        
 DECLARE @totIdlingTime int=null        
        
 SELECT @totRunningTime=SUM(ISNULL(RunningTime,0)),@totIdlingTime =SUM(ISNULL(IdlingTime,0)) FROM @tblVehicles          
        
 SELECT VehicleId,VehicleDescription,LicensePlate,ISNULL(NoofTrips,0) as NoofTrips,         
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(Distance  * @ConversionFactor))),'-') as Distance ,        
 ISNULL(dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(RunningTime,0)),'-') as FormatedRunning,        
 ISNULL (dbo.rvlf_fn_GetTimeFromSeconds(IdlingTime),'-')as FormatedIdling,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(10,2)) as idlingpercentage,        
 DaysUtilizaed,CONVERT(varchar,@dtStartDate,106) as StartDate,CONVERT(varchar,@dtEndDate,106) as EndDate,        
 FleetName,dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(@totIdlingTime,0))AS TotIdlingTime,        
 dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(@totRunningTime,0)) AS TotRunningTime,@DistanceCaptionPrefix as DistanceCaption  ,      
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,      
 PasGenerateddate =dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())      
  ,Violations  
 FROM @tblVehicles       
       
SET NOCOUNT OFF        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFleetVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetFleetVehicles]  
 @bigFleetID bigint ,  
 @bigOrganizationID bigint = null,  
 @bitIsAssigned bit = 0,  
 @VehDescPrefix nVarchar(50) = null  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_GetFleetVehicles]  
-- Description : To get assinged and unassinged vehicles  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 24-Jul-2009 MJJC Created Intial Version   
--              :   21-Feb-2010 MJJC Included defalut checking instead of name  
--              :   19-Aug-2010 LK     Removed the Vehicle Display Name  
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
 IF @bitIsAssigned = 0   
 BEGIN  
  SELECT v.VehicleId, v.VehicleDescription,m.ModelName, k.MakeName, v.Color,v.ModelYear, t.VehicleTypeName,   md.CustomerName,
  v.Vin, v.ModelId, v.MakeId, v.VehicleTypeId, v.VehicleDescription as VehicleName, v.Location, v.DisplayName  ,va.BoxId 
  FROM rvlfVehicle v   
  inner join rvlfVehicleAssignment va on v.VehicleId=va.VehicleId
    inner join rvlfMAKDevices md on md.VehicleId = v.VehicleId
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId   
   INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
   LEFT OUTER JOIN rvlfModel m ON v.ModelId = m.ModelId  
   LEFT OUTER JOIN rvlfMake k ON v.MakeId = k.MakeId  
   LEFT OUTER JOIN rvlfVehicleType t ON v.VehicleTypeId = t.VehicleTypeId  
  WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR f.OrganizationId = @bigOrganizationID)  
      AND (@VehDescPrefix IS NULL OR @VehDescPrefix='' OR v.VehicleDescription LIKE @VehDescPrefix + '%')  
   AND f.IsDefault = 1 AND v.VehicleId NOT IN  
    ( SELECT rfv.VehicleId FROM rvlfFleetVehicles rfv WHERE FleetId = @bigFleetID)  
  ORDER BY v.VehicleDescription asc  
    
 END  
   
 ELSE  
 BEGIN  
  -- SELECT the vehicles assinged to the fleet  
  SELECT ROW_NUMBER () over (order by v.vehicledescription asc) as SlNo, v.VehicleId, v.VehicleDescription,   md.CustomerName,
  m.ModelName, k.MakeName, v.Color,v.ModelYear, t.VehicleTypeName,  
  v.Vin, v.ModelId, v.MakeId, v.VehicleTypeId, v.VehicleDescription as VehicleName, v.Location, v.DisplayName,va.BoxId 
  FROM rvlfVehicle v   
  inner join rvlfVehicleAssignment va on v.VehicleId=va.VehicleId
   inner join rvlfMAKDevices md on md.VehicleId = v.VehicleId
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId   
   INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
   LEFT OUTER JOIN rvlfModel m ON v.ModelId = m.ModelId  
   LEFT OUTER JOIN rvlfMake k ON v.MakeId = k.MakeId  
   LEFT OUTER JOIN rvlfVehicleType t ON v.VehicleTypeId = t.VehicleTypeId  
  WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR f.OrganizationId = @bigOrganizationID)  
      AND (@VehDescPrefix IS NULL OR @VehDescPrefix='' OR v.VehicleDescription LIKE @VehDescPrefix + '%')  
   AND f.FleetId = @bigFleetID  
  ORDER BY v.VehicleDescription asc  
 END  
   
 SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFuelConsumptionReportNew]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_GetFuelConsumptionReportNew]   --'0','all','01-jul-2013','all',null,null                  
@bigFleetID bigint = null,                                    
@intBoxID VARCHAR(MAX) = null,                                    
@dtStartDate datetime = null,                                    
@dtEndDate datetime = null,      
@bigOrganizationID bigint = null,                                    
@bigQueryingUser bigint = null    
--@Type bit,    
--@vehicleid varchar(5)=null,    
--@Refid varchar(5) = null,     
--@fromdate varchar(50)=null,                  
--@todate varchar(50)=null,                  
--@userid int=null,                  
--@orgid int=null          
AS          
/**********************************************************************************************************          
Name  : [rvlf_sp_GetFuelConsumptionReportNew] 8,null,'01-Apr-2014','01-MaY-2014',6,1          
Description : To get the Fuel consumption Reports                  
Author  : Kapilraj          
Company  : Angler Technologies                      
History  : <<Date(dd-MON-yyyy)>> Initial Reason                      
**********************************************************************************************************/          
BEGIN              
SET NOCOUNT ON          
            
 --IF @vehicleid = 'all'          
 --BEGIN          
 -- SET @vehicleid = 0          
 --END            
           
 --SET @fromdate = CAST(CONVERT(DATE, @fromdate) AS VARCHAR)          
-- SET @todate = CAST(CONVERT(DATE, @todate) AS VARCHAR)          
          
                             
 Declare @dtFDate datetime =@dtStartDate                                    
 Declare @dtEDate datetime =@dtEndDate                                    
 Declare @fleetName varchar(25)                                    
 DECLARE @HoursToBeAdded INT = 0                                        
 DECLARE @MinsToBeAdded INT = 0                                        
 DECLARE @ConversionFactor numeric (10,2) = 1.0                                        
 DECLARE @DistanceCaptionPrefix varchar(15)                                        
 DECLARE @SpeedCaptionPrefix varchar(15)                                      
 DECLARE @DefaultDateFormat INT = 0                                    
 DECLARE @FuelFactor 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 ,                                          
    @DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,                                        
    @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END,                                    
    @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end) ,                                 
    @FuelFactor =CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 END                               
    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                                    
    INNER JOIN rvlfCurrencyType ct ON ct.CurrencyTypeId=o.CurrencyTypeId                                    
    WHERE up.UserId = @bigQueryingUser      
                            
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                                        
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))       
       
 DECLARE @TblTemp TABLE          
 (                
  VehicleId varchar(50),          
  RefgId int,          
  Dates dateTime,          
  AvgCons float,          
  CurrCons float,          
  Odometer bigint,          
  FuelQty float,          
  Value float,          
  Variance float,          
  IsRef bit          
 )         
 DECLARE @tblSummary TABLE          
 (          
  VehicleId VARCHAR(50),          
  RefgId int,          
  TotalFuelQty float,          
  CurrentConsumption float,          
  MaxOdometer bigint,          
  MinOdometer bigint,          
  TotalDistance float,          
  TotalFuelCost float,          
  IsRef bit          
 )         
        
 declare @tblSec Table           
 (          
  VehicleId VARCHAR(50),          
  RefgId int,          
  VSecMinOdometer bigint,        
  VSecFuelQty float,         
  VFuelCost float,          
  IsRef bit          
 )          
           
 --insert into @tblSec (VehicleId,RefgId,VSecMinOdometer,IsRef)          
           
 --SELECT VehicleId,NULL,MAX(Odometer) as SecODo,0 AS IsRef FROM           
 --rvlfFuelVehicle WHERE [DATE] < CAST(@fromdate AS DATETIME)  AND          
 --IsDelete=0 AND (@VehicleId IS NULL OR @VehicleId = 0 OR VehicleId=@VehicleId)          
 --and Sno in (select max(sno) from rvlfFuelVehicle where [DATE] < CAST(@fromdate AS DATETIME) and IsDelete =0 group by VehicleId)          
 --group by VehicleId           
            
           
 insert into @tblSec (VehicleId,RefgId,VSecMinOdometer,IsRef)          
           
 SELECT RA.VehicleId,RA.RefgId,MAX(Odometer),1 AS IsRef           
 FROM rvlfFuelContainer fc INNER JOIN rvlfRefrigeratorAssignmt RA ON RA.RefgId=fc.RefgId        
 left join rvlfVehicleAssignment VA on RA.VehicleId=VA.VehicleId      
 WHERE fc.[Date] < CAST(@dtStartDate AS DATETIME)           
 AND fc.RefgId IN (SELECT RefgId FROM rvlfRefrigeratorAssignmt    
  WHERE (@intBoxID IS NULL OR @intBoxID = 0 OR VA.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))))           
 and             
 fc.sno IN (SELECT max(sno) FROM rvlfFuelContainer where [DATE] < CAST(@dtStartDate AS DATETIME) and IsDelete = 0 group by RefgId)           
 AND (@intBoxID IS NULL OR @intBoxID = 0 OR RA.VehicleId=@intBoxID)          
 group by Ra.VehicleId,RA.RefgId          
          
           
 INSERT INTO @TblTemp(VehicleId,RefgId,Dates,AvgCons,CurrCons,Odometer,FuelQty,Value,Variance,IsRef)          
 --SELECT VehicleId,NULL,[Date],AvgConsumption,CurrConsumption,Odometer,FuelQty,Value,CAST(Variance AS DECIMAL(10,2)),0 As IsRef FROM           
 --rvlfFuelVehicle WHERE [DATE] BETWEEN CAST(@fromdate AS DATETIME) AND CAST(@todate AS DATETIME) AND          
 --IsDelete=0 AND (@VehicleId IS NULL OR @VehicleId = 0 OR VehicleId=@VehicleId)          
           
 --UNION ALL          
           
 SELECT ra.VehicleId,RA.RefgId,fc.[Date],fc.AvgConsumption,fc.CurrConsumption,fc.Odometer,fc.FuelQty,fc.Value,CAST(fc.Variance AS DECIMAL(10,2)),1 AS IsRef           
 FROM rvlfFuelContainer fc INNER JOIN rvlfRefrigeratorAssignmt RA ON RA.RefgId=fc.RefgId     
 left join rvlfVehicleAssignment VA on RA.VehicleId=VA.VehicleId         
 WHERE fc.[Date] BETWEEN CAST(@dtStartDate AS DATETIME) AND  CAST(@dtEndDate AS DATETIME)          
 AND fc.RefgId IN    
  (SELECT RefgId FROM rvlfRefrigeratorAssignmt RA    
  inner join rvlfVehicleAssignment VA on RA.VehicleId=VA.VehicleId    
  WHERE  (@intBoxID IS NULL OR @intBoxID = 0 OR VA.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))))    
            
 AND (@intBoxID IS NULL OR @intBoxID = 0 OR VA.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))          
          
 INSERT INTO @tblSummary(VehicleId,RefgId,MinOdometer,MaxOdometer,TotalFuelQty,TotalFuelCost,CurrentConsumption,TotalDistance,IsRef)          
 SELECT T.VehicleId,T.RefgId,          
           
         
 CASE WHEN T.RefgId IS NULL THEN           
 (CASE WHEN MIN(Odometer) = MAX(Odometer) THEN MAX(T.prevodov) ELSE MIN(Odometer) END) ELSE          
 (CASE WHEN MIN(Odometer) = MAX(Odometer) THEN MAX(T.prevodor) ELSE MIN(Odometer) END) END aS MinOdometer,            
 MAX(Odometer) MaxOdometer,          
 SUM(FuelQty) TotalFuelQty,SUM(Value) AS TotalFuelCost,           
 CASE WHEN T.RefgId IS NULL            
 THEN             
 (CASE WHEN MIN(Odometer) = MAX(Odometer) THEN MAX(Odometer) - MAX(T.prevodov) ELSE  MAX(Odometer)- MIN(Odometer) END)/           
 cast(ISNULL(SUM(FuelQty),0) as float)                   
 ElsE                 
 cast(ISNULL(SUM(FuelQty),0) as float)/          
 (CASE WHEN MIN(Odometer) = MAX(Odometer) THEN MAX(Odometer) - MAX(T.prevodor) ELSE  MAX(Odometer)- MIN(Odometer) END)  END AS CurrentConsumption,          
                  
 CASE WHEN T.RefgId IS NULL          
 THEN           
 (ISNULL(MAX(Odometer),0) - ISNULL((CASE WHEN MIN(Odometer) = MAX(Odometer) THEN  MAX(T.prevodov) ELSE MIN(Odometer) END),0))           
 ELSE           
 (ISNULL(MAX(Odometer),0) - ISNULL((CASE WHEN MIN(Odometer) = MAX(Odometer) THEN  MAX(T.prevodor)  ELSE MIN(Odometer) END),0))           
 END           
 AS TotalDistance,                  
 CASE WHEN RefgId IS NULL THEN 0 ELSE 1 END AS IsRef          
 from(          
 select VehicleId,RefgId,Dates,AvgCons,CurrCons,Odometer,FuelQty,Value,Variance,IsRef,          
 (select VSecMinOdometer as odo from @tblSec where (RefgId is null and VehicleId=ts.VehicleId and IsRef=ts.IsRef))as prevodov,          
 (select VSecMinOdometer as odo from @tblSec where ((VehicleId=ts.VehicleId and RefgId=ts.RefgId and IsRef=ts.IsRef)))as prevodor           
 from @TblTemp ts              
 ) T                  
  GROUP BY T.Vehicleid,T.RefgId           
            
 DECLARE @tblResult TABLE          
 (          
  VehicleId int,          
  VehicleName VARCHAR(35),          
  RefgId int,          
  RefgName VARCHAR(35),          
  LicensePlate VARCHAR(20),          
  [Date] varchar(30),          
  DateSort datetime,          
  Cost numeric(12,2),          
  Variance numeric(12,2),          
  FuelQty numeric(12,2),          
  CurrConsumption numeric(12,2),          
  --SAvgFuelCons VARCHAR(20),          
  SRAvgFuelCons VARCHAR(20),          
  --STotalDistance VARCHAR(20),          
  SRTotalDistance VARCHAR(20),          
  --SCurrentConsumption VARCHAR(20),          
  SRCurrentConsumption VARCHAR(20),          
  --STotalLitres VARCHAR(20),          
  SRTotalLitres numeric(12,2),          
  --STotalFuelCost VARCHAR(20),          
  SRTotalFuelCost VARCHAR(20),          
  --SMnMxOdometer VARCHAR(20),          
  SRMnMxOdometer VARCHAR(20),          
  NORs int,          
 -- NOVs int,          
  NoRef int,          
  FromDate VARCHAR(22),          
  ToDate VARCHAR(22),          
  ReportGenDate VARCHAR(15)          
 )          
          
 INSERT INTO @tblResult          
 SELECT tp.VehicleId,v.VehicleDescription,r.RefgId,ISNULL(r.RefgName,'NA') as RefgName,v.LicensePlate,          
  tp.Dates AS [Date],tp.Dates AS DateSort,tp.Value AS Cost,          
 tp.Variance,tp.FuelQty,tp.CurrCons AS CurrConsumption,          
 --CASE WHEN tp.IsRef = 0 THEN CAST(ISNULL(tp.AvgCons,0) AS DECIMAL(20,2)) END AS SAvgFuelCons,          
 CASE WHEN tp.IsRef = 1 THEN CAST(ISNULL(tp.AvgCons,0) AS DECIMAL(20,2)) END AS SRAvgFuelCons,          
 --CASE WHEN tp.IsRef = 0 THEN CAST(ISNULL(ab.TotalDistance,0) AS DECIMAL(20,0)) END AS STotalDistance,          
 CASE WHEN tp.IsRef = 1 THEN CAST(ISNULL(ab.TotalDistance,0) AS DECIMAL(20,0)) END AS SRTotalDistance,          
 --CASE WHEN tp.IsRef = 0 THEN CAST(ISNULL(ab.CurrentConsumption,0) AS DECIMAL(20,2)) END AS SCurrentConsumption,          
 CASE WHEN tp.IsRef = 1 THEN CAST(ISNULL(ab.CurrentConsumption,0) AS DECIMAL(20,2)) END AS SRCurrentConsumption,          
 --CASE WHEN tp.IsRef = 0 THEN CAST(ISNULL(ab.TotalFuelQty,0) AS DECIMAL(20,0)) END AS STotalLitres,          
 CASE WHEN tp.IsRef = 1 THEN CAST(ISNULL(ab.TotalFuelQty,0) AS DECIMAL(20,0)) END AS SRTotalLitres,          
 --CASE WHEN tp.IsRef = 0 THEN CAST(ISNULL(ab.TotalFuelCost,0) AS DECIMAL(20,2)) END AS STotalFuelCost,          
 CASE WHEN tp.IsRef = 1 THEN CAST(ISNULL(ab.TotalFuelCost,0) AS DECIMAL(20,2)) END AS SRTotalFuelCost,          
 --CASE WHEN tp.IsRef = 0 THEN CAST(ab.MinOdometer AS VARCHAR)+' - '+ CAST(ab.MaxOdometer AS VARCHAR) END AS SMnMxOdometer,          
 CASE WHEN tp.IsRef = 1 THEN CAST(ab.MinOdometer AS VARCHAR)+' - '+ CAST(ab.MaxOdometer AS VARCHAR) END AS SRMnMxOdometer,          
 CASE WHEN tp.IsRef = 1 THEN 1 END AS NORs,          
 --CASE WHEN tp.IsRef = 0 THEN 1 END AS NOVs,          
 CAST(tp.IsRef AS INT) AS NoRef,          
 CONVERT(VARCHAR(20),@dtStartDate,106) as FromDate,          
 CONVERT(VARCHAR(20),@dtEndDate,106) as ToDate,          
 REPLACE(CONVERT(VARCHAR(15),GETDATE(),106),' ','-') as ReportGenDate          
 FROM @TblTemp tp INNER JOIN rvlfVehicle v ON v.VehicleId = tp.VehicleId --AND RA.IsDelete=0        
 inner join rvlfRefrigeratorAssignmt RA on v.VehicleId= RA.VehicleId  and RA.UnAssignDate is null        
 LEFT OUTER JOIN rvlfRefrigeration r ON RA.RefgId = r.RefgId AND r.IsDelete=0          
-- LEFT OUTER JOIN rvlfContainer c ON c.ContId = RA.ContId          
 OUTER APPLY (SELECT * FROM @tblSummary ts WHERE ts.VehicleId=tp.VehicleId AND ts.IsRef=tp.IsRef) ab          
 ORDER BY v.VehicleDescription,tp.Dates,NoRef ASC           
           
 Update t SET           
 --SAvgFuelCons=(CASE WHEN CAST(AB.sAvg AS VARCHAR) LIKE '0.0%' THEN 'NA' ELSE CAST(AB.sAvg AS VARCHAR) END),          
 SRAvgFuelCons=(CASE WHEN CAST(AB.srAvg AS VARCHAR) LIKE '0.0%' THEN 'NA' ELSE CAST(AB.srAvg AS VARCHAR)  END),          
 --STotalDistance=(CASE WHEN CAST(AB.sTotDist AS VARCHAR) LIKE '0.0%' THEN 'NA' ELSE CAST(AB.sTotDist AS VARCHAR)  END),          
 SRTotalDistance=(CASE WHEN CAST(AB.srTotDist AS VARCHAR) LIKE '0.0%' THEN 'NA' ELSE CAST(AB.srTotDist AS VARCHAR)  END),          
 --SCurrentConsumption=(CASE WHEN CAST(AB.sCCons AS VARCHAR) LIKE '0.0%' THEN 'NA' ELSE CAST(AB.sCCons AS VARCHAR)  END),          
 SRCurrentConsumption=(CASE WHEN CAST(AB.srCCons AS VARCHAR) LIKE '0.0%' THEN 'NA' ELSE CAST(AB.srCCons AS VARCHAR)  END),          
 --STotalLitres=(CASE WHEN CAST(AB.sTotLit AS VARCHAR) LIKE '0.0%' THEN 'NA' ELSE CAST(AB.sTotLit AS VARCHAR)  END),          
 SRTotalLitres=(CASE WHEN CAST(AB.srTotLit AS VARCHAR) LIKE '0.0%' THEN 'NA' ELSE CAST(AB.srTotLit AS VARCHAR)  END),          
 --STotalFuelCost=(CASE WHEN CAST(AB.sTotFC AS VARCHAR) LIKE '0.0%' THEN 'NA' ELSE CAST(AB.sTotFC AS VARCHAR)  END),          
 SRTotalFuelCost=(CASE WHEN CAST(AB.srTotFC AS VARCHAR) LIKE '0.0%' THEN 'NA' ELSE CAST(AB.srTotFC AS VARCHAR)  END),          
 --SMnMxOdometer=(CASE WHEN CAST(ISNULL(AB.sOdometer,0) AS VARCHAR) LIKE '0.0%' THEN 'NA' ELSE CAST(ISNULL(AB.sOdometer,'NA') AS VARCHAR)  END),          
 SRMnMxOdometer=(CASE WHEN CAST(ISNULL(AB.srOdometer,0) AS VARCHAR) LIKE '0.0%' THEN 'NA' ELSE CAST(ISNULL(AB.srOdometer,'NA') AS VARCHAR)  END)          
 FROM @tblResult t INNER JOIN           
 (SELECT VehicleId,MAX(ISNULL(SRAvgFuelCons,0.0)) srAvg,          
 MAX(ISNULL(SRTotalDistance,0.0)) srTotDist,          
 MAX(ISNULL(SRCurrentConsumption,0.0)) srCCons,          
 MAX(ISNULL(SRTotalLitres,0.0)) srTotLit,          
 MAX(ISNULL(SRTotalFuelCost,0.0)) srTotFC,          
 MAX(SRMnMxOdometer) srOdometer           
 FROM @tblResult GROUP BY VehicleId) AB          
 ON AB.VehicleId=t.VehicleId          
           
--select * from @tblResult          
           
 SELECT *,         
 (SELECT CASE WHEN SUM(ISNULL(NORs,0)) = 0 THEN 'NA' ELSE CAST(SUM(ISNULL(NORs,0)) AS VARCHAR) END FROM @tblResult t WHERE t.VehicleId=r.VehicleId) NOR          
 ,Convert(varchar,@dtFDate,@DefaultDateFormat)  as PasStartDate,                                    
 Convert(varchar,@dtEDate,@DefaultDateFormat) as PasEndDate      
 FROM @tblResult r           
           
SET NOCOUNT OFF          
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFuelContainerNames]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE Procedure [dbo].[rvlf_sp_GetFuelContainerNames]        
@bigOrganizationId bigint      
AS        
/******************************************************************************/        
-- Name    : rvlf_sp_GetFuelContainerNames        
-- Description   : To get all the GetFuel         
-- Author    : Kapil        
-- Created Date  : 07-May-2014  
--  Modified Date :         
/******************************************************************************/        
BEGIN        
 SET NOCOUNT ON           
                      
        SELECT  V.RefgId,R.AvgFuel as AvgFuelCons,R.RefgName FROM rvlfRefrigeratorAssignmt V         
       inner join rvlfRefrigeration R ON V.RefgId = R.RefgId and UnAssignDate is null             
       where R.IsDelete=0 and OrganizationId=@bigOrganizationId      
                        
 SET NOCOUNT OFF        
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFuelDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetFuelDetails]  
@Sno BIGINT = NULL,      
@bigOrganizationId bigint 
AS      
/******************************************************************************/      
-- Name  : [rvlf_sp_GetFuelDetails]0,0      
-- Description : To get the fuel details      
--    :        
-- Author  : Kapil.      
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  convert(DECIMAL(10,2),F.Value) AS       
--    : 07-May-2014 Created Intial Version       
/******************************************************************************/      
BEGIN      
      
 IF @Sno = 0 SET @Sno = null  
  IF @Sno is not null 
 BEGIN   
  SELECT F.Sno,F.RefgId,C.RefgName as ContName,Odometer,CONVERT(VARCHAR(11),F.Date,106) AS Date,Date as DateSort,FuelQty,Value,AvgConsumption,CONVERT(DECIMAL(10,2),CurrConsumption)as CurrConsumption,CONVERT(DECIMAL(10,2),Variance) AS Variance,    
  CONVERT(DECIMAL(10,2),ExsLessQty) AS ExsLessQty,      
  CONVERT(DECIMAL(10,2),price) as Price, CONVERT(DECIMAL(10,2),Mileage) as  Mileage      
  From rvlfFuelContainer F INNER JOIN rvlfRefrigeration C ON F.RefgId = C.RefgId            
  where Sno = @Sno AND F.IsDelete =0 and C.OrganizationId=@bigOrganizationId  
 END   
ELSE   
BEGIN     
  SELECT F.Sno,F.RefgId,C.RefgName as ContName,Odometer,CONVERT(VARCHAR(11),F.Date,106) AS Date,Date as DateSort,FuelQty,CONVERT(DECIMAL(10,2),Value) as Value,CONVERT(DECIMAL(10,2),CurrConsumption)as CurrConsumption,CONVERT(DECIMAL(10,2),Variance)     
AS Variance ,CONVERT(DECIMAL(10,2),ExsLessQty) AS  ExsLessQty,      
  CONVERT(DECIMAL(10,2),price) as Price, CONVERT(DECIMAL(10,2),Mileage) as  Mileage      
  From rvlfFuelContainer F INNER JOIN rvlfRefrigeration C ON F.RefgId = C.RefgId         
  where F.IsDelete =0 and C.OrganizationId=@bigOrganizationId  
END    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFuelInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetFuelInfo]        
 @bigFleetID bigint = null,        
 @intBoxID varchar(max) = null,         
 @intBoxMsgInTypeId int=Null,        
 @dtStartDate datetime = null,        
 @dtEndDate datetime = null,         
 @bigOrganizationID bigint = null,        
 @bigQueryingUser bigint = 0         
AS        
/******************************************************************************/        
-- Name  : rvlf_sp_GetFuelInfo 8,null,'','2012/05/23 08:00:00 AM','2012/05/25 20:00:00 PM',6,303        
-- Description : To get the violations messages        
--    :   Pass the valu 0 (Zero) to @bigQueryingUser if the user is angler admin        
-- Author  : S. Jeyanthi.        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>>  Initial Reason        
--    : 18-Nov-2010 SJ    Created Intial Version         
/******************************************************************************/        
BEGIN        
 SET NOCOUNT ON         
         
 ------- Included to get the user prefernces---------------------        
         
 DECLARE @HoursToBeAdded INT = 0        
 DECLARE @MinsToBeAdded INT = 0        
 DECLARE @DistanceCaptionPrefix varchar(15)        
 DECLARE @SpeedCaptionPrefix varchar(15)        
 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 ,        
     @DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(in Miles)' ELSE '(in Kms)' END,        
     @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(in MPH)' ELSE '(in KMPH)' END        
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz        
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser        
            
        
    SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))        
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))        
   
 IF (@intBoxMsgInTypeId IS NULL  OR  @intBoxMsgInTypeId = '')     
  BEGIN        
   SELECT         
    h.MessageInID, h.BoxId,        
    DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime))OriginDateTime,          
    m.BoxMsgInTypeDesc, m.BoxMsgInTypeId, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime)) as OriginDateTimeSort,         
    CASE WHEN h.BoxMsgInTypeId=51 THEN 0 ELSE CAST (CAST(h.Speed AS numeric(10,2)) * @ConversionFactor  as int) END as Speed,          
    --h.CustomProp,         
    --CASE WHEN h.BoxMsgInTypeId = 28  THEN m.BoxMsgInTypeDesc         
    --   WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +        
    --   CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +        
    --  dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'        
    -- ELSE        
    --dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime)END  as MessageDetails,        
    dbo.rvlf_fn_GetFuelDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime) MessageDetails,        
    ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,        
    v.Vin, v.LicensePlate,v.VehicleDescription,Ma.MakeName, Mo.ModelName,v.ModelYear,        
    v.OrganizationId,          
    f.FleetName, g.OrganizationName, @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,        
    CAST( SUBSTRING (h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)+9,CHARINDEX(';',h.CustomProp,        
        CHARINDEX('Odometer=',h.CustomProp,1)) - (CHARINDEX('Odometer=',h.CustomProp,1)+9)) as int) OdometerReading           
   FROM rvlfMsgInHst h         
    INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId        
    INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId        
    INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId        
    LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID         
    INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId        
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId        
    INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId        
    INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId        
    LEFT JOIN rvlfMake Ma on Ma.MakeId =v.MakeId        
    LEFT JOIN rvlfModel Mo on Mo.ModelId=v.ModelId             
   WHERE        
    ( @bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND           
    (@intBoxID IS NULL OR @intBoxID='' OR h.BoxId in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND        
    ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR        
      h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND          
    m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity        
     WHERE ModuleId = 26 and UserGroupId IN         
     (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))        
    AND m.VisibleWeb=1 and (h.CustomProp like '%Fuel%') AND        
    h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)        
  END        
 ELSE IF @intBoxMsgInTypeId = 92 -- Fuel Low        
  BEGIN        
   SELECT         
   h.MessageInID, h.BoxId,        
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime))OriginDateTime,          
   m.BoxMsgInTypeDesc, m.BoxMsgInTypeId, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime)) as OriginDateTimeSort,         
   CASE WHEN h.BoxMsgInTypeId=51 THEN 0 ELSE CAST (CAST(h.Speed AS numeric(10,2)) * @ConversionFactor  as int) END as Speed,            
   dbo.rvlf_fn_GetFuelDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime) MessageDetails,        
   ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,        
   v.Vin, v.LicensePlate,v.VehicleDescription, Ma.MakeName, Mo.ModelName,v.ModelYear,        
   v.OrganizationId,          
   f.FleetName, g.OrganizationName, @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,        
   CAST( SUBSTRING (h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)+9,CHARINDEX(';',h.CustomProp,        
      CHARINDEX('Odometer=',h.CustomProp,1)) - (CHARINDEX('Odometer=',h.CustomProp,1)+9)) as int) OdometerReading         
  FROM rvlfMsgInHst h         
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId        
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId        
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId        
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID         
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId        
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId        
   INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId        
   INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId          
   LEFT JOIN rvlfMake Ma on Ma.MakeId =v.MakeId        
   LEFT JOIN rvlfModel Mo on Mo.ModelId=v.ModelId         
  WHERE        
   ( @bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND           
   (@intBoxID IS NULL OR @intBoxID='' OR h.BoxId in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND        
   ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR        
     h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND          
   m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity        
    WHERE ModuleId = 26 and UserGroupId IN         
    (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))        
   AND m.VisibleWeb=1 and (h.CustomProp like '%Fuel%') AND        
    (h.BoxMsgInTypeId =92) AND        
   h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)        
  END         
 ELSE -- Fuel Drain @intBoxMsgInTypeId=90        
  BEGIN        
           
   SELECT * FROM                 (SELECT a.BoxId,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,a.DateTimeCreated)) OriginDateTime,m.BoxMsgInTypeDesc,m.BoxMsgInTypeId,        
   CASE WHEN h.BoxMsgInTypeId=51 THEN 0 ELSE CAST (CAST(h.Speed AS numeric(10,2)) * @ConversionFactor  as int) END as Speed,        
   --CASE WHEN a.AlarmType = 4 THEN 'Speed:'+ CAST(CAST((CAST(a.[Description] AS numeric(10,0)) *        
   --  @ConversionFactor)AS numeric(10,0)) AS varchar(250)) + ' ' + CASE WHEN @ConversionFactor = 0.62 THEN 'MPH' ELSE 'KMPH' END        
   --  WHEN a.AlarmType IN (5,6) THEN dbo.rvlf_fn_GetAlarmDetails(a.[Description],a.AlarmType,a.BoxId, null, a.DateTimeCreated)        
   --  ELSE a.[Description] END  as 'MessageDetails',        
   dbo.rvlf_fn_GetFuelDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime) MessageDetails,        
   ISNULL(a.StreetAddress,'Address not resolved') as StreetAddress, Vin,LicensePlate,VehicleDescription,MakeName,ModelName,ModelYear,        
   v.OrganizationId,FleetName,OrganizationName,@DistanceCaptionPrefix DistanceCaption,@SpeedCaptionPrefix SpeedCaption,        
   CASE WHEN h.CustomProp Like '%Actual Fuel Drained%' THEN        
    CAST(SUBSTRING (h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)+9,CHARINDEX(';',h.CustomProp,        
       CHARINDEX('Odometer=',h.CustomProp,1)) - (CHARINDEX('Odometer=',h.CustomProp,1)+9)) as int) END OdometerReading,        
   a.AlarmId,  a.AlarmLevelId,         
   CASE WHEN a.AlarmType Not IN (5,6) THEN        
    CASE WHEN v.Notify=1 THEN 'Notify'         
     WHEN v.Warning=1 THEN 'Warning' WHEN v.Critical =1 THEN 'Critical'         
     ELSE 'No Notification is set' END         
    WHEN a.AlarmType IN (5,6) THEN        
     (SELECT CASE WHEN Notify=1 THEN 'Notify'         
     WHEN Warning=1 THEN 'Warning' WHEN Critical =1 THEN 'Critical'         
     ELSE 'No Notification is set' END FROM rvlfOrganizationGeozone WHERE         
     GeozoneNo = CAST(a.[Description] AS Bigint) )        
   END as NotificationType,        
   s.AlarmLevelName Severity        
  FROM rvlfAlarm a INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId        
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId        
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId        
   INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId and f.FleetId = @bigFleetID        
   INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId        
   INNER JOIN rvlfBoxMsgInType m ON a.AlarmType = m.BoxMsgInTypeId           
   INNER JOIN rvlfSeverity s ON a.AlarmLevelId = s.AlarmLevelId        
   LEFT JOIN rvlfMake Ma on Ma.MakeId =v.MakeId        
   LEFT JOIN rvlfModel Mo on Mo.ModelId=v.ModelId        
   LEFT JOIN rvlfMsgInHst h on h.OriginDateTime =a.DateTimeCreated and h.BoxId =a.BoxId and h.BoxMsgInTypeId=A.AlarmType         
  WHERE        
   ( @bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND          
   (@intBoxID IS NULL OR @intBoxID='' OR a.BoxId in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND        
   ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR        
     a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate) AND         
   m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity        
     WHERE ModuleId = 26 and UserGroupId IN         
     (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))AND        
   (@intBoxMsgInTypeId IS NULL OR @intBoxMsgInTypeId='' OR a.AlarmType = @intBoxMsgInTypeId)AND         
    m.VisibleWeb = 1 and         
    a.Description like '%Actual Fuel Drained=%'        
   AND v.OrganizationId = @bigOrganizationID         
   --AND h.CustomProp Like '%Odometer%'         
   ) A         
   --WHERE A.OdometerReading IS NOT NULL        
   ORDER by A.OriginDateTime Desc         
             
  END         
 SET NOCOUNT OFF        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFuelOperationalCost]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetFuelOperationalCost]                                  
@bigFleetID bigint = null,                                
@intBoxID VARCHAR(MAX) = null,                                
@dtStartDate datetime = null,                                
@dtEndDate datetime = null,                                
@fcPerLtrLV decimal(6,2) = 48.0,                                
@fcPerLtrHV decimal(6,2) = 50.0,                                
@distPerLtrLV decimal(6,2) = 10,                            
@distPerLtrHV decimal(6,2) = 8,                                
@bigOrganizationID bigint = 6,                                
@bigQueryingUser bigint = null                        
/*********************************************************************************************************************************************/                                          
-- Procedure Name : rvlf_sp_GetFuelOperationalCost 301,null,'03/28/2014 08:00:00 AM','03/29/2014 08:00:00 AM',288.04,288.04,14.52,20.97,170,502               
-- Description  : To get the ROI Details                                  
-- Author   : Sakthi                                  
-- Company   : Angler Technologies                                          
-- History   : <<Date(dd-MON-yyyy)>> Initial Reason                                          
--     : 13-Mar-2014 Gopal                                    
/*********************************************************************************************************************************************/                                         
AS                                  
BEGIN                                  
SET NOCOUNT ON                               
 -- set @dtStartDate = '01-Apr-2013'                          
  --set @dtEndDate = '01-May-2013'                          
declare @fuelcostperkmLV float                              
declare @fuelcostperkmHV float      
                           
 set @dtEndDate=  dateadd(day,6,@dtStartDate)                    
 Declare @dtFDate datetime =@dtStartDate                              
 Declare @dtEDate datetime =@dtEndDate                              
 Declare @fleetName varchar(25)                              
 DECLARE @HoursToBeAdded INT = 0                                  
 DECLARE @MinsToBeAdded INT = 0                                  
 DECLARE @ConversionFactor numeric (10,2) = 1.0                                  
 DECLARE @DistanceCaptionPrefix varchar(15)                                  
 DECLARE @SpeedCaptionPrefix varchar(15)                                
 DECLARE @DefaultDateFormat INT = 0                              
 DECLARE @FuelFactor numeric (10,2) = 1.0                              
 Declare @FuelCaptionPrefix varchar(10)     
         
    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,                              
    @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end) ,                           
    @FuelCaptionPrefix =CASE WHEN up.Fuel = 0 THEN '(Gallon)' ELSE '(Liter)' END  ,   
    @FuelFactor =CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 END
    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                              
    INNER JOIN rvlfCurrencyType ct ON ct.CurrencyTypeId=o.CurrencyTypeId                              
    WHERE up.UserId = @bigQueryingUser                        
                        
 declare @fcperidlingLV float =  round((3/@FuelFactor),2)              
 declare @fcperidlingHV float =  round((6/@FuelFactor),2)                  
                      
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                                  
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                            
    --select @dtStartDate,@dtEndDate                      
 Set @fcPerLtrLV=(@fcPerLtrLV/@FuelFactor)                
 Set @fcPerLtrHV=(@fcPerLtrHV/@FuelFactor)            
          
 Set @distPerLtrLV=(@distPerLtrLV*@ConversionFactor)                
 Set @distPerLtrHV=(@distPerLtrHV*@ConversionFactor)               
 SET @fuelcostperkmLV = (@fcPerLtrLV/@distPerLtrLV)                            
 SET @fuelcostperkmHV = (@fcPerLtrHV/@distPerLtrHV)             
           
          
            
  declare @tblFuelcost table(                            
  BoxId bigint,                            
  VehicleId int,                            
  VehicleDescription varchar(200),                            
  StartDay Varchar(20),                            
  TotDistance float,                            
  TotIdling bigint,                            
  TotRunning bigint,                              
  DistanceCost numeric(12,2),                            
  IdlingCost numeric(12,2),                            
  Vin varchar(20),                            
  LicensePlate varchar(20),UtilizedDay date,VehicleType varchar(2))                        
    DECLARE @TBLSTART TABLE                                    
 (                                    
  Processid bigint identity(1,1),                                    
  Boxid int,                                    
  StartTime datetime,                                    
  OdoStart bigint,                                 
  StartAddress nvarchar(300),                                    
  Running int,                                    
  idling int,                                    
  Speed int,                                    
  StopInterval int,                                    
  tripId int                                     
 )                                    
                                     
 DECLARE @TBLSTOP TABLE                                    
 (                                    
  Boxid int,                                    
  StopTime datetime,                                    
  OdoEnd bigint,                                    
  EndAddress nvarchar(300),                                    
  tripId int,                                    
  IsTripCompleted bit                                    
 )                   
 DECLARE @TBLDate TABLE                                    
 (                                    
  UtilizedDay date                                       
 )                      
  DECLARE @tblMessageForProcessingTrip TABLE (                                      
  [OriginDateTime] [datetime] NOT NULL,                                      
  [BoxMsgInTypeId] [tinyint] NULL,                                      
  [CustomProp] [varchar](600) NULL,                                        
  [Speed] int NULL,                                      
  [Ignition] bit null,                                        
  [OdoMeter] bigint null                      
 )                      
                     
 DECLARE @tblTripDetailsForTD TABLE(                                    
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,                                    
  [BoxId] [int]  NULL,                                    
  [StartDate] [datetime] NULL,                                    
  [EndDate] [datetime] NULL,                                    
  [OdometerStart] [bigint]  NULL,                                    
  [OdometerEnd] [bigint] NULL,                                    
  [IsTripClosed] [bit] NULL,                                    
  [IdlingDuration] [int] NULL,                                  
  [StopTime] [int] NULL,                    
  [Speed] int NULL,                   
  [RunningTime] int null,                    
  Distance bigint,                  
  UtilizedDay date                    
 )                       
                       
 DECLARE @tblBoxes TABLE (BoxID int)                      
         
 INSERT INTO @tblBoxes (BoxID)                       
 SELECT va.BoxID FROM dbo.rvlfVehicleAssignment va                                       
   INNER JOIN dbo.rvlfVehicle v ON va.VehicleId = v.VehicleId                                      
   INNER JOIN dbo.rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                      
   inner join (select distinct BoxId from rvlfMsgInHst where OriginDateTime between @dtStartDate AND @dtEndDate) Mh                      
on va.BoxId=Mh.BoxId           
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or va.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID                                      
   ORDER BY BoxId                      
                       
                            
  --------------------------Declaration End----------------------------------------                            
                        
  DECLARE @intBoxLooping int                                      
    insert into @TBLDate values(CAST(@dtStartDate as date)),(CAST(DATEADD(day,1,@dtStartDate)as date)),(CAST(DATEADD(day,2,@dtStartDate)as date))                  
 ,(CAST(DATEADD(day,3,@dtStartDate)as date)),(CAST(DATEADD(day,4,@dtStartDate)as date)),(CAST(DATEADD(day,5,@dtStartDate)as date)),(CAST(DATEADD(day,6,@dtStartDate)as date))                  
                  
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes                                      
 WHILE @intBoxLooping IS NOT NULL                                      
   BEGIN                       
   -- GET THE MSGS FOR THE BOXID                                      
    DELETE FROM @tblMessageForProcessingTrip                                           
    INSERT INTO @tblMessageForProcessingTrip(OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,OdoMeter)                                      
      SELECT  h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,CAST(SUBSTRING(sensormask,6,1) as bit),                                      
      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                                                
       FROM dbo.rvlfMsgInHst H                     
        LEFT OUTER JOIN dbo.rvlfLandmark L ON L.LandmarkID=H.LandMarkID                                                                
       WHERE h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                                                
          AND h.BoxID = @intBoxLooping and H.BoxMsgInTypeId not in(20,35)                                             
        ORDER BY h.origindatetime ASC                        
                         
     -- GET THE IGNITION ON DETAILS                                    
    DELETE FROM @TBLSTART                                         
    INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart)                                    
    SELECT @intBoxLooping,OriginDateTime,OdoMeter                                     
     FROM @tblMessageForProcessingTrip                                           
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                                     
   AND BoxMsgInTypeId IN(2)                                    
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                                     
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                                    
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                                     
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                                      
      AND Ignition=1                                    
      AND CustomProp LIKE '%SENSOR_NUM=3%'                        
                                           
                                         
    --GET THE IGNITION OFF DETAILS                                       
    DELETE FROM @TBLSTOP                                     
    INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd)                                    
    SELECT @intBoxLooping,OriginDateTime,OdoMeter                                       
     FROM @tblMessageForProcessingTrip                                      
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                                     
      AND BoxMsgInTypeId IN(3)                                    
      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                                     
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                                    
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                                     
       WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                                      
      AND CustomProp LIKE '%SENSOR_NUM=3%'                                    
                                        
    --CHECK THE ONGOING TRIPS                                     
    IF ((SELECT TOP 1 BoxMsgInTypeId FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) ORDER BY OriginDateTime DESC)=2)                                    
     BEGIN                                    
      INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart)                                    
       SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter                         
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC                                         
     IF EXISTS(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                            
        AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                                    
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC)                                            
      BEGIN                                            
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,IsTripCompleted)                           
        SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,0                                     
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                                    
         AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                                    
         FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC                                    
      END                                     
     ELSE                                    
      BEGIN                                    
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)                                            
        SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                                             
      END                                      
     END                                    
                                             
    --PREPARE THE TRIPS AND DETAILS                                        
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )                                     
    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 @TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                                        
                                          
      IF @DTSTOPSTART IS NOT NULL                                             
       UPDATE top(1) @TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART                                     
                                
      SET @DTSTOPSTART=@DTSTART                                     
      SET @DTEND=NULL                                    
      SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART                                     
                                          
      UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART                                     
   UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND                                      
      UPDATE top(1) @TBLSTART SET Speed =(SELECT MAX(SPEED) FROM @tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),                                    
      idling=(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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9                                     
        AND CustomProp NOT LIKE '%Idling:0;%'),                          
       Running=DATEDIFF(S,@DTSTART,@DTEND)                                    
       WHERE tripId=@INC AND StartTime=@DTSTART                                     
                                           
      SET @INC =@INC +1                     
                         
     SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART                                          
     END                                     
                                               
    --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME                                    
    UPDATE @TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END                                     
   WHERE Running IS NOT NULL                                    
                                        
    --INSERT THE DETAILS IN THE MASTER TABLE                                    
    INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,OdometerStart,                                    
     OdometerEnd,IdlingDuration,Speed, IsTripClosed,StopTime,RunningTime,Distance,UtilizedDay)                                     
    SELECT  isnull(S.Boxid,@intBoxLooping),S.StartTime,ST.StopTime,S.OdoStart,ST.OdoEnd,S.idling,                                    
     S.Speed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running,(ST.OdoEnd-S.OdoStart),dt.UtilizedDay                   
      FROM @TBLSTART S                                    
       INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId right join @TBLDate dt on dt.UtilizedDay=cast(DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),s.StartTime))as date)            
       --cast(s.StartTime as date)                   
                                         
SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping                                    
                                       
   UPDATE @tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM @tblTripDetailsForTD)           
  
    
      
         
          
           
               
   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping                    
   END                  
                        
    --select * from @tblTripDetailsForTD                  
                    
           
             
INSERT INTO @tblFuelcost                              
SELECT TDtls.BoxId,v.VehicleId,V.VehicleDescription,cast(DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),StartDate))as date)as StartDate ,sum(Distance*@ConversionFactor) as Distance,              
sum(isnull(IdlingDuration,0))as Idling,       
 sum(RunningTime) as Running,                            
 (SUM(Distance*@ConversionFactor)*(case when VehicleTypeId=1 then @fuelcostperkmLV else @fuelcostperkmHV end)) as Distancecost,                              
 ((CAST(sum(isnull(IdlingDuration,0)) as float)/CAST(3600 as float)))  *                            
  ((case when VehicleTypeId=1 then @fcPerLtrLV else @fcPerLtrHV end) *               
  (case when VehicleTypeId=1 then @fcperidlingLV else @fcperidlingHV end)) as idlingcost,                
                              
 v.vin,v.LicensePlate , TDtls.UtilizedDay, (case when VehicleTypeId=1 then 'LV' else 'HV' end)                         
 from @tblTripDetailsForTD as TDtls                              
 inner JOIN rvlfBoxId b ON b.BoxId=TDtls.BoxId                            
 inner join rvlfVehicleAssignment va on TDtls.BoxId=va.BoxId                          
 inner join rvlfVehicle v on va.VehicleId=v.VehicleId                             
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=va.VehicleId                              
 --inner join rvlfVehicleType VT on v.VehicleTypeId=VT.VehicleTypeId                              
 WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or TDtls.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                                 
 AND b.OrganizationId=@bigOrganizationID  and                            
 (cast(TDtls.StartDate as date) BETWEEN cast(@dtFDate as date) AND cast(@dtEDate as date) or TDtls.StartDate is null)                             
 group by TDtls.BoxId,v.VehicleId,V.VehicleDescription,cast(DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),StartDate))as date)            
 ,VehicleTypeId,Vin,LicensePlate,TDtls.UtilizedDay                             
                      
                
                  
  Declare @DistanceCostHV numeric(10,2)        
  Declare @DistanceCostLV numeric(10,2)        
  Declare @IdlingCostHV numeric(10,2)        
  Declare @IdlingCostLV numeric(10,2)     
      
 select @DistanceCostHV=SUM(DistanceCostHV),@DistanceCostLV=SUM(DistanceCostLV),@IdlingCostHV=SUM(IdlingCostHV),@IdlingCostLV=SUM(IdlingCostLV) from (    
 select case when  VehicleType='HV' then sum(isnull(DistanceCost,0)) else 0 end as DistanceCostHV,        
 case when  VehicleType='LV' then sum(isnull(DistanceCost,0)) else 0 end as DistanceCostLV,        
 case when VehicleType='HV' then sum(isnull(IdlingCost,0)) else 0 end as IdlingCostHV,        
 case when  VehicleType='LV' then sum(isnull(IdlingCost,0)) else 0 end as IdlingCostLV   from @tblFuelcost group by VehicleType ) as a        
                  
  Select det.UtilizedDay, det.BoxId,det.VehicleId,det.VehicleDescription,ISNULL(det.StartDay,det.UtilizedDay) as StartMonth,                  
  case when isnull((det.TotDistance),0)=0 then '-' else cast((det.TotDistance)as varchar) end as TotDistance,                        
  det.TotIdling as TotIdlingsec ,                  
  case when isnull(det.TotIdling,0)=0 then '-'else CAST( dbo.rvlf_fn_GetTimeFromSeconds(isnull(det.TotIdling,0))as varchar) end as TotIdling,                        
  isnull(det.TotRunning,0) as TotRunningsec,                  
  case when isnull(det.TotRunning,0)=0 then '-' else CAST(dbo.rvlf_fn_GetTimeFromSeconds(isnull(det.TotRunning,0))as varchar)end as TotRunning,                        
  case when isnull(det.DistanceCost,0)=0then '-' else CAST(isnull(det.DistanceCost,0)as varchar) end as DistanceCost                  
  ,case when isnull(det.IdlingCost,0)=0 then '-' else CAST(det.IdlingCost as varchar) end as IdlingCost                  
  ,case when isnull((det.DistanceCost+det.IdlingCost),0)=0 then '-' else CAST((det.DistanceCost+det.IdlingCost)as varchar) end as Totcost,                        
  smry.Vin,smry.LicensePlate,                  
 case when isnull(smry.TotDistanceCost,0)=0 then '-' else CAST(smry.TotDistanceCost as varchar) end as TotDistanceCost,                  
 case when smry.TotIdlingCost=0 then '-' else CAST(smry.TotIdlingCost as varchar) end as TotIdlingCost,                            
 case when isnull(smry.Total,0)=0 then '-' else CAST(smry.Total as varchar) end as Total,        
 @DistanceCostHV as DistanceCostHV,        
 @DistanceCostLV as DistanceCostLV,        
 @IdlingCostHV as IdlingCostHV,        
 @IdlingCostLV as IdlingCostLV,                  
 (@IdlingCostHV + @DistanceCostHV) as TotSumCostHV,    
 (@IdlingCostLV + @DistanceCostLV) as TotSumCostLV,    
  @fcPerLtrLV as fcPerLtrLV,  @fcPerLtrHV as fcPerLtrHV,                            
  @fcperidlingLV as fcperidlingLV, @fcperidlingHV as fcperidlingHV, @distPerLtrLV as distPerLtrLV,@distPerLtrHV as distPerLtrHV,                        
  @DistanceCaptionPrefix as DistanceCaptionPrefix,@SpeedCaptionPrefix as SpeedCaptionPrefix,@FuelCaptionPrefix as FuelCaptionPrefix,                           
  smry.PasStartDate,smry.PasEndDate,smry.PasGenerateddate,        
  case when det.TotRunning=0 or det.TotRunning IS NULL then 0 else 1 end as Utilized ,det.VehicleType                      
  from @tblFuelcost det               
  left join (                        
 Select BoxId,VehicleId,VehicleDescription,Vin,LicensePlate,sum(DistanceCost) as TotDistanceCost,sum(IdlingCost) as TotIdlingCost,                            
 sum(DistanceCost+IdlingCost) as Total ,               
 --@fcPerLtrLV as fcPerLtrLV, @fcPerLtrHV as fcPerLtrHV,                            
 --@fcperidlingLV as fcperidlingLV, @fcperidlingHV as fcperidlingHV,@distPerLtrLV as distPerLtrLV, @distPerLtrHV as distPerLtrHV,                            
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,                              
 Convert(varchar,@dtEDate,@DefaultDateFormat)+' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                
 --'03/23/14  8:00:00 PM' as PasEndDate,                
 PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())                        
 from @tblFuelcost                              
 group by BoxId,VehicleId,VehicleDescription,Vin,LicensePlate                            
 ) as smry on det.BoxId=smry.BoxId                         
 order by BoxId,det.UtilizedDay                          
         
    --select * from @tblFuelcost          
        
              
SET NOCOUNT OFF                                  
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFuelOperationalCost_test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[rvlf_sp_GetFuelOperationalCost_test]
@bigFleetID bigint = null,                        
@intBoxID VARCHAR(MAX) = null,                        
@dtStartDate datetime = null,                        
@dtEndDate datetime = null,                        
@fcPerLtrLV decimal(6,2) = 48.0,                        
@fcPerLtrHV decimal(6,2) = 50.0,                        
@distPerLtrLV decimal(6,2) = 10,                    
@distPerLtrHV decimal(6,2) = 8,                        
@bigOrganizationID bigint = 6,                        
@bigQueryingUser bigint = null                
/*********************************************************************************************************************************************/                                  
-- Procedure Name : rvlf_sp_GetFuelOperationalCost_test 301,null,'03/28/2014 08:00:00 AM','03/29/2014 08:00:00 AM',288.04,288.04,14.52,20.97,170,502       
-- Description  : To get the ROI Details                          
-- Author   : Sakthi                          
-- Company   : Angler Technologies                                  
-- History   : <<Date(dd-MON-yyyy)>> Initial Reason                                  
--     : 13-Mar-2014 Gopal                            
/*********************************************************************************************************************************************/                                 
AS                          
BEGIN                          
SET NOCOUNT ON                       
 -- set @dtStartDate = '01-Apr-2013'                  
  --set @dtEndDate = '01-May-2013'                  
declare @fuelcostperkmLV float                      
declare @fuelcostperkmHV float                    
                   
 set @dtEndDate=  dateadd(day,6,@dtStartDate)            
 Declare @dtFDate datetime =@dtStartDate                      
 Declare @dtEDate datetime =@dtEndDate                      
 Declare @fleetName varchar(25)                      
 DECLARE @HoursToBeAdded INT = 0                          
 DECLARE @MinsToBeAdded INT = 0                          
 DECLARE @ConversionFactor numeric (10,2) = 1.0                          
 DECLARE @DistanceCaptionPrefix varchar(15)                          
 DECLARE @SpeedCaptionPrefix varchar(15)                        
 DECLARE @DefaultDateFormat INT = 0                      
 DECLARE @FuelFactor 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 ,                            
    @DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Kms)' END,                          
    @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' END,                      
    @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end) ,                   
    @FuelFactor =CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 END                 
    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                      
    INNER JOIN rvlfCurrencyType ct ON ct.CurrencyTypeId=o.CurrencyTypeId                      
    WHERE up.UserId = @bigQueryingUser                
                
 declare @fcperidlingLV float =  round((3.02/@FuelFactor),2)      
 declare @fcperidlingHV float =  round((4.54/@FuelFactor),2)          
              
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                          
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                    
    --select @dtStartDate,@dtEndDate              
 Set @fcPerLtrLV=(@fcPerLtrLV/@FuelFactor)        
 Set @fcPerLtrHV=(@fcPerLtrHV/@FuelFactor)    
  
 Set @distPerLtrLV=(@distPerLtrLV*@ConversionFactor)        
 Set @distPerLtrHV=(@distPerLtrHV*@ConversionFactor)       
 SET @fuelcostperkmLV = (@fcPerLtrLV/@distPerLtrLV)                    
 SET @fuelcostperkmHV = (@fcPerLtrHV/@distPerLtrHV)     
   
  select @fcPerLtrHV,@distPerLtrHV,(@fcPerLtrHV/@distPerLtrHV)  
    
  declare @tblFuelcost table(                    
  BoxId bigint,                    
  VehicleId int,                    
  VehicleDescription varchar(200),                    
  StartDay Varchar(20),                    
  TotDistance float,                    
  TotIdling bigint,                    
  TotRunning bigint,                      
  DistanceCost float,                    
  IdlingCost numeric(12,2),                    
  Vin varchar(20),                    
  LicensePlate varchar(20),UtilizedDay date,VehicleType varchar(2))                
    DECLARE @TBLSTART TABLE                            
 (                            
  Processid bigint identity(1,1),                            
  Boxid int,                            
  StartTime datetime,                            
  OdoStart bigint,                         
  StartAddress nvarchar(300),                            
  Running int,                            
  idling int,                            
  Speed int,                            
  StopInterval int,                            
  tripId int                             
 )                            
                             
 DECLARE @TBLSTOP TABLE                            
 (                            
  Boxid int,                            
  StopTime datetime,                            
  OdoEnd bigint,                            
  EndAddress nvarchar(300),                            
  tripId int,                            
  IsTripCompleted bit                            
 )           
 DECLARE @TBLDate TABLE                            
 (                            
  UtilizedDay date                               
 )              
  DECLARE @tblMessageForProcessingTrip TABLE (                              
  [OriginDateTime] [datetime] NOT NULL,                              
  [BoxMsgInTypeId] [tinyint] NULL,                              
  [CustomProp] [varchar](600) NULL,                                
  [Speed] int NULL,                              
  [Ignition] bit null,                                
  [OdoMeter] bigint null              
 )              
             
 DECLARE @tblTripDetailsForTD TABLE(                            
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,                            
  [BoxId] [int]  NULL,                            
  [StartDate] [datetime] NULL,                            
  [EndDate] [datetime] NULL,                            
  [OdometerStart] [bigint]  NULL,                            
  [OdometerEnd] [bigint] NULL,                            
  [IsTripClosed] [bit] NULL,                            
  [IdlingDuration] [int] NULL,                          
  [StopTime] [int] NULL,            
  [Speed] int NULL,                            
  [RunningTime] int null,            
  Distance bigint,          
  UtilizedDay date            
 )               
               
 DECLARE @tblBoxes TABLE (BoxID int)              
                
 INSERT INTO @tblBoxes (BoxID)               
 SELECT va.BoxID FROM dbo.rvlfVehicleAssignment va                               
   INNER JOIN dbo.rvlfVehicle v ON va.VehicleId = v.VehicleId                              
   INNER JOIN dbo.rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId              
   inner join (select distinct BoxId from rvlfMsgInHst where OriginDateTime between @dtStartDate AND @dtEndDate) Mh              
on va.BoxId=Mh.BoxId                              
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or va.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID                              
   ORDER BY BoxId              
               
                    
  --------------------------Declaration End----------------------------------------                    
                
  DECLARE @intBoxLooping int                              
    insert into @TBLDate values(CAST(@dtStartDate as date)),(CAST(DATEADD(day,1,@dtStartDate)as date)),(CAST(DATEADD(day,2,@dtStartDate)as date))          
 ,(CAST(DATEADD(day,3,@dtStartDate)as date)),(CAST(DATEADD(day,4,@dtStartDate)as date)),(CAST(DATEADD(day,5,@dtStartDate)as date)),(CAST(DATEADD(day,6,@dtStartDate)as date))          
          
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes                              
 WHILE @intBoxLooping IS NOT NULL                              
   BEGIN               
   -- GET THE MSGS FOR THE BOXID                              
    DELETE FROM @tblMessageForProcessingTrip                                   
    INSERT INTO @tblMessageForProcessingTrip(OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,OdoMeter)                              
      SELECT  h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,CAST(SUBSTRING(sensormask,6,1) as bit),                              
      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                                        
       FROM dbo.rvlfMsgInHst H             
        LEFT OUTER JOIN dbo.rvlfLandmark L ON L.LandmarkID=H.LandMarkID                                                        
       WHERE h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                                        
          AND h.BoxID = @intBoxLooping and H.BoxMsgInTypeId not in(20,35)                                     
        ORDER BY h.origindatetime ASC                
                 
     -- GET THE IGNITION ON DETAILS                            
    DELETE FROM @TBLSTART                                 
    INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart)                            
    SELECT @intBoxLooping,OriginDateTime,OdoMeter                             
     FROM @tblMessageForProcessingTrip                                   
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                             
   AND BoxMsgInTypeId IN(2)                            
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                            
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                              
      AND Ignition=1                            
      AND CustomProp LIKE '%SENSOR_NUM=3%'                            
                                   
                                 
    --GET THE IGNITION OFF DETAILS                               
    DELETE FROM @TBLSTOP                             
    INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd)                            
    SELECT @intBoxLooping,OriginDateTime,OdoMeter                                
     FROM @tblMessageForProcessingTrip                              
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                             
      AND BoxMsgInTypeId IN(3)                            
      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                            
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                             
       WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                              
      AND CustomProp LIKE '%SENSOR_NUM=3%'                            
                                
    --CHECK THE ONGOING TRIPS                             
    IF ((SELECT TOP 1 BoxMsgInTypeId FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) ORDER BY OriginDateTime DESC)=2)                            
     BEGIN                            
      INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart)                            
       SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter                 
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC                                 
     IF EXISTS(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                    
        AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                            
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC)                                    
      BEGIN                                    
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,IsTripCompleted)                   
        SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,0                             
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                            
         AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                            
         FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC                            
      END                             
     ELSE                            
      BEGIN                            
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)                                    
        SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                                     
      END                              
     END                            
                                     
    --PREPARE THE TRIPS AND DETAILS                                
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )                             
    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 @TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                                
                                  
      IF @DTSTOPSTART IS NOT NULL                                     
       UPDATE top(1) @TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART                             
                                  
      SET @DTSTOPSTART=@DTSTART                             
      SET @DTEND=NULL                            
      SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART                             
                                  
      UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART                             
      UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND                              
      UPDATE top(1) @TBLSTART SET Speed =(SELECT MAX(SPEED) FROM @tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),                            
      idling=(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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9                             
        AND CustomProp NOT LIKE '%Idling:0;%'),                  
       Running=DATEDIFF(S,@DTSTART,@DTEND)                            
       WHERE tripId=@INC AND StartTime=@DTSTART                             
                                   
      SET @INC =@INC +1             
                 
     SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART                                  
     END                             
                                       
    --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME                            
    UPDATE @TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END                             
   WHERE Running IS NOT NULL                            
                                
    --INSERT THE DETAILS IN THE MASTER TABLE                            
    INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,OdometerStart,                            
     OdometerEnd,IdlingDuration,Speed, IsTripClosed,StopTime,RunningTime,Distance,UtilizedDay)                             
    SELECT  isnull(S.Boxid,@intBoxLooping),S.StartTime,ST.StopTime,S.OdoStart,ST.OdoEnd,S.idling,                            
     S.Speed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running,(ST.OdoEnd-S.OdoStart),dt.UtilizedDay           
      FROM @TBLSTART S                            
       INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId right join @TBLDate dt on dt.UtilizedDay=cast(DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),s.StartTime))as date)    
       --cast(s.StartTime as date)           
                                 
   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping                            
                               
   UPDATE @tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM @tblTripDetailsForTD)            
  
   
       
   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping            
   END          
                
    --select * from @tblTripDetailsForTD          
            
   SELECT TDtls.BoxId,v.VehicleId ,cast(DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),StartDate))as date)as StartDate ,
   sum(Distance*@ConversionFactor) as Distance,      
   sum(isnull(IdlingDuration,0))as Idling,                      
   sum(RunningTime) as Running, SUM(Distance*@ConversionFactor) as dst,@ConversionFactor,    
   (case when VehicleTypeId=1 then @fuelcostperkmLV else @fuelcostperkmHV end),               
 (SUM(Distance*@ConversionFactor)*(case when VehicleTypeId=1 then @fuelcostperkmLV else @fuelcostperkmHV end)) as Distancecost,                      
 ((CAST(sum(isnull(IdlingDuration,0)) as float)/CAST(3600 as float)))  *                    
  ((case when VehicleTypeId=1 then @fcPerLtrLV else @fcPerLtrHV end) *       
  (case when VehicleTypeId=1 then @fcperidlingLV else @fcperidlingHV end)) as idlingcost,        
                      
 v.vin,v.LicensePlate , TDtls.UtilizedDay, (case when VehicleTypeId=1 then 'LV' else 'HV' end)                 
 from @tblTripDetailsForTD as TDtls                      
 inner JOIN rvlfBoxId b ON b.BoxId=TDtls.BoxId                    
 inner join rvlfVehicleAssignment va on TDtls.BoxId=va.BoxId                  
 inner join rvlfVehicle v on va.VehicleId=v.VehicleId                     
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=va.VehicleId                      
 --inner join rvlfVehicleType VT on v.VehicleTypeId=VT.VehicleTypeId                      
 WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or TDtls.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                         
 AND b.OrganizationId=@bigOrganizationID  and                    
 (cast(TDtls.StartDate as date) BETWEEN cast(@dtFDate as date) AND cast(@dtEDate as date) or TDtls.StartDate is null)                     
 group by TDtls.BoxId,v.VehicleId,V.VehicleDescription,cast(DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),StartDate))as date)    
 ,VehicleTypeId,Vin,LicensePlate,TDtls.UtilizedDay     
     
INSERT INTO @tblFuelcost                      
SELECT TDtls.BoxId,v.VehicleId,V.VehicleDescription,cast(DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),StartDate))as date)as StartDate ,sum(Distance*@ConversionFactor) as Distance,      
sum(isnull(IdlingDuration,0))as Idling,                      
 sum(RunningTime) as Running,                    
 (SUM(Distance*@ConversionFactor)*(case when VehicleTypeId=1 then @fuelcostperkmLV else @fuelcostperkmHV end)) as Distancecost,                      
 ((CAST(sum(isnull(IdlingDuration,0)) as float)/CAST(3600 as float)))  *                    
  ((case when VehicleTypeId=1 then @fcPerLtrLV else @fcPerLtrHV end) *       
  (case when VehicleTypeId=1 then @fcperidlingLV else @fcperidlingHV end)) as idlingcost,        
                      
 v.vin,v.LicensePlate , TDtls.UtilizedDay, (case when VehicleTypeId=1 then 'LV' else 'HV' end)                 
 from @tblTripDetailsForTD as TDtls                      
 inner JOIN rvlfBoxId b ON b.BoxId=TDtls.BoxId                    
 inner join rvlfVehicleAssignment va on TDtls.BoxId=va.BoxId                  
 inner join rvlfVehicle v on va.VehicleId=v.VehicleId                     
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=va.VehicleId                      
 --inner join rvlfVehicleType VT on v.VehicleTypeId=VT.VehicleTypeId                      
 WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or TDtls.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                         
 AND b.OrganizationId=@bigOrganizationID  and                    
 (cast(TDtls.StartDate as date) BETWEEN cast(@dtFDate as date) AND cast(@dtEDate as date) or TDtls.StartDate is null)                     
 group by TDtls.BoxId,v.VehicleId,V.VehicleDescription,cast(DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),StartDate))as date)    
 ,VehicleTypeId,Vin,LicensePlate,TDtls.UtilizedDay                     
              
        
          
  Declare @DistanceCostHV numeric(10,2)
  Declare @DistanceCostLV numeric(10,2)
  Declare @IdlingCostHV numeric(10,2)
  Declare @IdlingCostLV numeric(10,2) 
          
  Select det.UtilizedDay, det.BoxId,det.VehicleId,det.VehicleDescription,ISNULL(det.StartDay,det.UtilizedDay) as StartMonth,          
  case when isnull((det.TotDistance),0)=0 then '-' else cast((det.TotDistance)as varchar) end as TotDistance,                
  det.TotIdling as TotIdlingsec ,          
  case when isnull(det.TotIdling,0)=0 then '-'else CAST( dbo.rvlf_fn_GetTimeFromSeconds(isnull(det.TotIdling,0))as varchar) end as TotIdling,                
  isnull(det.TotRunning,0) as TotRunningsec,          
  case when isnull(det.TotRunning,0)=0 then '-' else CAST(dbo.rvlf_fn_GetTimeFromSeconds(isnull(det.TotRunning,0))as varchar)end as TotRunning,                
  case when isnull(det.DistanceCost,0)=0then '-' else CAST(isnull(det.DistanceCost,0)as varchar) end as DistanceCost          
  ,case when isnull(det.IdlingCost,0)=0 then '-' else CAST(det.IdlingCost as varchar) end as IdlingCost          
  ,case when isnull((det.DistanceCost+det.IdlingCost),0)=0 then '-' else CAST((det.DistanceCost+det.IdlingCost)as varchar) end as Totcost,                
  smry.Vin,smry.LicensePlate,          
 case when isnull(smry.TotDistanceCost,0)=0 then '-' else CAST(smry.TotDistanceCost as varchar) end as TotDistanceCost,          
 case when smry.TotIdlingCost=0 then '-' else CAST(smry.TotIdlingCost as varchar) end as TotIdlingCost,                    
 case when isnull(smry.Total,0)=0 then '-' else CAST(smry.Total as varchar) end as Total,
 case when det.VehicleType='HV' then isnull(DistanceCost,0) else 0 end as DistanceCostHV,
 case when det.VehicleType='LV' then isnull(DistanceCost,0) else 0 end as DistanceCostLV,
 case when det.VehicleType='HV' then isnull(IdlingCost,0) else 0 end as IdlingCostHV,
 case when det.VehicleType='LV' then isnull(IdlingCost,0) else 0 end as IdlingCostLV,          
  @fcPerLtrLV as fcPerLtrLV,  @fcPerLtrHV as fcPerLtrHV,                    
  @fcperidlingLV as fcperidlingLV, @fcperidlingHV as fcperidlingHV, @distPerLtrLV as distPerLtrLV,@distPerLtrHV as distPerLtrHV,                
  @DistanceCaptionPrefix as DistanceCaptionPrefix,@SpeedCaptionPrefix as SpeedCaptionPrefix,                    
  smry.PasStartDate,smry.PasEndDate,smry.PasGenerateddate,
  case when det.TotRunning=0 or det.TotRunning IS NULL then 0 else 1 end as Utilized ,det.VehicleType              
  from @tblFuelcost det       
  left join (                
 Select BoxId,VehicleId,VehicleDescription,Vin,LicensePlate,sum(DistanceCost) as TotDistanceCost,sum(IdlingCost) as TotIdlingCost,                    
 sum(DistanceCost+IdlingCost) as Total ,       
 --@fcPerLtrLV as fcPerLtrLV, @fcPerLtrHV as fcPerLtrHV,                    
 --@fcperidlingLV as fcperidlingLV, @fcperidlingHV as fcperidlingHV,@distPerLtrLV as distPerLtrLV, @distPerLtrHV as distPerLtrHV,                    
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,                      
 Convert(varchar,@dtEDate,@DefaultDateFormat)+' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,        
 --'03/23/14  8:00:00 PM' as PasEndDate,        
 PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())                
 from @tblFuelcost                      
 group by BoxId,VehicleId,VehicleDescription,Vin,LicensePlate                    
 ) as smry on det.BoxId=smry.BoxId                 
 order by BoxId,det.UtilizedDay                  
 
     select * from @tblFuelcost  
 --select case when  VehicleType='HV' then sum(isnull(DistanceCost,0)) else 0 end as DistanceCostHV,
 --case when  VehicleType='LV' then sum(isnull(DistanceCost,0)) else 0 end as DistanceCostLV,
 --case when VehicleType='HV' then sum(isnull(IdlingCost,0)) else 0 end as IdlingCostHV,
 --case when  VehicleType='LV' then sum(isnull(IdlingCost,0)) else 0 end as IdlingCostLV   from @tblFuelcost group by VehicleType
      
SET NOCOUNT OFF                          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetFuelSummary]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetFuelSummary]                        
 @bigVehicleId BIGINT = NULL,                        
 @bigFleetID bigint = null,                        
 @intBoxID varchar(max) = NULL,                        
 @dtStartDate datetime = null,                        
 @dtEndDate datetime = null,                        
 @bigOrganizationID bigint = null,                        
 @bigQueryingUser bigint=NULL                        
AS                        
/******************************************************************************/                        
-- Name  : rvlf_sp_GetFuelSummary NULL,8,NULL,'11/01/2012 08:00:00 AM','11/07/2012 08:00:00 AM',6,303               
-- 1598,222,138,,,19,NULL                      
-- Description : To Get the Fuel Entry                        
-- Author  : MuthuKumaraVadivel. V                        
-- Company  : Angler Technologies                        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                        
--    : 13-May-2011 VM Created Intial Version                         
/******************************************************************************/                        
BEGIN                        
SET NOCOUNT ON                         
 Declare @dtFDate datetime = @dtStartDate                      
 Declare @dtEDate datetime = @dtEndDate                         
 BEGIN                        
                      
  DECLARE @ConversionFactor decimal(18,2) = 1.0        
  DECLARE @ConversionFactorSpeed decimal(18,2) = 1.0        
  DECLARE @DefaultDateFormat INT = 0                        
    DECLARE @HoursToBeAdded INT = 0                        
 DECLARE @MinsToBeAdded INT = 0                       
                       
  SELECT @ConversionFactor = CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 END,@DefaultDateFormat=(case when  ISNULL(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end),                    
@ConversionFactorSpeed = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                   
@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded                           
FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz                        
ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser        
        
        
--FIND THE CURRENT DRIVER NAMES BASED ON THE SCHEDULES                
DECLARE @tblDriverDetails TABLE(Boxid int,DisplayName varchar(30),DriverName varchar(max))                              
                              
 INSERT INTO @tblDriverDetails(Boxid,DisplayName)              
 SELECT DA.BoxId,DM.DisplayName          
  FROM rvlfDriverAssignment DA          
   INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=DA.BoxId                              
   INNER JOIN rvlfFleetVehicles FV ON FV.VehicleId=VA.VehicleId                              
   INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId                            
   LEFT OUTER JOIN rvlfIButtonMapping IB ON IB.DriverId<>DM.DriverId and IB.BoxID = VA.BoxId                                
  WHERE FV.FleetId=@bigFleetId                               
   AND GETUTCDATE() BETWEEN CASE WHEN DA.PunchIn IS NULL THEN DA.FromTime ELSE DA.PunchIn END                              
    AND CASE WHEN DA.PunchOut IS NULL THEN DA.ToTime ELSE DA.PunchOut END                 
                    
      --FIND THE MULTI DERIVERS BASED ON THE VEHICLE        
 DECLARE @INC INT=0        
 SELECT @INC =MIN(BOXID) FROM @tblDriverDetails        
 WHILE @INC IS NOT NULL        
  BEGIN                                
   DECLARE @vcDriverNames VARCHAR(MAX)=NULL                              
  SELECT @vcDriverNames=COALESCE(@vcDriverNames,'')+CONVERT(VARCHAR,DisplayName)+',' FROM @tblDriverDetails WHERE Boxid=@INC                               
   UPDATE @tblDriverDetails SET DriverName=@vcDriverNames,DisplayName=NULL WHERE Boxid=@INC                               
   SELECT @INC =MIN(BOXID) FROM @tblDriverDetails WHERE Boxid >@INC                               
  END                      
 INSERT INTO @tblDriverDetails (Boxid,DisplayName,DriverName)                              
 SELECT Boxid,'DRIVER',DriverName FROM @tblDriverDetails GROUP BY Boxid,DisplayName,DriverName                                 
 DELETE FROM @tblDriverDetails WHERE DisplayName IS NULL                
                  
                   
  -- GET FUEL DETAILS                          
  DECLARE @tblFuel TABLE                        
  (                        
   [Rows] INT  IDENTITY PRIMARY KEY,                            
   BoxId  INT,                    
   VehicleID bigint null,                        
   VehicleName VARCHAR(250) null,                        
   FromDate DATETIME null,                        
   ToDate DATETIME null,                        
   FuelFilled DECIMAL(18,2) null,                        
   FuelCost DECIMAL(18,2) null,                        
   Vin VARCHAR(50) null,                        
   LicensePlate VARCHAR(50),                        
   VehicleDescription VARCHAR(250),                        
   Comments VARCHAR(250),                    
   Distance INT,            
   FuelStation VARCHAR(250),               
   DriverName VARCHAR(250)            
  )                         
                          
                          
  INSERT INTO @tblFuel (BoxId, VehicleID, VehicleName, FromDate, ToDate, FuelFilled,FuelCost, Vin, LicensePlate,VehicleDescription,Comments,FuelStation,DriverName)            
   SELECT va.BoxId,F.VehicleID, V.VehicleDescription AS VehicleName,         
   --CONVERT(DATETIME, F.FuelFilledDateTime, 100) AS FromDate,           
   CONVERT(DATETIME, DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,F.FuelFilledDateTime)), 100) AS FromDate,    
   NULL AS ToDate, F.FuelFilled / @ConversionFactor AS FuelFilled,            
       
   (CONVERT(decimal(18,2), F.FuelFilled) * CAST(f.FuelCost AS DECIMAL(18,2))) AS FuelCost,                  
   V.Vin, V.LicensePlate,V.VehicleDescription,f.Comments,F.FuelStation,DM.DisplayName                   
   FROM rvlfFuelEntry F                         
   INNER JOIN rvlfVehicle V ON F.VehicleId = V.VehicleId                        
   INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId = V.VehicleId                        
   INNER JOIN rvlfFleetVehicles FV ON V.VehicleId = FV.VehicleId                        
   INNER JOIN rvlfFleet FL ON FV.FleetId = FL.FleetId                
   LEFT OUTER JOIN rvlfIButtonMapping BM ON BM.BoxID = va.BoxId                
LEFT OUTER JOIN @tblDriverDetails DD ON DD.Boxid= va.BoxId                
LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId in (select Top 1 DriverId from rvlfDriverAssignment where Boxid = va.BoxId ORDER BY AssignmentId desc)            
   WHERE V.OrganizationId = @bigOrganizationId AND                     
   (@intBoxID IS NULL OR @intBoxID='' OR VA.BoxId IN (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))              
   AND (@bigFleetID IS NULL OR @bigFleetID='' OR FL.FleetId = @bigFleetID)                         
   AND (@dtStartDate IS NULL OR @dtEndDate IS NULL OR DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,FuelFilledDateTime))    
   BETWEEN @dtStartDate AND @dtEndDate)    
   --BETWEEN CONVERT(DATE, @dtStartDate) AND CONVERT(DATE, @dtEndDate))                        
   AND (BM.PunchInTime IS NULL OR BM.PunchInTime =(SELECT MAX(PunchInTime)         
   FROM rvlfIButtonMapping WHERE Boxid=va.BoxId)) ORDER BY V.VehicleDescription,FromDate ASC          
                           
          
            
DECLARE @TblBoxId AS TABLE                
(                
 [Rows] INT  IDENTITY PRIMARY KEY,                
 BoxId INT                
)              
            
INSERT INTO @TblBoxId SELECT DISTINCT Boxid FROM @tblFuel            
            
DECLARE @RowCount AS BIGINT = 0                    
SELECT @RowCount = COUNT([Rows]) from @TblBoxId                    
                    
DECLARE @intFlag AS INT = 1                    
DECLARE @boxids AS INT                    
DECLARE @DISTANCE AS INT                    
DECLARE @FROMDATE AS DATETIME,@TODATE AS DATETIME                  
                    
WHILE (@intFlag <= @RowCount)            
BEGIN                    
            
  CREATE TABLE #TblDistance                    
  (                        
  [Rows] INT  IDENTITY PRIMARY KEY,                            
   BoxId  INT,                    
   VehicleID bigint null,                        
   VehicleName VARCHAR(250) null,                        
   FromDate DATETIME null,                        
   ToDate DATETIME null,                        
   FuelFilled DECIMAL(18,2) null,                        
   FuelCost DECIMAL(18,2) null,                        
   Vin VARCHAR(50) null,                        
   LicensePlate VARCHAR(50),                        
   VehicleDescription VARCHAR(250),                        
   Comments VARCHAR(250),                    
   Distance INT,            
   FuelStation VARCHAR(250),            
   DriverName VARCHAR(250)            
  )                 
                    
 SELECT @boxids = BOXID FROM @TblBoxId WHERE [rows] = @intFlag            
             
 INSERT INTO #TblDistance (BoxId, VehicleID, VehicleName, FromDate, ToDate, FuelFilled,FuelCost, Vin, LicensePlate,VehicleDescription,Comments,FuelStation,DriverName)            
 SELECT BoxId ,                    
   VehicleID,                        
   VehicleName,            
   FromDate,                        
   ToDate,                        
   FuelFilled,                        
   FuelCost,                        
   Vin,                        
   LicensePlate,                        
   VehicleDescription,                        
   Comments,                       
   FuelStation,               
   DriverName  FROM @tblFuel WHERE BoxId = @boxids ORDER BY FromDate ASC             
               
   DECLARE @Count AS BIGINT = 0                  
 DECLARE @intFlg AS INT = 1                
             
  SELECT @Count = COUNT(BoxId) FROM #TblDistance              
              
              
   WHILE (@intFlg <= @Count)                
  BEGIN                
                      
   SELECT @FROMDATE = FromDate, @boxids = BoxId                 
   FROM #TblDistance WHERE [rows] = @intFlg                   
                 
                   
   IF EXISTS (SELECT FromDate FROM #TblDistance WHERE [rows] = @intFlg + 1)                
   BEGIN                
     SELECT @TODATE = FromDate FROM #TblDistance WHERE [rows] = @intFlg + 1                
   END                
   ELSE                
   BEGIN                
    SET @TODATE = NULL                
   END                
                
                   
   SELECT @DISTANCE = (MAX(Odometer) - MIN(Odometer)) FROM [DBO].[rvlfMsgInHst]                
   WHERE CAST(DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,OriginDateTime)) AS DATETIME)                 
   BETWEEN @FROMDATE AND ISNULL(@TODATE,@dtEndDate)        
   --BETWEEN @FROMDATE AND ISNULL(@TODATE,DATEADD(MINUTE,,DATEADD(HOUR,0,@dtEndDate)))                      
   AND BoxId = @boxids AND Odometer <> 0                
                   
   UPDATE @tblFuel SET DISTANCE = ISNULL(@DISTANCE,0),                   
   --ToDate = ISNULL(@TODATE,DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,@TODATETIME)))                      
   ToDate = ISNULL(@TODATE,DATEADD(MINUTE,0,DATEADD(HOUR,0,@dtEndDate)))                      
   WHERE BoxId = @boxids AND FromDate = @FROMDATE                
                 
   SET @intFlg = @intFlg + 1                
  END                 
                
 DROP TABLE #TblDistance              
 SET @intFlag = @intFlag + 1                
                
END                           
            
SELECT VehicleID,VehicleName, Convert(varchar,FromDate,100) as FromDate,Convert(varchar,ToDate,100) as ToDate,            
FuelFilled,CASE WHEN FuelCost IS NULL THEN 0  ELSE FuelCost END  AS FuelCost,        
  Vin,LicensePlate,VehicleDescription,Comments,                 
  FuelStation,ISNULL(DriverName,'-') AS DriverName,            
  (SELECT COUNT(f1.VehicleName) FROM @tblFuel f1 WHERE f1.VehicleID = VehicleID) AS NoofInstances,                                     
  Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,        
  Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                      
  PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()),                         
  (Distance * @ConversionFactorSpeed) As Distance ,BoxId       
  FROM @tblFuel ORDER BY VehicleDescription, FromDate DESC        
                            
    END                        
                          
SET NOCOUNT OFF                        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetGarminCommands]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[rvlf_sp_GetGarminCommands]    
AS    
/******************************************************************************/    
-- Name  : rvlf_sp_GetGarminCommands    
-- Description : To get the command for garmin    
-- Author  : Sakthi Gopinath S    
-- Created Date: 27-Feb-2012    
-- Company  : Angler Technologies    
--    : 07-Nov-2013 Sakthi Include MDT message    
/******************************************************************************/    
BEGIN    
SET NOCOUNT ON    
 SELECT BoxCmdOutTypeId,BoxCmdOutTypeCode,CASE WHEN BoxCmdOutTypeId=39 THEN 'Send Message to device'     
 WHEN BoxCmdOutTypeId=46 THEN 'Delete Inbox & Outbox'     
 ELSE BoxcmdTypeDesc END AS BoxcmdTypeDesc FROM dbo.rvlfBoxCmdOutType     
 WHERE BoxCmdOutTypeId IN (39,46,56,57,58,59,79,80,81)    
SET NOCOUNT OFF    
END
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetGarminLandmarks]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetGarminLandmarks]            
@bigFleetId bigint,            
@bigVehicleId bigint,            
@bigOrgId int,            
@bitIsWaypoint int,            
@bitAssigned bit,          
@bigQueryingUser int = null          
AS            
/******************************************************************************/                
-- Name   : [rvlf_sp_GetGarminLandmarks] 8,32,6,2,0,94               
-- Description : To get the assigned landmarks for garmin            
-- Author  : Sakthi Gopinath S                
-- Created Date : 06-Jan-2012            
-- Company  : Angler Technologies                    
/******************************************************************************/                
BEGIN            
 SET NOCOUNT ON            
           
 IF @bitIsWaypoint=1           
 BEGIN            
   IF @bitAssigned=1            
   BEGIN            
     SELECT wp.Sno,CASE WHEN l.LandmarkID IS NULL THEN 0 ELSE l.LandmarkID END AS LandmarkID,            
     CASE WHEN l.LandmarkName IS NULL THEN 'Address '+CAST(wp.WayPointID AS VARCHAR) ELSE l.LandmarkName END AS LandmarkName,            
     CASE WHEN l.Description IS NULL THEN '-' ELSE l.[Description] END AS [Description],            
     CASE WHEN l.Latitude IS NULL THEN wp.Latitude ELSE l.Latitude END AS Latitude,            
     CASE WHEN l.Longitude IS NULL THEN wp.Longitude ELSE l.Longitude END AS Longitude,            
     CASE WHEN l.StreetAddress IS NULL THEN wp.StreetAddress ELSE l.StreetAddress END AS StreetAddress,            
     CASE WHEN l.LandmarkCategoryID IS NULL THEN 0 ELSE l.LandmarkCategoryID END AS LandmarkCategoryID,             
     '-' AS [Status] FROM rvlfLandmark l RIGHT JOIN rvlfGarminWaypoint wp ON wp.LandmarkId=l.LandmarkID            
     WHERE wp.VehicleId=@bigVehicleId            
   END            
   ELSE            
   BEGIN            
     --Display the Unassigned landmark            
     SELECT l.LandmarkID,l.LandmarkName,l.Description,l.Latitude,l.Longitude,l.StreetAddress,l.LandmarkCategoryID            
     FROM rvlfLandmark l WHERE l.OrganizationId=@bigOrgId --AND l.LandmarkID NOT IN            
    -- (SELECT LandmarkId FROM rvlfGarminWaypoint WHERE VehicleId=@bigVehicleId AND LandmarkId IS NOT NULL)            
   END            
 END            
 ELSE IF @bitIsWaypoint=2          
 BEGIN            
   IF @bitAssigned=1            
   BEGIN            
     SELECT Gs.Sno,CASE WHEN l.LandmarkID IS NULL THEN 0 ELSE l.LandmarkID END AS LandmarkID,            
     CASE WHEN l.LandmarkName IS NULL THEN 'Address '+CAST(Gs.StopId AS VARCHAR) ELSE l.LandmarkName END AS LandmarkName,            
     CASE WHEN l.Description IS NULL THEN '-' ELSE l.[Description] END AS [Description],            
     CASE WHEN l.Latitude IS NULL THEN Gs.Latitude ELSE l.Latitude END AS Latitude,            
     CASE WHEN l.Longitude IS NULL THEN Gs.Longitude ELSE l.Longitude END AS Longitude,            
     CASE WHEN l.StreetAddress IS NULL THEN Gs.StreetAddress ELSE l.StreetAddress END AS StreetAddress,            
     CASE WHEN l.LandmarkCategoryID IS NULL THEN 0 ELSE l.LandmarkCategoryID END AS LandmarkCategoryID             
     FROM rvlfLandmark l RIGHT JOIN rvlfGarminStop Gs ON Gs.LandmarkId=l.LandmarkID            
     WHERE Gs.VehicleId=@bigVehicleId            
   END            
   ELSE            
   BEGIN            
     --Display the Unassigned landmark            
     SELECT l.LandmarkID,l.LandmarkName,l.Description,l.Latitude,l.Longitude,l.StreetAddress,l.LandmarkCategoryID             
     FROM rvlfLandmark l WHERE l.OrganizationId=@bigOrgId --AND l.LandmarkID NOT IN            
     --(SELECT LandmarkId FROM rvlfGarminStop WHERE VehicleId=@bigVehicleId  AND LandmarkId IS NOT NULL)            
   END            
 END            
 ELSE          
 BEGIN          
           
   DECLARE @HoursToBeAdded INT = 0          
   DECLARE @MinsToBeAdded INT = 0          
   DECLARE @DefaultDateFormat INT = 0          
   SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,          
   @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          
           
   -- Get assigned waypoints for the selected vehicles          
   SELECT wp.VehicleId,l.LandmarkID,            
   CASE WHEN l.LandmarkName IS NULL THEN 'Address '+CAST(wp.WayPointId AS VARCHAR) ELSE l.LandmarkName END AS LandmarkName,            
   CASE WHEN l.Description IS NULL THEN '-' ELSE l.[Description] END AS [Description],            
   CASE WHEN l.Latitude IS NULL THEN wp.Latitude ELSE l.Latitude END AS Latitude,            
   CASE WHEN l.Longitude IS NULL THEN wp.Longitude ELSE l.Longitude END AS Longitude,            
   CASE WHEN l.StreetAddress IS NULL THEN wp.StreetAddress ELSE l.StreetAddress END AS StreetAddress,            
   CASE WHEN l.LandmarkCategoryID IS NULL THEN 0 ELSE l.LandmarkCategoryID END AS LandmarkCategoryID,            
   '-' AS [Status] FROM rvlfLandmark l RIGHT OUTER JOIN rvlfGarminWaypoint wp ON l.LandmarkID=wp.LandmarkId            
   INNER JOIN rvlfVehicle v ON v.VehicleId = wp.VehicleId             
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId             
   INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId            
   WHERE (@bigFleetId IS NULL OR @bigFleetId='' OR f.FleetId=@bigFleetId) AND             
   (@bigVehicleId IS NULL OR @bigVehicleId='' OR v.vehicleId=@bigVehicleId) AND            
   v.OrganizationId=@bigOrgId            
             
   -- Get assigned stops for the selected vehicles          
   SELECT s.VehicleId,l.LandmarkID,            
   CASE WHEN l.LandmarkName IS NULL THEN 'Address '+CAST(s.StopId AS VARCHAR) ELSE l.LandmarkName END AS LandmarkName,            
   CASE WHEN l.Description IS NULL THEN '-' ELSE l.[Description] END AS [Description],            
   CASE WHEN l.Latitude IS NULL THEN s.Latitude ELSE l.Latitude END AS Latitude,            
   CASE WHEN l.Longitude IS NULL THEN s.Longitude ELSE l.Longitude END AS Longitude,            
   CASE WHEN l.StreetAddress IS NULL THEN s.StreetAddress ELSE l.StreetAddress END AS StreetAddress,            
   CASE WHEN l.LandmarkCategoryID IS NULL THEN 0 ELSE l.LandmarkCategoryID END AS LandmarkCategoryID,            
   Case When s.StopStatus='Read Inactive' then 'Reached' else s.StopStatus end AS [Status]    
   FROM rvlfLandmark l RIGHT OUTER JOIN rvlfGarminStop s ON l.LandmarkID=s.LandmarkId            
   INNER JOIN rvlfVehicle v ON v.VehicleId = s.VehicleId             
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId             
   INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId            
   WHERE (@bigFleetId IS NULL OR @bigFleetId='' OR f.FleetId=@bigFleetId) AND             
   (@bigVehicleId IS NULL OR @bigVehicleId='' OR v.vehicleId=@bigVehicleId) AND            
   v.OrganizationId=@bigOrgId            
             
   --GET Last ETA          
   SELECT TOP 1 h.MessageInID,va.BoxId,v.VehicleDescription,          
   CASE WHEN CAST(SUBSTRING(CustomProp,8,CHARINDEX(';Distance',CustomProp,1)-8) AS bigint)=-1 THEN          
   'No Navigation' ELSE          
   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) END AS ETA,       
  
   
   CASE WHEN CAST(SUBSTRING(CustomProp,8,CHARINDEX(';Distance',CustomProp,1)-8) AS bigint)=-1 THEN '-'          
   ELSE SUBSTRING(CustomProp,CHARINDEX(';Distance',CustomProp,1)+10,LEN(Customprop)-CHARINDEX(';Distance',CustomProp,1)+10) + ' meters' END           
   AS Distance,h.Latitude,h.Longitude,h.StreetAddress,        
   (SELECT TOP 1 CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,SentDateTime)),@DefaultDateFormat)+         
   + ' ' + Convert(varchar,cast(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,SentDateTime)) as Time),22)        
   FROM rvlfMsgOutHst WHERE BoxCmdOutTypeId=59 AND MessageInID IS NOT NULL AND BoxId=h.BoxId AND CustomProp='512'        
   ORDER BY SentDateTime DESC) AS CmdSentDateTime         
   FROM dbo.rvlfMsgInHst h INNER JOIN rvlfVehicleAssignment va ON va.BoxId=h.BoxId          
   INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId           
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId             
   INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId            
   WHERE (@bigFleetId IS NULL OR @bigFleetId='' OR f.FleetId=@bigFleetId) AND           
   (@bigVehicleId IS NULL OR @bigVehicleId='' OR v.vehicleId=@bigVehicleId) AND            
   v.OrganizationId=@bigOrgId AND h.BoxMsgInTypeId=114 AND CharIndex('ETA:',CustomProp) <> 0          
   --AND h.MessageInID='76F752BC-525D-E111-B874-00219B712B2E'          
   ORDER BY OriginDateTime DESC           
  END          
 SET NOCOUNT OFF            
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetGarminStopStatus]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetGarminStopStatus]  
@bitIsStopStatus bit  
AS  
/******************************************************************************/      
-- Name   : [rvlf_sp_GetGarminStopStatus] 0  
-- Description : To get the stop status for garmin  
-- Author  : Sakthi Gopinath S      
-- Created Date : 06-Jan-2012  
-- Company  : Angler Technologies          
/******************************************************************************/    
BEGIN  
 SET NOCOUNT ON  
  SELECT StatusId,StatusName,StatusCode FROM rvlfGarminStopStatus  
  WHERE IsStopStatus=@bitIsStopStatus  
 SET NOCOUNT OFF  
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetGarminWayOrStopPointId]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetGarminWayOrStopPointId]    
@vehicleId bigint,    
@bitIswaypoint bit,    
@LandmarkId int = 0,    
@WayOrStopID int = null    
AS    
/******************************************************************************/        
-- Name   : [rvlf_sp_GetGarminWayOrStopPointId] 180,0,0,8    
-- Description : To get Nextid or waypoint or stop id    
-- Author  : Sakthi Gopinath S        
-- Created Date : 10-Jan-2012    
-- Company  : Angler Technologies            
/******************************************************************************/      
BEGIN    
 SET NOCOUNT ON    
  IF @bitIswaypoint = 1    
  BEGIN    
   IF @LandmarkId =0 AND @WayOrStopID IS NULL    
   BEGIN    
    SELECT ISNULL(MAX(wp.WayPointId),0)+1 AS 'NextId' FROM dbo.rvlfGarminWaypoint wp WHERE wp.VehicleId=@vehicleId     
   END    
   ELSE    
   BEGIN    
    SELECT wp.WayPointId AS 'WayPointId' FROM dbo.rvlfGarminWaypoint wp WHERE wp.VehicleId=@vehicleId AND     
    (@LandmarkId = 0 OR wp.LandmarkId=@LandmarkId) AND (@WayOrStopID IS NULL OR wp.WayPointId=@WayOrStopID)    
   END       
  END    
  ELSE    
  BEGIN    
   IF @LandmarkId =0 AND @WayOrStopID IS NULL    
   BEGIN    
    SELECT ISNULL(MAX(s.StopId),0)+1 AS 'NextId' FROM dbo.rvlfGarminStop s WHERE s.VehicleId=@vehicleId    
   END    
   ELSE    
   BEGIN    
    SELECT s.StopId AS 'StopId' FROM dbo.rvlfGarminStop s WHERE s.VehicleId=@vehicleId AND     
   --SELECT s.LandmarkId AS 'StopId' FROM dbo.rvlfGarminStop s WHERE s.VehicleId=@vehicleId AND     
    (@LandmarkId = 0 OR s.LandmarkId=@LandmarkId) AND (@WayOrStopID IS NULL OR s.StopId=@WayOrStopID)    
   END    
  END      
 SET NOCOUNT OFF    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetGeozoneTollFare]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetGeozoneTollFare]                    
                                
 @bigFleetID bigint = null,                                  
 @intBoxID varchar(max) = null,                                  
 @dtStartDate datetime = null,                                  
 @dtEndDate datetime = null,                                  
 @tiBoxMsgInType tinyint = null,                                  
 @bigOrganizationID bigint = null,                                  
 @bigQueryingUser bigint = 0                                  
AS                                  
/******************************************************************************/                                  
-- Name  : [rvlf_sp_GetGeozoneTollFare] 8, null,'2014-01-20 08:00 AM' , '2014-01-23 10:00PM', null, 6, 63                   
-- Description : To get the Toll gate geozone Fare details       
-- Author  : Gopal.R.                                  
-- Company  : Angler Technologies                                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                  
                              
/******************************************************************************/                                  
BEGIN                                  
 ------- Included to get the user prefernces---------------------                                  
  Declare @dtFDate datetime =@dtStartDate                              
 Declare @dtEDate datetime =@dtEndDate                              
                                   
 DECLARE @HoursToBeAdded INT = 0                                  
 DECLARE @MinsToBeAdded INT = 0                                  
 DECLARE @DefaultDateFormat INT = 0                                  
 DECLARE @ConversionFactor numeric (10,2) = 1.0                                  
 DECLARE @Lang varchar(50)              
                                             
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                                  
     @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')                                 
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz                                  
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser                                  
                                   
 --------------------------------                                  
                                  
 -------------------date convertion--included by Narayanasamy on 03-Nov-09---------------------------------                                  
                                  
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                                  
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                                  
                                  
 ----------------------------------------------------------------------------------------------------------                                  
 DECLARE @bitIsNotificationSent bit                                  
 DECLARE @vcStreedAddress nvarchar(20) = NULL             
 Declare @TotalGeozone int=0                                 
 Declare @GeozoneActivityIn int=0                                 
 Declare @GeozoneActivityOut int=0                                 
                                                 
 DECLARE @tblGeozoneActivities TABLE                                   
  (           
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,                             
   MessageInID uniqueidentifier,                                  
   OriginDateTime Datetime,                                  
   DateTimeReceived DateTime,        
   BoxMsgInTypeDesc nvarchar(50),                                  
   StreetAddress nvarchar(300),                          
   BoxId int,                                  
   VehicleDescription varchar(50),                   
   Vin varchar(20),                                  
   LicensePlate varchar(20),                                  
   FleetName varchar(50),                                   
   OrganizationID bigint,                                  
   GeozoneID bigint,                                  
   BoxMsgInTypeId tinyint ,       
   vehicleId bigint,      
   vehicleType int,              
   Customprop varchar(max)                                 
  )                                  
  Declare @temp table ( [TripId] [bigint]IDENTITY(1,1) NOT NULL,GeozoneNo bigint,                             
   VehicleDescription varchar(50),BoxId int, FleetName varchar(50), LicensePlate varchar(20),     
   OriginDateTime Date ,    
   Vin varchar(20),    
   GeozoneName varchar(50),                               
   Tollfare decimal(8,2),    
   TotalNoofTrips bigint       
   )                  
                    
 INSERT INTO @tblGeozoneActivities  SELECT h.MessageInID,                                  
  h.OriginDateTime, h.DateTimeReceived,                            
  case when @Lang='LanguageArNew' then isnull (m.BoxMsgInTypeDesc,m.BoxMsgInTypeDesc) else m.BoxMsgInTypeDesc end,                                   
  --m.BoxMsgInTypeDesc,                l            
  --ISNULL(h.StreetAddress,'Address is not resolved')                      
    Replace(ISNULL( (                      
    Case WHEN @Lang='LanguageArNew' THEN ISNULL(H.StreetAddress_AR,H.StreetAddress)                       
    When @Lang='LanguageHindi' THEN ISNULL(H.StreetAddress_Hin,H.StreetAddress)                       
    ELSE H.StreetAddress END),'Address is not resolved'),'''','\''')                           
  ,h.BoxId, v.VehicleDescription,v.Vin,v.LicensePlate,                                  
   f.FleetName, v.OrganizationId,                                  
   (CAST( SUBSTRING(h.CustomProp,                                  
     CHARINDEX('=',h.CustomProp,1)+1,(CHARINDEX(';',h.CustomProp,1)                                  
     - CHARINDEX('=',h.CustomProp,1))-1) as bigint)) as GeozoneID, h.BoxMsgInTypeId,v.VehicleId,v.VehicleTypeId,h.CustomProp                              
   FROM rvlfMsgInHst h                                   
    INNER JOIN rvlfVehicleAssignment a ON h.BoxId = a.BoxId                                  
    INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                                   
    INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId                                  
    LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID                                   
    INNER JOIN rvlfVehicle v ON a.VehicleId = v.VehicleId                                   
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId                                  
    INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId and f.FleetId = @bigFleetID       
                                     
   WHERE                                  
    (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR  h.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND                                      
    (h.BoxMsgintypeid = 5 ) and                                  
    (@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='' OR h.BoxMsgInTypeId = @tiBoxMsgInType) AND                                  
    (@dtStartDate IS NULL OR (h.OriginDateTime BETWEEN @dtStartDate AND                        
     @dtEndDate ) )               
            
            
insert into @temp                 
select og.GeozoneNo, TA.VehicleDescription,TA.BoxId,TA.FleetName,TA.LicensePlate,    
(Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,TA.OriginDateTime)),@DefaultDateFormat)) as OriginDateTime,      
--TA.OriginDateTime,    
TA.Vin,OG.GeozoneName      
,isnull((select top 1 TollFare from rvlfGeozoneSalikFare where cast(ValidFrom as date) <=CAST(TA.OriginDateTime as DATE) and VehicleTypeId=TA.vehicleType and GeozoneID=OG.GeozoneNo order by ValidFrom desc),0) as    
TollFare ,    
COUNT(TA.GeozoneID) as TotalNoofTrips      
--Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,            
  -- Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,            
   --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate      
  
      
from @tblGeozoneActivities TA inner join rvlfOrganizationGeozone OG on TA.GeozoneID=OG.GeozoneId      
inner join rvlfGeozoneSalikFare GSF on OG.GeozoneNo=GSF.GeozoneID and TA.vehicleType=GSF.VehicleTypeId      
   group by TA.VehicleDescription,TA.BoxId,TA.FleetName,TA.LicensePlate,CAST(TA.OriginDateTime as DATE),TA.Vin,OG.GeozoneName,      
   (Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,TA.OriginDateTime)),@DefaultDateFormat)) ,TA.vehicleType,OG.GeozoneNo     
--,GSF.TollFare        
    
  select [TripId] ,GeozoneNo,VehicleDescription ,BoxId , FleetName , LicensePlate ,OriginDateTime,    
  --(Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)),@DefaultDateFormat)) as OriginDateTime,    
   OriginDateTime as OriginDateTimesort,Vin,GeozoneName,Tollfare,TotalNoofTrips,    
   (Tollfare*TotalNoofTrips) as TotalFare,    
   (select count(*) from(select OriginDateTime from @temp where BoxId=T.BoxId   group by OriginDateTime)as a) as TotalDays,    
  (select count(*) from(select GeozoneNo from @temp where BoxId=T.BoxId  group by GeozoneNo)as a) as TotalGeozone,    
  Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,            
  Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,            
  Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate          
  
      from @temp T         
        
END   
  
--[rvlf_sp_GetGeozoneTollFare] 8, null,'2014-01-20 08:00 AM' , '2014-01-23 10:00PM', null, 6, 63 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetGridAdvancedFilterSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasu.E
-- Create date: 13-09-2016
-- Description:	Get the GridView Advanced filter settings for the current user.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetGridAdvancedFilterSettings] 
	-- Add the parameters for the stored procedure here
	@bigUserId		bigint = NULL, 
	@bigModuleId	bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT * FROM rvlfGridAdvancedFilters 
	WHERE	UserID = @bigUserId 
	and		ModuleId = @bigModuleId
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_SP_GetHistoryOut]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- exec rvlf_SP_GetHistoryOut @bigVehicleId=N'',@bigFleetId=N'176',@dtFromdateTime=N'06-19-2018 12:00:00 AM',@dtTodateTime=N'07-20-2018 12:00:00 AM',@bigOrganizationId=N'86',@bigQueryingUser=N'457'
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_SP_GetHistoryOut]
	-- Add the parameters for the stored procedure here
	 @bigVehicleId bigint=null,  
	 @bigFleetId bigint=null,  
	 @dtFromdateTime datetime=null,  
	 @dtTodateTime datetime=null,  
	 @bigOrganizationId bigint=null,  
	 @bigQueryingUser bigint=null      
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DECLARE @Lang varchar(50),  @LangSetting varchar(20)                               
	DECLARE @HoursToBeAdded INT = 0     
	DECLARE @MinsToBeAdded INT = 0                  
	DECLARE @Distance varchar(20)                  
	DECLARE @DefaultDateFormat INT = 0 
	DECLARE @ConversionFactor numeric (10,2) = 1.0 
	DECLARE @OperationTypeID table (OperationTypeID bigint) 
    DECLARE @controllerType tinyint= (select VehicleTypeId from rvlfVehicle where VehicleId=@bigVehicleId)
	               
    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)  ,
			@Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings                
    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    
	inner join rvlfOrganization o on u.OrganizationId = o.OrganizationId        

--select mo.BoxId as VehicleDescription,C.BoxCmdOutTypeName, left (right (MO.CustomProp, len (MO.CustomProp)-(14 + len(mo.BoxId) + 1)), len (MO.CustomProp)-(14 + len(mo.BoxId) + 3)) as Inputs,dbo.rvlf_fn_DayLightSavings_Date
select mo.BoxId as VehicleDescription,C.BoxCmdOutTypeName, case when C.BoxCmdOutTypeId in (1,19) then MO.CustomProp else replace(replace(SUBSTRING(mo.CustomProp, (16 + len(MO.BoxId)), len(mo.CustomProp) - (16 + len(mo.BoxId))),'MIN','MIN='),'MAX','MAX=') end as Inputs,
CreatedDateTime=dbo.rvlf_fn_DayLightSavings(@dtFromdateTime,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime) ,
CreatedDateTimeSort=SentDateTime,
EffectiveToSort=dbo.rvlf_fn_DayLightSavings(@dtFromdateTime,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime),
RetriesPeriod=dbo.rvlf_fn_DayLightSavings(@dtFromdateTime,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime),
ExecutionOn1=dbo.rvlf_fn_DayLightSavings(@dtFromdateTime,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime),
case when Acknowledged is null then 
case when dateadd(MI,30,dateadd(HH,6,SentDateTime))>= getdate() then 'Pending' else 'Expired' end
	when Acknowledged=0 then
	'Expired'
	else
	case when MI.CustomProp is not null then 
		 case when dbo.rvlf_fn_GetParamValueWithIndex(MI.CustomProp,'Status=',';')=0 then 'Fail' else 'Success' end else '-' end
	end as commandStatus ,MO.ScheduleId,'' as SMSStatus,case when mo.MessageInID is null then 'No' else 'Yes' end as Acknowledged,ExecutionOn=case when MI.OriginDateTime is null then '-' else cast(dbo.rvlf_fn_DayLightSavings(@dtFromdateTime,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,MI.OriginDateTime) as varchar(50)) end from rvlfMsgOutHst MO INNER JOIN rvlfBoxCmdOutType C ON C.BoxCmdOutTypeId=MO.BoxCmdOutTypeId inner join rvlfmakdevices MD on md.boxid=mo.boxid INNER JOIN rvlfFleetVehicles FV ON FV.VehicleId=MD.VehicleId   
	left join rvlfMsgInHst MI on MI.MessageInID=MO.MessageInID
   INNER JOIN rvlfFleet F ON F.FleetId=FV.FleetId  WHERE (@bigFleetId IS NULL OR @bigFleetId='' OR F.FleetId=@bigFleetId)  
   AND md.OrganizationId =@bigOrganizationId   
   AND MD.VehicleId=@bigVehicleId
   and cast(mo.SentDateTime as date) between cast(@dtFromdateTime as date) and cast(@dtTodateTime as date) 
   ORDER BY CreatedDateTimeSort desc 
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetIdlingInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvlf_sp_GetIdlingInfo]  
    @bigFleetID bigint = NULL,  
 @intBoxID int =NULL,  
 @dtStartDate datetime =NULL,  
 @dtEndDate datetime = NULL,  
 @bigQueryingUser bigint = NULL,  
 @bigOrganizationID bigint = NULL  
as  
/******************************************************************************/  
-- Name  : rvlf_sp_GetIdlingInfo null,null,'2010/12/20 08:00:00','2010/12/31 17:00:00',62,40  
-- Description : To get the Idling information  
--    :   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin  
-- Author  : Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 09-DEc-2010 Created with optimization  
--    : 04-Feb-2011 TSK Modified to show LandmarkName instead of StreetAddress  
/******************************************************************************/  
  
BEGIN  
    SET NOCOUNT ON    
   
   
 IF @bigFleetID IS NULL  
  BEGIN  
   SELECT @bigFleetID=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 = @bigQueryingUser  
   
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))  
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))  
   
 DECLARE @tblTripDetailsForTD TABLE(  
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,  
  [BoxId] [int] NOT NULL,  
  [StartDate] [datetime] NOT NULL,  
  [EndDate] [datetime] NULL,  
  [OdometerStart] [bigint] NOT NULL,  
  [OdometerEnd] [bigint] NULL,  
  [IsTripClosed] [bit] NULL,  
  [IdlingDuration] [int] NULL,  
  [StopTime] [int] NULL,  
  [StartAddress] nvarchar(300) NULL,  
  [EndAddress] nvarchar(300) NULL  
 )  
  
 DECLARE @intDuration int  
 DECLARE @dtOriginDateTime datetime  
 DECLARE @bigOdoMeterReading int  
 DECLARE @bitIgnitionStatus bit  
 DECLARE @vcStreetAddress nvarchar(250)  
 DECLARE @tiBoxMsgInTypeId tinyint  
 DECLARE @bigTripID bigint  
 DECLARE @intIterator int  
 DECLARE @canShowFuelMessage bit = 0  
   
 IF EXISTS (SELECT * FROM rvlfPackageOperations r  
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId  
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId  
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)  
   BEGIN  
    SET @canShowFuelMessage = 1  
   END  
  
 DECLARE @tblMessageForProcessingTrip TABLE (  
  [ProcessorID] [bigint] identity(1,1) NOT NULL,    
  [Boxid] [int] NOT NULL,  
  [OriginDateTime] [datetime] NOT NULL,  
  [BoxMsgInTypeId] [tinyint] NULL,  
  [OdoMeterReading] [int] NULL,  
  [IgnitionStatus] [bit] NULL,  
  [StreetAddress] [nvarchar](250) NOT NULL,    
  [CustomProp] [varchar](600) NULL,    
  [Speed] int NULL,  
  [SensorMask] varchar(250) NULL,  
  [TripId] [bigint] NULL,  
  [Duration] [int] NULL,  
  [SensorNo] [tinyint] NULL  
 )  
  
 DECLARE @tblBoxes TABLE (BoxID int)  
    
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId  
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or BoxId = @intBoxID) AND V.OrganizationId=@bigOrganizationID  
   ORDER BY BoxId   
  
 DECLARE @intBoxLooping int  
  
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes  
 WHILE @intBoxLooping IS NOT NULL  
   BEGIN   
   DECLARE @DTFIRST DATETIME=NULL,@DTEND DATETIME=NULL  
   --FIND THE FIRST IGNITION ON TIME BETWEEN THE FROM AND TO TIME  
    SELECT TOP 1 @DTFIRST=OriginDateTime FROM rvlfMsgInHst WHERE Boxid=@intBoxLooping AND BoxMsgInTypeId=2   
     AND OriginDateTime BETWEEN @dtStartDate and @dtEndDate AND cast( SUBSTRING(sensormask,6,1) as bit) = 1  
     ORDER BY OriginDateTime ASC  
    SELECT TOP 1 @DTEND=OriginDateTime FROM rvlfMsgInHst WHERE Boxid=@intBoxLooping AND BoxMsgInTypeId=3   
     AND OriginDateTime BETWEEN @dtStartDate and @dtEndDate AND cast( SUBSTRING(sensormask,6,1) as bit) = 0  
     ORDER BY OriginDateTime DESC                                    
      
    INSERT INTO @tblMessageForProcessingTrip (  
      Boxid, OriginDateTime, BoxMsgInTypeId, OdoMeterReading, IgnitionStatus, StreetAddress,       
     CustomProp, Speed,  
     SensorMask, Duration, SensorNo)  
      SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,  
       CAST( SUBSTRING (h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)+9,CHARINDEX(';',h.CustomProp,  
        CHARINDEX('Odometer=',h.CustomProp,1)) - (CHARINDEX('Odometer=',h.CustomProp,1)+9)) as int) as OdoMeterReading,  
       cast( SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,  
       --ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,  
       --Replace(ISNULL(h.StreetAddress,'Address is not resolved'),'''','\''')  as StAddress,  
       CASE WHEN (H.LandMarkID IS NULL OR H.LandMarkID = 0) THEN ISNULL(h.StreetAddress, 'Address is not resolved') ELSE ISNULL(L.LandmarkName,' ') END AS StreetAddress,  
       h.CustomProp,Speed   
       ,Case WHEN h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc   
        WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +  
        CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +  
        dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'  
        ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID,   
        h.OriginDateTime, @canShowFuelMessage)END,   
       CASE WHEN h.BoxMsgInTypeID = 9 THEN   
        CAST(dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeID, h.BoxId,0) as int) ELSE 0 END,  
       CASE WHEN h.BoxMsgInTypeId = 2 THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,  
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END  
        from rvlfMsgInHst h   
         INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
         LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID                
        where h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId IN (2,3,9)  
        AND 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 @DTFIRST and @DTEND           
          AND h.BoxID = @intBoxLooping  
        ORDER BY h.origindatetime ASC   
     
    SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping  
   END  
  
 SELECT @intIterator = MIN(ProcessorID) FROM @tblMessageForProcessingTrip WHERE TripId is NULL  
 WHILE @intIterator IS NOT NULL  
  BEGIN  
   SET @intBoxID = NULL; SET @dtOriginDateTime = NULL; SET @tiBoxMsgInTypeId = NULL;   
   SET @bigOdoMeterReading = NULL;SET @bitIgnitionStatus = NULL; SET @vcStreetAddress = NULL;   
   SET @intDuration = NULL; DECLARE @dtEndTrip datetime=null;  
   Declare @bigOdoEnd bigint=null;declare @bitIsTripClosed bit=0;declare @intIdlingDuration int=0;  
   declare @dtNextStartTime datetime=null;declare @vcEndAddress nvarchar(300)=null  
   SELECT  @intBoxID = Boxid, @dtOriginDateTime = OriginDateTime,   
     @tiBoxMsgInTypeId = BoxMsgInTypeId, @bigOdoMeterReading = OdoMeterReading,  
     @bitIgnitionStatus = IgnitionStatus,@vcStreetAddress = StreetAddress,   
     @intDuration = Duration      
   FROM @tblMessageForProcessingTrip WHERE ProcessorID=@intIterator and TripId is NULL  
  
   IF(@bitIgnitionStatus=1 AND @tiBoxMsgInTypeId=2)  
    BEGIN  
     DECLARE @DTENDTIME DATETIME=NULL  
    --NEXT IGNITION TIME       
     SELECT TOP 1 @dtNextStartTime=OriginDateTime,@bitIsTripClosed=1 FROM @tblMessageForProcessingTrip   
      WHERE BoxMsgInTypeId=2 AND Boxid =@intBoxID AND OriginDateTime>@dtOriginDateTime AND SensorNo = 3  
        
     IF(@dtNextStartTime IS NOT NULL)  
      BEGIN  
       SELECT TOP 1 @DTENDTIME=OriginDateTime,@bitIsTripClosed=1,@vcEndAddress=StreetAddress,  
        @bigOdoEnd=OdoMeterReading     
        FROM @tblMessageForProcessingTrip   
        WHERE BoxMsgInTypeId=3 AND Boxid =@intBoxID AND OriginDateTime>=@dtOriginDateTime   
         AND OriginDateTime<@dtNextStartTime  
      END  
     ELSE  
      BEGIN  
       SELECT TOP 1 @DTENDTIME=OriginDateTime,@bitIsTripClosed=1,@vcEndAddress=StreetAddress,  
        @bigOdoEnd=OdoMeterReading    
        FROM @tblMessageForProcessingTrip   
        WHERE BoxMsgInTypeId=3 AND Boxid =@intBoxID AND OriginDateTime>@dtOriginDateTime  
      END   
     IF(@DTENDTIME IS NOT NULL AND @dtOriginDateTime IS NOT NULL)  
      BEGIN  
       SET @intIdlingDuration=(SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)as int)),0)  
        FROM @tblMessageForProcessingTrip   
        WHERE BoxMsgInTypeId=9 AND BoxId=@intBoxID   
         AND OriginDateTime BETWEEN @dtOriginDateTime and @DTENDTIME  
         GROUP BY BoxId)  
       IF EXISTS(SELECT BOXID FROM @tblMessageForProcessingTrip WHERE Boxid=@intBoxID AND OriginDateTime BETWEEN @dtOriginDateTime and @DTENDTIME AND BoxMsgInTypeId=9 AND @intIdlingDuration=0)  
        BEGIN  
         DECLARE @dtIdilingOn datetime=null,@dtTamper datetime=null  
         SELECT @dtIdilingOn= OriginDateTime FROM @tblMessageForProcessingTrip WHERE Boxid=@intBoxID AND OriginDateTime BETWEEN @dtOriginDateTime and @DTENDTIME AND BoxMsgInTypeId=9   
         SELECT @dtTamper= OriginDateTime FROM rvlfMsgInHst WHERE Boxid=@intBoxID AND OriginDateTime BETWEEN @dtOriginDateTime and @DTENDTIME AND BoxMsgInTypeId=41   
         IF(@dtTamper IS NOT NULL)  
          SET @intIdlingDuration=ISNULL(DATEDIFF(SS,@dtIdilingOn,@dtTamper),0)  
         ELSE  
          SET @intIdlingDuration=ISNULL(DATEDIFF(SS,@dtIdilingOn,@DTENDTIME),0)            
        END  
          
      END   
           
      
      
   --INSERT THE TRIP DETAILS  
    INSERT INTO @tblTripDetailsForTD(BoxId,EndAddress,EndDate,IdlingDuration,IsTripClosed,OdometerEnd,OdometerStart,  
     StartAddress,StartDate,StopTime)    
     VALUES(@intBoxID,@vcEndAddress,@DTENDTIME,@intIdlingDuration,@bitIsTripClosed,@bigOdoEnd,@bigOdoMeterReading,  
       @vcStreetAddress,@dtOriginDateTime,DATEDIFF(S,@DTENDTIME,@dtNextStartTime))   
    SET @bigTripID=@@IDENTITY   
    END   
    UPDATE @tblMessageForProcessingTrip SET TripId = @bigTripID where Boxid=@intBoxID AND OriginDateTime>=@dtOriginDateTime AND OriginDateTime<=@DTENDTIME   
     
    SELECT @intIterator = MIN(ProcessorID) FROM @tblMessageForProcessingTrip WHERE ProcessorID > @intIterator and TripId is NULL  
  END  
    
 UPDATE @tblTripDetailsForTD SET StopTime = DATEDIFF(ss, EndDate, @dtEndDate) WHERE TripId=(SELECT MAX(TripId) FROM @tblTripDetailsForTD)  
  
--SELECT * FROM @tblTripDetailsForTD    
 SELECT t.TripId,t.BoxId,v.VehicleId,v.VehicleDescription,v.Vin,v.LicensePlate,m.MakeName, d.ModelName,v.ModelYear,  
 DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,StartDate)) as StartDate,  
 DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,EndDate)) as EndDate,StartAddress,EndAddress,  datediff(ss,t.startDate,t.EndDate) as TripDuration,  dbo.rvlf_fn_GetTimeFromSeconds(ABS(datediff(ss,t.startDate,t.EndDate))) as TripDurationFormatted,   
 ISNULL(IdlingDuration,0)AS IdlingDuration,  
 (Case WHEN ISNULL(IdlingDuration,0)= 0 THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(ABS(t.IdlingDuration)) END) as IdlingDurationFormatted,    
  --CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN 0    
  --ELSE ABS(CAST((t.IdlingDuration * 1.00 / datediff(ss,t.startDate,t.EndDate) * 100) as numeric(18,2)))END as IdlingPercentage,   
  CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN '-'  
  WHEN ABS(CAST((t.IdlingDuration * 1.00 / datediff(ss,t.startDate,t.EndDate) * 100) as numeric(18,2))) = 0 THEN '-'    
  ELSE ISNULL(CAST(ABS(CAST((t.IdlingDuration * 1.00 / datediff(ss,t.startDate,t.EndDate) * 100) as numeric(18,2))) as nvarchar),'-') END as IdlingPercentage,      
  100 - CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN 0 ELSE  
  CAST((t.IdlingDuration*1.00 / datediff(ss,t.startDate,t.EndDate)*100)   
  as numeric(18,2))END as RunnningPercentage,  
  t.StopTime StoppedTime,  
  dbo.rvlf_fn_GetTimeFromSeconds(ABS(t.StopTime)) as StoppedTimeFormatted,  
  CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN 0 ELSE  
  CAST((ISNULL(t.StopTime,0)*1.00 / (ISNULL(t.StopTime,0) + ABS(datediff(ss,t.startDate,t.EndDate))))*100 as numeric(18,2)) END as StopPercentage,   
  CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN 0 ELSE  
  CAST(( ABS(datediff(ss,t.startDate,t.EndDate))*1.00 / (ISNULL(t.StopTime,0) + ABS(datediff(ss,t.startDate,t.EndDate))))*100   
  as numeric(18,2))END as OnPercentage,  
  ABS(OdometerEnd-OdometerStart) AS DistanceTravelled,   
  CASE WHEN IsTripClosed = 0 THEN 'Ongoing' ELSE 'Compeleted' END TripStatus from @tblTripDetailsForTD t  
   inner join rvlfVehicleAssignment va on va.BoxId =t.BoxId   
   inner join rvlfVehicle v on v.VehicleId=va.VehicleId   
   LEFT OUTER JOIN rvlfMake m ON v.MakeId =m.MakeId  
   LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId  
  WHERE t.startDate IS not NULL AND t.EndDate is not null  
  ORDER BY T.TripId  
     
 SELECT v.VehicleId,v.VehicleDescription,  
 CASE WHEN SUM(datediff(ss,startDate,EndDate)) = 0 THEN 0 ELSE    
  ISNULL(ABS(CAST((SUM(IdlingDuration)*1.00 / SUM(datediff(ss,startDate,EndDate))*100)   
  as numeric(18,2))),0)END as IdlingPercentage,  
  100 - CASE WHEN SUM(datediff(ss,t.startDate,t.EndDate)) = 0 THEN 0 ELSE  
  ISNULL(CAST((SUM(t.IdlingDuration)*1.00 / SUM(datediff(ss,t.startDate,t.EndDate))*100)   
  as numeric(18,2)),0) END as RunningPercentage    
 from @tblTripDetailsForTD t  
  inner join rvlfVehicleAssignment va on va.BoxId =t.BoxId   
  inner join rvlfVehicle v on v.VehicleId=va.VehicleId   
  LEFT OUTER JOIN rvlfMake m ON v.MakeId =m.MakeId  
  LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId  
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  INNER JOIN rvlfFleet f ON fv.FleetId= f.FleetId   
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId   
  WHERE t.startDate IS not NULL AND t.EndDate is not null   
  GROUP BY t.BoxId, v.VehicleDescription,v.VehicleId ORDER BY VehicleId  
        
END  
  
  
  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetIdlingInfo_Old_09_Dec_2010]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetIdlingInfo_Old_09_Dec_2010]
	@bigFleetID bigint = Null,
	@intBoxID int = Null,
	@dtStartDate datetime =NULL,
	@dtEndDate datetime = NULL,
	@bigQueryingUser bigint = Null,
	@bigOrganizationID bigint = 0
AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetIdlingInfo 61,160,'2010/11/29 09:00:00','2010/11/29 17:00:00',62,40
--	Description	:	To get the Idling information
--				:   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin
--	Author		:	S. Jeyanthi
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	11-Nov-2010	SJ	Created Intial Version 	
/******************************************************************************/
BEGIN
		SET NOCOUNT ON 	
	
	IF @bigFleetID IS NULL
		BEGIN
			SELECT @bigFleetID=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 = @bigQueryingUser
	
	SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))
	SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))
	
	CREATE TABLE #tblTripDetailsForTD(
		[TripId] [bigint] NOT NULL,
		[BoxId] [int] NOT NULL,
		[StartDate] [datetime] NOT NULL,
		[EndDate] [datetime] NULL,
		[OdometerStart] [bigint] NOT NULL,
		[OdometerEnd] [bigint] NULL,
		[IsTripClosed] [bit] NULL,
		[IdlingDuration] [int] NULL,
		[StopTime] [int] NULL,
		[StartAddress] varchar(300) NULL,
		[EndAddress] varchar(300) NULL,
		[VIN] [varchar](20) NULL,
		[LicensePlate] [varchar](20) NULL,
		[VehDispName] [varchar](50) NULL,
		[MakeName] [varchar](200) NULL,
		[ModelName] [varchar](200) NULL,
		[ModelYear] [smallint] null
	)

	DECLARE @intDuration int
	DECLARE @dtOriginDateTime datetime
	DECLARE @bigOdoMeterReading int
	DECLARE @bitIgnitionStatus bit
	DECLARE @vcStreetAddress varchar(250)
	DECLARE @tiBoxMsgInTypeId tinyint
	DECLARE @lastIdlingDuration int 
	DECLARE @lastIdlingTime DateTime
	DECLARE @tiSensorNo tinyint
	DECLARE @bigTripID bigint
	DECLARE @intIterator int
	DECLARE @canShowFuelMessage bit = 0
	DECLARE @bigPreviousTripID bigint
	DECLARE @vcVIN varchar(20) = NULL
	DECLARE @vcLicensePlate varchar(20) =NULL
	DECLARE @vcVehDispName varchar(50) = NULL
	DECLARE @vcMakeName varchar (200) = NULL
	DECLARE @vcModelName varchar(200) = NULL
	DECLARE @intModelYear smallint = NULL

	IF EXISTS (SELECT * FROM rvlfPackageOperations r
		INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId
		INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId
		WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)
			BEGIN
				SET @canShowFuelMessage = 1
			END

	CREATE TABLE #tblMessageForProcessingTrip (
		[ProcessorID] [bigint] identity(1,1) NOT NULL,
		[MessageInId] [uniqueidentifier] NOT NULL,
		[Boxid] [int] NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[OdoMeterReading] [int] NULL,
		[IgnitionStatus] [bit] NULL,
		[StreetAddress] [varchar](250) NOT NULL,
		[VehicleId] [bigint] NOT NULL,
		[VIN] [varchar](20) NULL,
		[LicensePlate] [varchar](20) NULL,
		[VehDispName] [varchar](50) NULL,
		[MakeName] [varchar](200) NULL,
		[ModelName] [varchar](200) NULL,
		[ModelYear] [smallint] null, 
		[CustomProp] [varchar](600) NULL,
		[BoxMsgInTypeDesc] varchar(100) NULL,
		[Speed] int NULL,
		[SensorMask] varchar(250) NULL,
		[TripId] [bigint] NULL,
		[Duration] [int] NULL,
		[SensorNo] [tinyint] NULL
	)

	CREATE INDEX IDX_RVLT_Processor on #tblMessageForProcessingTrip(ProcessorID)

	CREATE INDEX IDX_RVLT_Trips On #tblTripDetailsForTD (BoxId,IsTripClosed)
	DECLARE @tblBoxes TABLE (BoxID int, StartDate DateTime, EndDate DateTime)
		
		INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va 
			INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
			INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
			WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL or BoxId = @intBoxID)
			
	DECLARE @intBoxLooping int
		DECLARE @dtFirstDate datetime
		DECLARE @dtLastDate datetime
		SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes
		WHILE @intBoxLooping IS NOT NULL
			BEGIN
				SELECT TOP 1 @bitIgnitionStatus = cast( SUBSTRING(SensorMask,6,1) as bit), @tiBoxMsgInTypeId = BoxMsgInTypeId,
					@dtOriginDateTime = OriginDateTime, @tiSensorNo = CASE WHEN BoxMsgInTypeId = 2 
						THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,
							CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END
				FROM rvlfMsgInHst where BoxId= @intBoxLooping and OriginDateTime between @dtStartDate and @dtEndDate
					AND CustomProp like '%Odometer%' and BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)
				ORDER BY OriginDateTime asc
				print @dtStartDate ; print @dtEndDate
				print @dtOriginDateTime
				SET @dtFirstDate = NULL; SET @dtLastDate= NULL
				IF @bitIgnitionStatus = 1 and @tiBoxMsgInTypeId <> 2
					BEGIN
					print 123
						SELECT TOP 1 @dtOriginDateTime = OriginDateTime FROM rvlfMsgInHst 
							WHERE BoxId= @intBoxLooping and BoxMsgInTypeId = 2 
								and SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,
								CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) = '3' 
								AND OriginDateTime <= @dtOriginDateTime
							ORDER BY OriginDateTime desc
						SET @dtFirstDate =  @dtOriginDateTime
					END
				ELSE IF @tiBoxMsgInTypeId = 2 AND @tiSensorNo = 3
					BEGIN
					print 456
						SET @dtFirstDate = @dtOriginDateTime
					END
				ELSE 
					BEGIN
					print 789
						SELECT TOP 1 @dtOriginDateTime = OriginDateTime FROM rvlfMsgInHst 
							WHERE BoxId= @intBoxLooping and BoxMsgInTypeId = 2 
								and SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,
								CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) = '3' 
								AND OriginDateTime >= @dtStartDate
							ORDER BY OriginDateTime asc
						SET @dtFirstDate =  @dtOriginDateTime
					END
				
				SELECT TOP 1 @bitIgnitionStatus = cast( SUBSTRING(SensorMask,6,1) as bit), @tiBoxMsgInTypeId = BoxMsgInTypeId,
					@dtOriginDateTime = OriginDateTime
				FROM rvlfMsgInHst where BoxId= @intBoxLooping and OriginDateTime between @dtStartDate and @dtEndDate
					AND CustomProp like '%Odometer%' and BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)
				ORDER BY OriginDateTime desc
				
				IF @bitIgnitionStatus = 1
					BEGIN
						SELECT TOP 1 @dtOriginDateTime = OriginDateTime FROM rvlfMsgInHst 
							WHERE BoxId= @intBoxLooping and BoxMsgInTypeId = 3 
								AND OriginDateTime >= @dtOriginDateTime
							ORDER BY OriginDateTime asc
						SET @dtLastDate = @dtOriginDateTime
					END
				ELSE IF @bitIgnitionStatus = 0 or @tiBoxMsgInTypeID = 3
					BEGIN
						SET @dtLastDate = @dtOriginDateTime
					END
				ELSE 
					BEGIN
						SELECT TOP 1 @dtOriginDateTime = OriginDateTime FROM rvlfMsgInHst 
							WHERE BoxId= @intBoxLooping and BoxMsgInTypeId = 3 
								AND OriginDateTime <= @dtEndDate
							ORDER BY OriginDateTime desc
						SET @dtLastDate =  @dtOriginDateTime
					END
				print @dtFirstDate ; print @dtLastDate
				INSERT INTO #tblMessageForProcessingTrip (
					MessageInId, Boxid, OriginDateTime, BoxMsgInTypeId, OdoMeterReading, IgnitionStatus, StreetAddress,
					VehicleId, VIN, LicensePlate, VehDispName, MakeName, ModelName,ModelYear,
					CustomProp, BoxMsgInTypeDesc, Speed,
					SensorMask, Duration, SensorNo)
						SELECT h.MessageInId,h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,
							CAST( SUBSTRING (h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)+9,CHARINDEX(';',h.CustomProp,
								CHARINDEX('Odometer=',h.CustomProp,1)) - (CHARINDEX('Odometer=',h.CustomProp,1)+9)) as int) as OdoMeterReading,
							cast( SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,
							ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,v.VehicleId,v.VIN,v.LicensePlate, 
							v.VehicleDescription,mk.MakeName, md.ModelName,ModelYear, 
							h.CustomProp, m.BoxMsgInTypeDesc, Speed 
							,Case WHEN h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc 
								WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +
								CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +
								dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'
								ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID, 
								h.OriginDateTime, @canShowFuelMessage)END, 
							CASE WHEN h.BoxMsgInTypeID = 9 THEN 
								CAST(dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeID, h.BoxId,0) as int) ELSE 0 END,
							CASE WHEN h.BoxMsgInTypeId = 2 THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,
								CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END
								from rvlfMsgInHst h 
									INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId
									INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
									INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
									LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId
									LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId
									INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId
									INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId
									INNER JOIN rvlfOrganization g ON v.OrganizationId = g.OrganizationId
								where h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)
								AND 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 ( @bigFleetID IS NULL  OR f.FleetId = @bigFleetID) 									
										AND h.OriginDateTime between @dtStartDate and @dtEndDate								
										AND h.BoxID = @intBoxLooping
									order by h.origindatetime asc, h.MessageInID asc
				SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes WHERE BoxID < @intBoxLooping
			END


 SELECT @intIterator = MIN(ProcessorID) FROM #tblMessageForProcessingTrip WHERE TripId is NULL    
  WHILE @intIterator IS NOT NULL    
  BEGIN    
   SET @intBoxID = NULL; SET @dtOriginDateTime = NULL; SET @tiBoxMsgInTypeId = NULL; SET @bigOdoMeterReading = NULL;     
   SET @bitIgnitionStatus = NULL; SET @vcStreetAddress = NULL; SET @intDuration = NULL; SET @tiSensorNo = NULL    
   SELECT  @intBoxID = Boxid, @dtOriginDateTime = OriginDateTime,     
     @tiBoxMsgInTypeId = BoxMsgInTypeId, @bigOdoMeterReading = OdoMeterReading,    
     @bitIgnitionStatus = IgnitionStatus,@vcStreetAddress = StreetAddress,     
     @intDuration = Duration, @tiSensorNo = SensorNo,    
     @vcVIN = VIN, @vcLicensePlate  = LicensePlate, @vcVehDispName  = VehDispName, @vcMakeName = MakeName,    
     @vcModelName = ModelName , @intModelYear=ModelYear  
   FROM #tblMessageForProcessingTrip WHERE ProcessorID=@intIterator    
   
   DECLARE @bigEndOdoMeterReading bigint;
   SET @bigEndOdoMeterReading = NULL; 
			
    SELECT top 1 @bigEndOdoMeterReading =OdoMeterReading from #tblMessageForProcessingTrip where Boxid=@intBoxID order by ProcessorID desc
			
    
   SELECT @bigTripID = ISNULL(MAX(TripID),0) FROM #tblTripDetailsForTD WHERE BoxID = @intBoxID     
    AND IsTripClosed = 0    
    IF (@bitIgnitionStatus = 1 AND @tiBoxMsgInTypeId=2) 
			BEGIN		
				DECLARE @dtENDTIME DATETIME=NULL,@dtSTARTTIME DATETIME=NULL
				SELECT TOP 1 @dtENDTIME=OriginDateTime,@dtSTARTTIME=@dtOriginDateTime  FROM #tblMessageForProcessingTrip WHERE OriginDateTime>@dtOriginDateTime AND BoxMsgInTypeId=3AND Boxid=@intBoxID						
			END		

    IF @intDuration > 0     
     BEGIN    
      UPDATE #tblTripDetailsForTD SET IdlingDuration = IdlingDuration + @intDuration     
       WHERE TripID = @bigTripID     
     END    
        
    IF @bitIgnitionStatus = 1 AND @bigTripID = 0 AND @tiBoxMsgInTypeId = 2 AND @tiSensorNo = 3    
     BEGIN    
      SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM #tblTripDetailsForTD     
       WHERE BoxId = @intBoxID     
      SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM #tblTripDetailsForTD    
      INSERT INTO #tblTripDetailsForTD     
        (TripId, BoxId, StartDate, OdometerStart, OdometerEnd,    
         IsTripClosed, IdlingDuration, StartAddress, VIN, LicensePlate, VehDispName,     
         MakeName, ModelName,ModelYear)    
        VALUES     
        (@bigTripID, @intBoxID, @dtOriginDateTime, @bigOdoMeterReading ,     
         @bigEndOdoMeterReading,0,0, @vcStreetAddress, @vcVIN, @vcLicensePlate, @vcVehDispName, @vcMakeName, @vcModelName,@intModelYear)    
           
      UPDATE #tblTripDetailsForTD SET StopTime = DATEDIFF(ss, EndDate, @dtOriginDateTime)     
      WHERE BoxId = @intBoxID 
       AND TripID = @bigPreviousTripID           
     END    
    ELSE IF @bitIgnitionStatus = 0 AND @tiBoxMsgInTypeId = 3    
     BEGIN    
		set @lastIdlingDuration = 1    
      select TOP 1 @lastIdlingDuration = CAST(dbo.rvlf_fn_GetDuration(CustomProp,     
       BoxMsgInTypeID, BoxID, 0)as int) , @lastIdlingTime = OriginDateTime    
        FROM rvlfmsginhst where BoxId = @intBoxID    
         AND OriginDateTime <= @dtOriginDateTime  AND OriginDateTime>=@dtSTARTTIME AND OriginDateTime<=@dtENDTIME   
         AND BoxMsgInTypeId = 9 order by Origindatetime desc--, MessageInID asc    
         
      IF @lastIdlingDuration = 0     
       BEGIN    
		 SET @lastIdlingDuration = ISNULL(DATEDIFF (SS, @lastIdlingTime, @dtOriginDateTime),0)    
         --SET @lastIdlingDuration = 0
       END    
      ELSE    
       BEGIN    
        SET @lastIdlingDuration = 0
       END    
           
      DECLARE @nextTripStart Datetime = null    
      SELECT TOP 1 @nextTripStart = OrigindateTime    
       from rvlfMsgInHst where OriginDateTime > @dtOriginDateTime    
       AND BoxMsgInTypeId = 2 AND CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,    
       CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) = 3    
       AND BoxId= @intBoxID    
       Order by OriginDateTime asc    
           
      UPDATE #tblTripDetailsForTD SET     
       EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL     
       THEN OdometerEnd ELSE @bigOdoMeterReading END,    
       IsTripClosed = 1, EndAddress = @vcStreetAddress,     
       IdlingDuration = IdlingDuration + @lastIdlingDuration,
       StopTime = DATEDIFF(ss,@dtOriginDateTime, @nextTripStart)    
      WHERE TripID = @bigTripID AND BoxId = @intBoxID    
     END    
    UPDATE #tblMessageForProcessingTrip SET TripId = @bigTripID where ProcessorID=@intIterator    
    SELECT @intIterator = MIN(ProcessorID) FROM #tblMessageForProcessingTrip WHERE ProcessorID > @intIterator and TripId is NULL    
  END  
		
UPDATE #tblTripDetailsForTD SET StopTime = DATEDIFF(ss, EndDate, @dtEndDate) WHERE TripId=(SELECT MAX(TripId) FROM #tblTripDetailsForTD)
	
	SELECT t.TripId,t.BoxId,v.VehicleId,v.VehicleDescription,v.Vin,v.LicensePlate,m.MakeName, d.ModelName,v.ModelYear,
	DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,StartDate)) as StartDate,
	DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,EndDate)) as EndDate,StartAddress,EndAddress,
	datediff(ss,t.startDate,t.EndDate) as TripDuration,
	dbo.rvlf_fn_GetTimeFromSeconds(ABS(datediff(ss,t.startDate,t.EndDate))) as TripDurationFormatted,	
	IdlingDuration,
	(Case WHEN IdlingDuration= 0 THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(ABS(t.IdlingDuration)) END) as IdlingDurationFormatted,	
		
		CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN '-'
		WHEN ABS(CAST((t.IdlingDuration * 1.00 / datediff(ss,t.startDate,t.EndDate) * 100) as numeric(18,2))) = 0 THEN '-'		
		ELSE CAST(ABS(CAST((t.IdlingDuration * 1.00 / datediff(ss,t.startDate,t.EndDate) * 100) as numeric(18,2))) as nvarchar) END as IdlingPercentage, 				
		
		100 - CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN 0 ELSE
		CAST((t.IdlingDuration*1.00 / datediff(ss,t.startDate,t.EndDate)*100) 
		as numeric(18,2))END as RunnningPercentage,
		t.StopTime StoppedTime,
		dbo.rvlf_fn_GetTimeFromSeconds(ABS(t.StopTime)) as StoppedTimeFormatted,
		CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN 0 ELSE
		CAST((ISNULL(t.StopTime,0)*1.00 / (ISNULL(t.StopTime,0) + ABS(datediff(ss,t.startDate,t.EndDate))))*100 as numeric(18,2)) END as StopPercentage,	
		CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN 0 ELSE
		CAST(( ABS(datediff(ss,t.startDate,t.EndDate))*1.00 / (ISNULL(t.StopTime,0) + ABS(datediff(ss,t.startDate,t.EndDate))))*100 
		as numeric(18,2))END as OnPercentage,
		ABS(OdometerEnd-OdometerStart) AS DistanceTravelled, 
		CASE WHEN IsTripClosed = 0 THEN 'Ongoing' ELSE 'Compeleted' END TripStatus from #tblTripDetailsForTD t
			inner join rvlfVehicleAssignment va on va.BoxId =t.BoxId 
			inner join rvlfVehicle v on v.VehicleId=va.VehicleId 
			LEFT OUTER JOIN rvlfMake m ON v.MakeId =m.MakeId
			LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId 
			
			
--select v.VehicleId,v.VehicleDescription,
--	CASE WHEN SUM(datediff(ss,startDate,EndDate)) = 0 THEN 0 ELSE		
--		ABS(CAST((SUM(IdlingDuration)*1.00 / SUM(datediff(ss,startDate,EndDate))*100) 
--		as numeric(18,2)))END as IdlingPercentage,
--		100 - CASE WHEN SUM(datediff(ss,t.startDate,t.EndDate)) = 0 THEN 0 ELSE
--		CAST((SUM(t.IdlingDuration)*1.00 / SUM(datediff(ss,t.startDate,t.EndDate))*100) 
--		as numeric(18,2))END as RunningPercentage
	
	SELECT v.VehicleId,v.VehicleDescription,
	CASE WHEN SUM(datediff(ss,startDate,EndDate)) = 0 THEN 0 ELSE		
		ISNULL(ABS(CAST((SUM(IdlingDuration)*1.00 / SUM(datediff(ss,startDate,EndDate))*100) 
		as numeric(18,2))),0)END as IdlingPercentage,
		100 - CASE WHEN SUM(datediff(ss,t.startDate,t.EndDate)) = 0 THEN 0 ELSE
		ISNULL(CAST((SUM(t.IdlingDuration)*1.00 / SUM(datediff(ss,t.startDate,t.EndDate))*100) 
		as numeric(18,2)),0) END as RunningPercentage	
				 	
	from #tblTripDetailsForTD t
		LEFT join rvlfVehicleAssignment va on va.BoxId =t.BoxId 
		LEFT join rvlfVehicle v on v.VehicleId=va.VehicleId 
		LEFT OUTER JOIN rvlfMake m ON v.MakeId =m.MakeId
		LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId
		INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId
		INNER JOIN rvlfFleet f ON fv.FleetId= f.FleetId 
		INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId			
		GROUP BY t.BoxId, v.VehicleDescription,v.VehicleId 		
		
		
		DROP Table #tblMessageForProcessingTrip
		DROP Table #tblTripDetailsForTD

END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetIdlingInfo_Test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvlf_sp_GetIdlingInfo_Test]

 @bigFleetID bigint = 61,
	@intBoxID int =159,
	--@dtStartDate datetime ='2010/11/29 08:00:00',
	--@dtEndDate datetime = '2010/11/30 00:00:00',
	@dtStartDate datetime ='2010-11-29 06:20:43.000', -- '2010-11-29 08:00:00',
	@dtEndDate datetime = ' 2010-11-29 06:59:17.000',--'2010-11-29 20:00:00',
	@bigQueryingUser bigint = 62,
	@bigOrganizationID bigint = 40
AS
BEGIN
		SET NOCOUNT ON 	
	
	
	IF @bigFleetID IS NULL
		BEGIN
			SELECT @bigFleetID=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 = @bigQueryingUser
	
	SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))
	SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))
	
	DECLARE @tblTripDetailsForTD TABLE(
		[TripId] [bigint]IDENTITY(1,1) NOT NULL,
		[BoxId] [int] NOT NULL,
		[StartDate] [datetime] NOT NULL,
		[EndDate] [datetime] NULL,
		[OdometerStart] [bigint] NOT NULL,
		[OdometerEnd] [bigint] NULL,
		[IsTripClosed] [bit] NULL,
		[IdlingDuration] [int] NULL,
		[StopTime] [int] NULL,
		[StartAddress] varchar(300) NULL,
		[EndAddress] varchar(300) NULL,
		Speed int NULL
	)

	DECLARE @intDuration int
	DECLARE @dtOriginDateTime datetime
	DECLARE @bigOdoMeterReading int
	DECLARE @bitIgnitionStatus bit
	DECLARE @vcStreetAddress varchar(250)
	DECLARE @tiBoxMsgInTypeId tinyint
	DECLARE @bigTripID bigint
	DECLARE @intIterator int
	DECLARE @canShowFuelMessage bit = 0
	
	IF EXISTS (SELECT * FROM rvlfPackageOperations r
		INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId
		INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId
		WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)
			BEGIN
				SET @canShowFuelMessage = 1
			END

	DECLARE @tblMessageForProcessingTrip TABLE (
		[ProcessorID] [bigint] identity(1,1) NOT NULL,		
		[Boxid] [int] NOT NULL,
		[OriginDateTime] [datetime] NOT NULL,
		[BoxMsgInTypeId] [tinyint] NULL,
		[OdoMeterReading] [int] NULL,
		[IgnitionStatus] [bit] NULL,
		[StreetAddress] [varchar](250) NOT NULL,		
		[CustomProp] [varchar](600) NULL,		
		[Speed] int NULL,
		[SensorMask] varchar(250) NULL,
		[TripId] [bigint] NULL,
		[Duration] [int] NULL,
		[SensorNo] [tinyint] NULL
	)

	DECLARE @tblBoxes TABLE (BoxID int)
		
	INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va 
			INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
			INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
			WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL or BoxId = @intBoxID) AND V.OrganizationId=@bigOrganizationID

	DECLARE @intBoxLooping int
	
	SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes
	WHILE @intBoxLooping IS NOT NULL
			BEGIN								
				INSERT INTO @tblMessageForProcessingTrip (
					 Boxid, OriginDateTime, BoxMsgInTypeId, OdoMeterReading, IgnitionStatus, StreetAddress,					
					CustomProp, Speed,
					SensorMask, Duration, SensorNo)
						SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,
							CAST( SUBSTRING (h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)+9,CHARINDEX(';',h.CustomProp,
								CHARINDEX('Odometer=',h.CustomProp,1)) - (CHARINDEX('Odometer=',h.CustomProp,1)+9)) as int) as OdoMeterReading,
							cast( SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,
							ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,
							h.CustomProp,Speed 
							,Case WHEN h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc 
								WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +
								CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +
								dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'
								ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID, 
								h.OriginDateTime, @canShowFuelMessage)END, 
							CASE WHEN h.BoxMsgInTypeID = 9 THEN 
								CAST(dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeID, h.BoxId,0) as int) ELSE 0 END,
							CASE WHEN h.BoxMsgInTypeId = 2 THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,
								CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END
								from rvlfMsgInHst h 
									INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId														
								where h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId IN (2,3,9,41)
								AND 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 = @intBoxLooping
								ORDER BY h.origindatetime ASC, h.MessageInID ASC
				
				SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes WHERE BoxID < @intBoxLooping
			END

	SELECT @intIterator = MIN(ProcessorID) FROM @tblMessageForProcessingTrip WHERE TripId is NULL
	
	WHILE @intIterator IS NOT NULL
		BEGIN
			SET @intBoxID = NULL; SET @dtOriginDateTime = NULL; SET @tiBoxMsgInTypeId = NULL; 
			SET @bigOdoMeterReading = NULL;SET @bitIgnitionStatus = NULL; SET @vcStreetAddress = NULL; 
			SET @intDuration = NULL; DECLARE @dtEndTrip datetime=null;
			Declare @bigOdoEnd bigint=null;declare @bitIsTripClosed bit=0;declare @intIdlingDuration int=0;
			declare @dtNextStartTime datetime=null;declare @vcEndAddress varchar(300)=null
			SELECT  @intBoxID = Boxid, @dtOriginDateTime = OriginDateTime, 
					@tiBoxMsgInTypeId = BoxMsgInTypeId, @bigOdoMeterReading = OdoMeterReading,
					@bitIgnitionStatus = IgnitionStatus,@vcStreetAddress = StreetAddress, 
					@intDuration = Duration				
			FROM @tblMessageForProcessingTrip WHERE ProcessorID=@intIterator

			IF(@bitIgnitionStatus=1 AND @tiBoxMsgInTypeId=2)
				BEGIN
					DECLARE @DTENDTIME DATETIME=NULL
				--NEXT IGNITION TIME					
					SELECT TOP 1 @dtNextStartTime=OriginDateTime,@bitIsTripClosed=1 FROM @tblMessageForProcessingTrip 
						WHERE BoxMsgInTypeId=2 AND Boxid =@intBoxID AND OriginDateTime>@dtOriginDateTime 
					IF(@dtNextStartTime IS NOT NULL)
						BEGIN
							SELECT TOP 1 @DTENDTIME=OriginDateTime,@bitIsTripClosed=1,@vcEndAddress=StreetAddress,
								@bigOdoEnd=OdoMeterReading   
								FROM @tblMessageForProcessingTrip 
								WHERE BoxMsgInTypeId=3 AND Boxid =@intBoxID AND OriginDateTime>=@dtOriginDateTime 
									AND OriginDateTime<@dtNextStartTime  
						END
					ELSE
						BEGIN
							SELECT TOP 1 @DTENDTIME=OriginDateTime,@bitIsTripClosed=1,@vcEndAddress=StreetAddress,
								@bigOdoEnd=OdoMeterReading  
								FROM @tblMessageForProcessingTrip 
								WHERE BoxMsgInTypeId=3 AND Boxid =@intBoxID AND OriginDateTime>@dtOriginDateTime
						END	
					IF(@DTENDTIME IS NOT NULL AND @dtOriginDateTime IS NOT NULL)
						BEGIN
							SET @intIdlingDuration=(SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)as int)),0)
								FROM @tblMessageForProcessingTrip 
								WHERE BoxMsgInTypeId=9 AND BoxId=@intBoxID 
									AND OriginDateTime BETWEEN @dtOriginDateTime and @DTENDTIME
									GROUP BY BoxId)
							IF EXISTS(SELECT BOXID FROM @tblMessageForProcessingTrip WHERE Boxid=@intBoxID AND OriginDateTime BETWEEN @dtOriginDateTime and @DTENDTIME AND BoxMsgInTypeId=9 AND @intIdlingDuration=0)
								BEGIN
									DECLARE @dtIdilingOn datetime=null,@dtTamper datetime=null
									SELECT @dtIdilingOn= OriginDateTime FROM @tblMessageForProcessingTrip WHERE Boxid=@intBoxID AND OriginDateTime BETWEEN @dtOriginDateTime and @DTENDTIME AND BoxMsgInTypeId=9 
									SELECT @dtTamper= OriginDateTime FROM @tblMessageForProcessingTrip WHERE Boxid=@intBoxID AND OriginDateTime BETWEEN @dtOriginDateTime and @DTENDTIME AND BoxMsgInTypeId=41 
									IF(@dtTamper IS NOT NULL)
										SET @intIdlingDuration=ISNULL(DATEDIFF(SS,@dtIdilingOn,@dtTamper),0)
									ELSE
										SET @intIdlingDuration=ISNULL(DATEDIFF(SS,@dtIdilingOn,@DTENDTIME),0)										
								END
								
						END					
					ELSE
						BEGIN
							DELETE FROM @tblMessageForProcessingTrip WHERE Boxid=@intBoxID AND OriginDateTime <=@dtOriginDateTime
						END
				
				DECLARE @maxSpeed int =(Select MAX(speed) from @tblMessageForProcessingTrip where OriginDateTime between 
				@dtOriginDateTime and @DTENDTIME)
			--INSERT THE TRIP DETAILS
				INSERT INTO @tblTripDetailsForTD(BoxId,EndAddress,EndDate,IdlingDuration,IsTripClosed,OdometerEnd,OdometerStart,
					StartAddress,StartDate,StopTime,speed)  
					VALUES(@intBoxID,@vcEndAddress,@DTENDTIME,@intIdlingDuration,@bitIsTripClosed,@bigOdoEnd,@bigOdoMeterReading,
					  @vcStreetAddress,@dtOriginDateTime,DATEDIFF(S,@DTENDTIME,@dtNextStartTime),@maxSpeed) 
				SET @bigTripID=@@IDENTITY 
				END	
				UPDATE @tblMessageForProcessingTrip SET TripId = @bigTripID where Boxid=@intBoxID AND OriginDateTime>=@dtOriginDateTime AND OriginDateTime<=@DTENDTIME 
				SELECT @intIterator = MIN(ProcessorID) FROM @tblMessageForProcessingTrip WHERE ProcessorID > @intIterator and TripId is NULL
		END
		
	UPDATE @tblTripDetailsForTD SET StopTime = DATEDIFF(ss, EndDate, @dtEndDate) WHERE TripId=(SELECT MAX(TripId) FROM @tblTripDetailsForTD)
--SELECT * FROM @tblMessageForProcessingTrip 
--SELECT * FROM @tblTripDetailsForTD 	
	SELECT t.TripId,t.BoxId,v.VehicleId,v.VehicleDescription,v.Vin,v.LicensePlate,m.MakeName, d.ModelName,v.ModelYear,
	DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,StartDate)) as StartDate,
	DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,EndDate)) as EndDate,StartAddress,EndAddress,
	datediff(ss,t.startDate,t.EndDate) as TripDuration,
	dbo.rvlf_fn_GetTimeFromSeconds(ABS(datediff(ss,t.startDate,t.EndDate))) as TripDurationFormatted,	
	ISNULL(IdlingDuration,0)AS IdlingDuration,
	(Case WHEN ISNULL(IdlingDuration,0)= 0 THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(ABS(t.IdlingDuration)) END) as IdlingDurationFormatted,		
		CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN 0 	
		ELSE ABS(CAST((t.IdlingDuration * 1.00 / datediff(ss,t.startDate,t.EndDate) * 100) as numeric(18,2)))END as IdlingPercentage, 				
		100 - CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN 0 ELSE
		CAST((t.IdlingDuration*1.00 / datediff(ss,t.startDate,t.EndDate)*100) 
		as numeric(18,2))END as RunnningPercentage,
		t.StopTime StoppedTime,
		dbo.rvlf_fn_GetTimeFromSeconds(ABS(t.StopTime)) as StoppedTimeFormatted,
		CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN 0 ELSE
		CAST((ISNULL(t.StopTime,0)*1.00 / (ISNULL(t.StopTime,0) + ABS(datediff(ss,t.startDate,t.EndDate))))*100 as numeric(18,2)) END as StopPercentage,	
		CASE WHEN datediff(ss,t.startDate,t.EndDate) = 0 THEN 0 ELSE
		CAST(( ABS(datediff(ss,t.startDate,t.EndDate))*1.00 / (ISNULL(t.StopTime,0) + ABS(datediff(ss,t.startDate,t.EndDate))))*100 
		as numeric(18,2))END as OnPercentage,
		ABS(OdometerEnd-OdometerStart) AS DistanceTravelled, 
		CASE WHEN IsTripClosed = 0 THEN 'Ongoing' ELSE 'Compeleted' END TripStatus from @tblTripDetailsForTD t
			inner join rvlfVehicleAssignment va on va.BoxId =t.BoxId 
			inner join rvlfVehicle v on v.VehicleId=va.VehicleId 
			LEFT OUTER JOIN rvlfMake m ON v.MakeId =m.MakeId
			LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId
			
	SELECT v.VehicleId,v.VehicleDescription,
	CASE WHEN SUM(datediff(ss,startDate,EndDate)) = 0 THEN 0 ELSE		
		ABS(CAST((SUM(IdlingDuration)*1.00 / SUM(datediff(ss,startDate,EndDate))*100) 
		as numeric(18,2)))END as IdlingPercentage,100 - CASE WHEN SUM(datediff(ss,t.startDate,t.EndDate)) = 0 THEN 0 ELSE
		CAST((SUM(t.IdlingDuration)*1.00 / SUM(datediff(ss,t.startDate,t.EndDate))*100) 
		as numeric(18,2))END as RunningPercentage	 	
	from @tblTripDetailsForTD t
		inner join rvlfVehicleAssignment va on va.BoxId =t.BoxId 
		inner join rvlfVehicle v on v.VehicleId=va.VehicleId 
		LEFT OUTER JOIN rvlfMake m ON v.MakeId =m.MakeId
		LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId
		INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId
		INNER JOIN rvlfFleet f ON fv.FleetId= f.FleetId 
		INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId
		GROUP BY t.BoxId, v.VehicleDescription,v.VehicleId 					
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetIdlingSummary]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetIdlingSummary]    
 @bigOrganizationID bigint=null,    
 @bigFleetID bigint = NULL,    
 @intBoxID varchar(max)=null,    
 @dtStartDate datetime=null,    
 @dtEndDate datetime=null,    
 @bigQueryingUser bigint=null      
AS    
/********************************************************************************************************/    
-- Name  : [rvlf_sp_GetIdlingSummary] 121,186,null,'2013-03-19 08:00:00 AM','2013-03-21 08:00:00 PM',303
-- Description : To get the Fleet idling summary details    
-- Author  : Narayanasamy    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--          : 25-Mar-2011 VN Created     
--          : 11-Aug-2011 Ranjith Date Format Included  
--          : 30-Nov-2011 Sakthi Distance calculation based on organization  
/********************************************************************************************************/    
BEGIN    
SET NOCOUNT ON  
   
 Declare @dtFDate datetime =@dtStartDate  
 Declare @dtEDate datetime =@dtEndDate  
 IF @bigFleetID IS NULL    
 BEGIN    
   SELECT @bigFleetID=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)    
 DECLARE @DefaultDateFormat INT = 0  
   
 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,  
 @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 = @bigQueryingUser    
        
        
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))    
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))        
      
 DECLARE @tblVehicles TABLE    
 (    
  VehicleId bigint,    
  VehicleDescription varchar(50),    
  LicensePlate varchar(50),    
  Vin varchar(50),    
  Boxid bigint,    
  NoofTrips int,    
  Distance int,    
  RunningTime INT,    
  IdlingTime INT,    
  NoofIdling int,    
  MaxIdling int,    
  FleetName varchar(50)    
 )    
   
 DECLARE @TBLSTART TABLE    
 (    
  Processid bigint identity(1,1),    
  Boxid int,    
  StartTime datetime,    
  Running int,    
  tripId int    
 )    
     
 DECLARE @TBLSTOP TABLE    
 (    
  Boxid int,    
  StopTime datetime,    
  tripId int    
 )     
    
 DECLARE @tblMessageForProcessingTrip TABLE (     
   [Boxid] [int] NOT NULL,    
   [OriginDateTime] [datetime] NOT NULL,    
   [BoxMsgInTypeId] [tinyint] NULL,      
   [Ignition] bit null,          
   [CustomProp] [varchar](600) 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 (@bigFleetID IS NULL OR @bigFleetID='' OR F.FleetId=@bigFleetID)    
 AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR VA.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))    
 ORDER BY BI.BOXID    
    
DECLARE @intBoxLoop int =(SELECT MIN(Boxid) FROM @tblVehicles)    
    
WHILE @intBoxLoop IS NOT NULL    
 BEGIN    
        
  DELETE FROM @tblMessageForProcessingTrip         
  INSERT INTO @tblMessageForProcessingTrip(Boxid,OriginDateTime,BoxMsgInTypeId,CustomProp,Ignition)    
  SELECT h.Boxid,h.OriginDateTime,h.BoxMsgInTypeId,h.CustomProp,CAST(SUBSTRING(sensormask,6,1) as bit)           
  FROM rvlfMsgInHst h INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                  
  WHERE h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId IN (2,3,9)    
  AND 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     
            
  -- GET THE IGNITION ON DETAILS    
  DELETE FROM @TBLSTART         
  INSERT INTO @TBLSTART (Boxid,StartTime)    
  SELECT @intBoxLoop,OriginDateTime     
  FROM @tblMessageForProcessingTrip           
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate     
  AND BoxMsgInTypeId IN(2) AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip     
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)    
  AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip     
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)      
  AND Ignition=1 AND CustomProp LIKE '%SENSOR_NUM=3%'  
         
  --GET THE IGNITION OFF DETAILS       
  DELETE FROM @TBLSTOP     
  INSERT INTO @TBLSTOP (Boxid,StopTime)    
  SELECT @intBoxLoop,OriginDateTime FROM @tblMessageForProcessingTrip      
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate     
  AND BoxMsgInTypeId IN(3) AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip     
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)    
  AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip     
  WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)      
  AND CustomProp LIKE '%SENSOR_NUM=3%'  
    
  --PREPARE THE TRIPS AND DETAILS    
  DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )     
  DECLARE @DTSTART DATETIME=null,@DTEND DATETIME=null      
  DECLARE @INC INT=1           
  WHILE @LOOP IS NOT NULL    
  BEGIN    
      SELECT TOP 1 @DTSTART=StartTime  FROM @TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR @DTEND='' OR StartTime >@DTEND)        
      SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART     
      UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART     
      UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND                 
      SET @INC =@INC +1          
      SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART          
  END               
     
  --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))    
  WHERE Boxid =@intBoxLoop AND Distance IS NULL    
     
  --CALCULATE THE NO OF IDLING    
  UPDATE @tblVehicles SET NoofIdling =(SELECT COUNT(BoxId) AS Actions     
  FROM @tblMessageForProcessingTrip WHERE BoxId=@intBoxLoop AND (OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)    
  AND BoxMsgInTypeId IN (9) AND CustomProp NOT LIKE '%Idling:0%')    
  WHERE Boxid =@intBoxLoop AND NoofIdling IS NULL    
      
  --CALCULATE THE MAX IDLING TIME    
  UPDATE @tblVehicles SET MaxIdling =(SELECT MAX(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT))    
  FROM @tblMessageForProcessingTrip WHERE BoxId=@intBoxLoop AND (OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)    
  AND BoxMsgInTypeId IN (9) AND CustomProp NOT LIKE '%Idling:0%')    
  WHERE Boxid =@intBoxLoop AND MaxIdling IS NULL    
    
  --CALCULATE THE NOOFTRIPS    
  UPDATE @tblVehicles SET NoofTrips =(SELECT COUNT(S.Boxid) FROM @TBLSTART S INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId)    
  WHERE Boxid =@intBoxLoop AND NoofTrips IS NULL    
      
  --RUNNING TIME     
  UPDATE @tblVehicles SET RunningTime =(SELECT SUM(DATEDIFF(S,S.StartTime,ST.StopTime))FROM @TBLSTART S INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId)    
  WHERE Boxid =@intBoxLoop AND RunningTime IS NULL    
      
  --IDLING TIME    
  UPDATE @tblVehicles SET IdlingTime =(SELECT SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,(CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7)))AS INT))    
  FROM @tblMessageForProcessingTrip WHERE BoxId=@intBoxLoop AND (OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)    
  AND BoxMsgInTypeId IN (9) AND CustomProp NOT LIKE '%Idling:0%')     
  WHERE Boxid =@intBoxLoop AND IdlingTime IS NULL           
    
  UPDATE @tblVehicles SET IdlingTime =CASE WHEN IdlingTime >RunningTime THEN RunningTime ELSE IdlingTime END WHERE Boxid =@intBoxLoop     
  SELECT @intBoxLoop = MIN(Boxid) FROM @tblVehicles WHERE Boxid >@intBoxLoop     
 END    
    
 DECLARE @totRunningTime int=null    
 DECLARE @totIdlingTime int=null    
    
 SELECT @totRunningTime=SUM(ISNULL(RunningTime,0)),@totIdlingTime =SUM(ISNULL(IdlingTime,0)) FROM @tblVehicles      
    
 SELECT Boxid,VehicleId,VehicleDescription,LicensePlate,ISNULL(NoofTrips,0) as NoofTrips,     
 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 as Distance ,   
 ISNULL(dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(RunningTime,0)),'-') as FormatedRunning,    
 ISNULL (dbo.rvlf_fn_GetTimeFromSeconds(IdlingTime),'-')as FormatedIdling,    
 ISNULL (dbo.rvlf_fn_GetTimeFromSeconds(MaxIdling),'-')as MaxIdling,    
 ISNULL (dbo.rvlf_fn_GetTimeFromSeconds((IdlingTime/(CASE WHEN NoofIdling=0 THEN NULL ELSE NoofIdling END) )),'-')as AvgIdling,    
 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 bigint) as idlingpercentage,    
 NoofIdling,CONVERT(varchar,@dtStartDate,106) as StartDate,CONVERT(varchar,@dtEndDate,106) as EndDate,    
 FleetName,dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(@totIdlingTime,0))AS TotIdlingTime,    
 dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(@totRunningTime,0)) AS TotRunningTime,@DistanceCaptionPrefix as DistanceCaption,    
 @SpeedCaptionPrefix as SpeedCaption ,  
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,  
 PasGenerateddate =dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())  
 FROM @tblVehicles  
  
SET NOCOUNT OFF  
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetIdlingSummaryDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetIdlingSummaryDetails]                  
 @bigOrganizationID bigint=null,                  
 @bigFleetID bigint = NULL,                  
 @intBoxID varchar(max)=null,                  
 @dtStartDate datetime=null,                  
 @dtEndDate datetime=null,                  
 @bigQueryingUser bigint=null                  
AS                  
/*******************************************************************************************************************/                  
-- Name  : [rvlf_sp_GetIdlingSummaryDetails] 40,61,null,'2013-11-20 08:00:00 AM','2013-11-21 08:00:00 PM',303      
-- Description : To get the Fleet idling summary details                  
-- Author  : Narayanasamy                  
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
--    : 07-Apr-2011 VN Created                  
--    : 09-Aug-2011 Ranjith Date format Included                 
--    : 31-Aug-2013 Sakthi Only get the idling details for the completed trips      
/*******************************************************************************************************************/                  
BEGIN                  
SET NOCOUNT ON              
              
 Declare @dtFDate datetime =@dtStartDate                
 Declare @dtEDate datetime =@dtEndDate               
                
 IF @bigFleetID IS NULL                    
  BEGIN                    
   SELECT @bigFleetID=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)                 
 DECLARE @DefaultDateFormat INT = 0          
  DECLARE @Lang varchar(50),  @LangSetting varchar(20)        
        
 IF @intBoxID = '0' BEGIN SET @intBoxID = NULL END      
               
 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,                
 @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)=0 then 107 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                    
                        
  --check the driver module rights                    
  DECLARE @bitIsDriverRights bit=NULL                    
  IF EXISTS(SELECT OP.PackageId FROM rvlfOrganizationPackage OP                     
  INNER JOIN rvlfPackageOperations PO ON OP.PackageId=PO.PackageId                      
  WHERE OrganizationID=@bigOrganizationID AND IsActive=1 AND OperationID=147)                    
  BEGIN                    
   SET @bitIsDriverRights=1                    
  END                     
  ELSE                    
  BEGIN                    
   SET @bitIsDriverRights=0                    
  END                     
                        
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                    
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                        
                      
 DECLARE @tblVehicles TABLE                    
 (                    
  VehicleId bigint,                    
  VehicleDescription varchar(50),                    
  LicensePlate varchar(50),                    
  Vin varchar(50),                    
  Boxid bigint,                    
  TotalNoofTrips int,                  
  TotalNoofIdling int,                    
  TotalRunningTime int,                    
  TotalIdlingTime int,              
  UNIQUE CLUSTERED(BoxId,VehicleId)                  
 )                    
                    
  DECLARE @TBLSTART TABLE                    
  (                    
   Processid bigint identity(1,1),                    
   Boxid int,                    
   StartTime datetime,                    
   Running int,                    
   tripId int,              
   UNIQUE CLUSTERED(TripId,Boxid,Processid)              
  )                    
                     
  DECLARE @TBLSTOP TABLE                    
  (                    
   Boxid int,                    
   StopTime datetime,                    
   tripId int              
   --UNIQUE CLUSTERED(TripId,Boxid,StopTime)                    
  )                     
                    
  DECLARE @tblMessageForProcessingTrip TABLE (                        
   [OriginDateTime] [datetime] NOT NULL,                    
   [BoxMsgInTypeId] [tinyint] NULL,                      
   [Address] nvarchar(300) null,                      
   [Ignition] tinyint null,                      
   [CustomProp] [varchar](600) NULL              
   --UNIQUE CLUSTERED(OriginDateTime,BoxMsgInTypeId,Ignition,CustomProp)                            
  )                    
  INSERT INTO @tblVehicles (VehicleId,Boxid,VehicleDescription,LicensePlate,Vin)                    
  SELECT VA.VehicleId,BI.BoxId,V.VehicleDescription,V.LicensePlate,V.Vin 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 V.OrganizationId =@bigOrganizationID AND F.OrganizationId =@bigOrganizationID)                    
  AND (@bigFleetID IS NULL OR F.FleetId=@bigFleetID)                    
  AND (@intBoxID IS NULL OR VA.BoxId in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                    
  ORDER BY BI.BOXID                    
                    
DECLARE @TBLIDLINGDETAILS TABLE                    
 (                    
  --Processid bigint identity(1,1),                    
  Boxid int,                    
  StartTime datetime,                    
  EndTime datetime,                    
  StartTrip datetime,                    
  EndTrip datetime,                      
  StreetAddress nvarchar(300),                    
  Running int,                    
  idling int,                    
  DriverId bigint,              
  UNIQUE CLUSTERED(Boxid,StartTrip,EndTrip,StartTime,EndTime)                    
 )                    
                    
DECLARE @intBoxLoop int =(SELECT MIN(Boxid) FROM @tblVehicles)                    
                    
WHILE @intBoxLoop IS NOT NULL                    
 BEGIN                    
                        
  DELETE FROM @tblMessageForProcessingTrip                         
  INSERT INTO @tblMessageForProcessingTrip(OriginDateTime,BoxMsgInTypeId,CustomProp,Ignition,Address)                    
  SELECT  h.OriginDateTime, h.BoxMsgInTypeId,h.CustomProp,    
  --CAST(SUBSTRING(h.SensorMask,6,1) as bit),    
  CASE WHEN CustomProp LIKE '%SENSOR_NUM=%' THEN SUBSTRING(CustomProp,CHARINDEX('SENSOR_NUM=',CustomProp,1)+11,(CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_NUM=',CustomProp,1))-( CHARINDEX('SENSOR_NUM=',CustomProp,1)+11))) ELSE NULL END,                  
  
  --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 (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 L.LandmarkName END                  
  from rvlfMsgInHst h INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                     
  LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID                                  
  where h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId IN (2,3,9)                    
  AND 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                     
                            
  -- GET THE IGNITION ON DETAILS                    
  DELETE FROM @TBLSTART                         
  INSERT INTO @TBLSTART (Boxid,StartTime)                    
  SELECT @intBoxLoop,OriginDateTime FROM @tblMessageForProcessingTrip                           
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId IN(2)                    
  AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                     
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                    
  AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                     
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                      
  AND Ignition=3  AND CustomProp LIKE '%SENSOR_NUM=3%'               
                       
  --GET THE IGNITION OFF DETAILS                       
  DELETE FROM @TBLSTOP                     
  INSERT INTO @TBLSTOP (Boxid,StopTime)                    
  SELECT @intBoxLoop,OriginDateTime                      
  FROM @tblMessageForProcessingTrip                      
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                     
  AND BoxMsgInTypeId IN(3)                    
  AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                     
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                    
  AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                     
  WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                      
  AND CustomProp LIKE '%SENSOR_NUM=3%'                   
                
  --PREPARE THE TRIPS AND DETAILS                    
  DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )                     
  DECLARE @DTSTART DATETIME=null,@DTEND DATETIME=null                      
  DECLARE @INC INT=1                           
  WHILE @LOOP IS NOT NULL                    
  BEGIN                    
      SELECT TOP 1 @DTSTART=StartTime  FROM @TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                        
      SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART                     
      UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART                     
      UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND                                 
      SET @INC =@INC +1                          
      SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART                          
  END                                
              
  --CALCULATE THE NOOFTRIPS                    
UPDATE @tblVehicles SET TotalNoofTrips =(SELECT COUNT(S.Boxid) FROM @TBLSTART S                     
  INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId),                    
  TotalRunningTime=(SELECT SUM(DATEDIFF(S,S.StartTime,ST.StopTime)) FROM @TBLSTART S                     
  INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId )                     
  WHERE Boxid=@intBoxLoop AND TotalNoofTrips IS NULL AND TotalRunningTime IS NULL                       
                      
  --GET THE IDLING DETAILS                     
  INSERT INTO @TBLIDLINGDETAILS (Boxid,EndTime,StartTime,StreetAddress)           
  SELECT idl.BoxId,idl.OriginDateTime,idl.StartTime,idl.Address FROM      
  (SELECT @intBoxLoop AS BoxID ,OriginDateTime, DATEADD(S,-CAST(SUBSTRING(CUSTOMPROP,CHARINDEX('Idling:',CUSTOMPROP,0)+7,                    
  (CHARINDEX(';',CUSTOMPROP,CHARINDEX('Idling:',CUSTOMPROP,0))- (CHARINDEX('Idling:',CUSTOMPROP,0)+7))) AS INT),OriginDateTime) AS StartTime,Address                       
  FROM @tblMessageForProcessingTrip WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                     
  AND BoxMsgInTypeId IN(9) AND CustomProp NOT LIKE '%Idling:0;%') idl WHERE idl.OriginDateTime BETWEEN (SELECT MIN(StartTime) FROM @TBLSTART)      
  AND (SELECT MAX(StopTime) FROM @TBLSTOP)             
  --SELECT @intBoxLoop,OriginDateTime, DATEADD(S,-CAST(SUBSTRING(CUSTOMPROP,CHARINDEX('Idling:',CUSTOMPROP,0)+7,                    
  --(CHARINDEX(';',CUSTOMPROP,CHARINDEX('Idling:',CUSTOMPROP,0))- (CHARINDEX('Idling:',CUSTOMPROP,0)+7))) AS INT),OriginDateTime),Address                       
  --FROM @tblMessageForProcessingTrip WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                     
  --AND BoxMsgInTypeId IN(9) AND CustomProp NOT LIKE '%Idling:0;%'                    
                          
  UPDATE @TBLIDLINGDETAILS SET StartTrip=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE OriginDateTime<=StartTime                     
  AND BoxMsgInTypeId =2 AND Ignition=3 AND OriginDateTime <= StartTime                    
  ORDER BY OriginDateTime DESC),EndTrip=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE OriginDateTime>=EndTime                      
  AND BoxMsgInTypeId =3 AND OriginDateTime >= EndTime                    
  ORDER BY OriginDateTime) WHERE StartTrip IS NULL AND EndTrip IS NULL                      
                      
  IF EXISTS(SELECT Boxid FROM @TBLIDLINGDETAILS WHERE StartTrip IS NULL)                    
  BEGIN                  
   --GET THE IGINITION DETAILS FROM MAIN TABLE                     
   UPDATE @TBLIDLINGDETAILS SET StartTrip=(SELECT TOP 1 OriginDateTime FROM rvlfMsgInHst WHERE OriginDateTime<=StartTime                     
   AND Boxid=@intBoxLoop  AND BoxMsgInTypeId =2 AND CAST(SUBSTRING(sensormask,6,1) as bit)=1 AND OriginDateTime <= EndTime                     
   ORDER BY OriginDateTime DESC) WHERE StartTrip IS NULL                     
  END                 
                    
  IF EXISTS(SELECT Boxid FROM @TBLIDLINGDETAILS WHERE EndTrip IS NULL)                    
   BEGIN                     
    --GET THE IGINITION DETAILS FROM MAIN TABLE                     
    UPDATE @TBLIDLINGDETAILS SET EndTrip=(SELECT TOP 1 OriginDateTime FROM rvlfMsgInHst WHERE OriginDateTime>=EndTime                      
    AND Boxid=@intBoxLoop AND BoxMsgInTypeId =3 AND OriginDateTime >= EndTime ORDER BY OriginDateTime)                      
    WHERE EndTrip IS NULL                     
   END                    
  UPDATE @TBLIDLINGDETAILS SET Running=DATEDIFF(S,StartTrip,EndTrip),idling=DATEDIFF(S,StartTime,EndTime)                     
  WHERE Running IS NULL AND idling IS NULL                    
                       
  UPDATE @tblVehicles SET TotalNoofIdling =(SELECT COUNT(Boxid) FROM @TBLIDLINGDETAILS WHERE Boxid=@intBoxLoop),                    
  TotalIdlingTime=(SELECT SUM(idling) FROM @TBLIDLINGDETAILS WHERE Boxid=@intBoxLoop GROUP BY Boxid)--,                    
  WHERE Boxid =@intBoxLoop AND TotalNoofIdling IS NULL AND TotalIdlingTime IS NULL --AND MaxIdlingTime IS NULL                                   
                      
  --update the driver id in the temp table                    
  IF(@bitIsDriverRights=1)                    
   BEGIN                    
    UPDATE @TBLIDLINGDETAILS SET DriverId= (SELECT TOP 1 CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,0)+6,(LEN(CustomProp)-(CHARINDEX('MAPID=',CustomProp,0)+6))+1) AS BIGINT)    
     ELSE NULL END FROM rvlfMsgInHst                     
     WHERE OriginDateTime <=EndTime                      
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM rvlfMsgInHst WHERE OriginDateTime<=StartTime AND BoxMsgInTypeId =76 AND CustomProp LIKE '%Driver Status=OUT;%' ORDER BY OriginDateTime DESC)                    
      AND BoxMsgInTypeId =76 AND CustomProp LIKE '%Driver Status=IN;%' ORDER BY OriginDateTime DESC)                    
     WHERE DriverId IS NULL                     
   END                    
  SELECT @intBoxLoop = MIN(Boxid) FROM @tblVehicles WHERE Boxid >@intBoxLoop                     
 END                    
                    
 --DELETE THE INVALID IDLINGS                    
 DELETE FROM @TBLIDLINGDETAILS WHERE Running IS NULL                    
                    
 SELECT V.Boxid,VehicleId,VehicleDescription,LicensePlate,vin,ISNULL(TotalNoofTrips,0) as TotalNoofTrips,                     
 ISNULL(dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(TotalRunningTime,0)),'-') as TotalRunningTime,                    
 ISNULL (dbo.rvlf_fn_GetTimeFromSeconds(CASE WHEN TotalRunningTime<TotalIdlingTime THEN TotalRunningTime ELSE TotalIdlingTime END),'-')as TotalIdlingTime,     
               case when @Lang='LanguageEn' then 'Idling' when @Lang='LanguageHindi' then N'8	A	8	M	$	@	' when @Lang='LanguageArNew' then N'*3C9' end as idlingTxt,       
 CAST(ISNULL(((CASE WHEN TotalRunningTime<TotalIdlingTime THEN TotalRunningTime ELSE TotalIdlingTime END)*1.00)/    
 CASE WHEN(ISNULL(TotalRunningTime,0)*1.00)=0 THEN 1 ELSE (ISNULL(TotalRunningTime,0)*1.00) END *100,0) AS NUMERIC(10,2)) as Totalidlingpercentage,                    
 --Sakthi Included for getting running percentage      
 case when @Lang='LanguageEn' then 'Running' when @Lang='LanguageHindi' then N'0	(	?			' when @Lang='LanguageArNew' then N'*4:JD' end as RunningTxt,    
 CAST(100-ISNULL(((CASE WHEN TotalRunningTime<TotalIdlingTime THEN TotalRunningTime ELSE TotalIdlingTime END)*1.00)/    
 CASE WHEN(ISNULL(TotalRunningTime,0)*1.00)=0 THEN 1 ELSE (ISNULL(TotalRunningTime,0)*1.00) END *100,0) AS NUMERIC(10,2)) AS TotalRunningpercentage,      
 TotalNoofIdling,@DistanceCaptionPrefix as DistanceCaption,@SpeedCaptionPrefix as SpeedCaption,                    
 IdlingStartTime =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,T.StartTime),                
 IdlingEndTime =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,T.EndTime),                
 ISNULL (dbo.rvlf_fn_GetTimeFromSeconds(T.idling),'-')as IdlingTime,                    
 ISNULL (dbo.rvlf_fn_GetTimeFromSeconds(T.Running),'-')as RunningTime,                    
 CAST(ISNULL((t.Idling*1.00)/CASE WHEN(ISNULL(t.Running,0)*1.00)=0 THEN 1 ELSE (ISNULL(t.Running,0)*1.00) END *100,0) AS NUMERIC(8,2)) as Idlingpercentage,                    
 t.StreetAddress,ISNULL(DM.DriverName,'-') AS DriverName,@bitIsDriverRights AS DriverRights,                
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                
 PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())                
 FROM @tblVehicles V INNER JOIN @TBLIDLINGDETAILS T ON T.Boxid =V.Boxid                    
 LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId=T.DriverId                
             
SET NOCOUNT OFF              
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetIdlingVsRunning]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvlf_sp_GetIdlingVsRunning]  
(  
 @bigOrganizationID bigint,  
    @bigFleetID bigint = null,  
 @dtStartDate datetime = null,   
 @dtEndDate datetime = null,   
 @bigQueryingUser bigint = null,  
 @bigTopNos bigint = 5 --,  
)  
as  
/******************************************************************************/  
-- Name  : rvlf_sp_GetIdlingVsRunning 1  
-- Description : To get the the Idling Vs Running data for dashboard  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 11-Oct-2009 MJJC Created Intial Version   
--    : Updated by Narayanasamy on 3-Nov-09 for convert date as GMT format  
/******************************************************************************/   
BEGIN  
  
 ------- Included to get the user prefernces---------------------  
   
 DECLARE @HoursToBeAdded INT = 0  
 DECLARE @MinsToBeAdded 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   
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz  
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser  
   
 ---------------------------------------------------------------------------  
   
 -------------------date conversion--included by Narayanasamy on 03-Nov-09---------------------------------  
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))  
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))  
 ----------------------------------------------------------------------------------------------------------  
  
 SELECT TOP (@bigTopNos)   
   
  CASE WHEN SUM(datediff(ss,t.startDate,t.EndDate)) = 0 THEN 0 ELSE  
  CAST((SUM(t.IdlingDuration)*1.00 / SUM(datediff(ss,t.startDate,t.EndDate))*100)   
  as /*numeric(18,2)*/ int)END as IdlingPercentage,   
    
  dbo.rvlf_fn_GetTimeFromSeconds(SUM(t.IdlingDuration)) as IdlingDuration,  
    
  100 - CASE WHEN SUM(datediff(ss,t.startDate,t.EndDate)) = 0 THEN 0 ELSE  
  CAST((SUM(t.IdlingDuration)*1.00 / SUM(datediff(ss,t.startDate,t.EndDate))*100)   
  as /*numeric(18,2)*/int )END as RunnningPercentage,  
    
  dbo.rvlf_fn_GetTimeFromSeconds(SUM(datediff(ss,t.startDate,t.EndDate)) - SUM(t.IdlingDuration)) as RunningTime,  
    
  v.VehicleDescription, t.BoxId,   
  SUBSTRING(v.VehicleDescription,1, 10)   
   + CASE WHEN LEN(v.VehicleDescription)>10 THEN '...' ELSE '' END as VehicleName  
    
  from rvlfTripDetails t  
  INNER JOIN rvlfVehicleAssignment va ON t.BoxId = va.BoxId  
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  INNER JOIN rvlfFleet f ON fv.FleetId= f.FleetId  
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
  LEFT OUTER JOIN rvlfMake m ON v.MakeId =m.MakeId  
  LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId  
  --INNER JOIN rvlfTimeZones tz ON v.TimeZone = tz.TimeZoneID  
 WHERE   
  ( @bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND   
  ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
    t.StartDate BETWEEN @dtStartDate AND @dtEndDate)  
 GROUP BY t.BoxId,v.VehicleDescription  
 ORDER BY IdlingPercentage DESC   
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetImageGalary]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    
CREATE PROCEDURE [dbo].[rvlf_sp_GetImageGalary]           
/*************************************************************************************          
Stored Procedure Name : rvlf_sp_GetImageGalary   184,'6/16/2013 10:00:00 AM','6/20/2013 10:00:00 AM',140       
Purpose               : Select,Insert,Modify and Delete Ibutton Settings      
Created by            : Ranjith         
Created date          : 13-Sep-11          
Updated by            :        
Updated date          :        
**************************************************************************************/          
    @vehicleId varchar(50),    
 @startdate as datetime,    
 @enddate datetime,            
    @bigQueryingUser bigint = 0    
AS        
begin      
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,@DefaultDateFormat=(case when  ISNULL(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end),    
     @bigOrganizationID = u.OrganizationId    
    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    
       
   -- print @HoursToBeAdded    
    --print @MinsToBeAdded    
        
 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))    
 ----------------------------------------------------------------------------------------------------------    
     
     
select dbo.rvlf_fn_GetCameraHex(h.BoxId,CAST(SUBSTRING(customprop, CHARINDEX('Image ID:',customprop,0)+9,(CHARINDEX(';',customprop,CHARINDEX('Image ID:',customprop,1))) -(CHARINDEX('Image ID:',customprop,1)+9)) as int),GETUTCDATE(),GETUTCDATE())   
as CameraData  
,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [Timestamp] ,  
--isnull(h.StreetAddress,'NA') as StreetAddress  
 case WHEN (H.LandMarkID IS NULL or H.LandMarkID = 0) THEN ISNULL(H.StreetAddress,'Address is not resolved') ELSE     
       ISNULL(L.LandmarkName, ISNULL(H.StreetAddress,'Address is not resolved'))    
       END as StreetAddress  
 from    
rvlfMsgInHst h    
inner join rvlfVehicleAssignment va on va.BoxId =h.BoxId    
inner join rvlfVehicle v on v.VehicleId =va.VehicleId    
LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID   
where v.VehicleId = @vehicleId and BoxMsgInTypeId =114     
--and OriginDateTime between CONVERT(date,@startdate)  and CONVERT(date,@enddate)    
and OriginDateTime between  
   CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109)  
 and CustomProp like '%imgHeader%'    
order by h.OriginDateTime desc     
--select '<ul class="rtg-images"> <li data-title='+ convert(varchar(50),GETUTCDATE()) +'<a target="_blank"></a>' +  ' href="' + photo +'">     
--<img src="' + Photo +'"> </li>'     
--    from rvlfDriverMaster where OrganizationID = 6 and Photo is not null and Photo <> ''    
end    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetIncentiveSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE Procedure [dbo].[rvlf_sp_GetIncentiveSettings]
	@bigIncentiveId bigint=null,
	@bigOrgId bigint=null,
	@bitOpeation bit=null

AS
/******************************************************************************/
--	Name		:	[rvlf_sp_GetIncentiveSettings]null,6,1
--	Description	:	To get the driver incentive setting details.
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	13-Sep-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN

	IF(@bitOpeation =1)
		BEGIN
			SELECT BattaId,Description,RatePerKM,OtherAmt,FromRange,
				CAST(CASE WHEN ToRange=10000 THEN 'No limit' ELSE CAST(ToRange AS VARCHAR) END AS VARCHAR) AS ToRange,
				VehicleType,CAST(CASE WHEN Active=1 THEN 'Active' ELSE 'InActive' END AS VARCHAR) AS Active,
				CAST(CASE WHEN NoOfDrivers=0 THEN 'NA' ELSE CAST(NoOfDrivers AS VARCHAR) END AS VARCHAR) AS NoOfDrivers,
				OrganizationId     
			FROM rvlfDriverBattaDetails 
			WHERE (@bigIncentiveId IS NULL OR @bigOrgId='' OR BattaId=@bigIncentiveId)
				AND(@bigOrgId IS NULL OR @bigOrgId='' OR OrganizationId=@bigOrgId)
				AND(FromRange IS NOT NULL AND ToRange IS NOT NULL)
				
			SELECT BattaId,Description,OtherAmt,VehicleType,FromTime,ToTime,CAST(CASE WHEN Active=1 THEN 'Active' ELSE 'InActive' END AS VARCHAR) AS Active,
				CAST(CASE WHEN NoOfDrivers=0 THEN 'NA' ELSE CAST(NoOfDrivers AS VARCHAR) END AS VARCHAR) AS NoOfDrivers,
				OrganizationId,IgnitionStatus     
			FROM rvlfDriverBattaDetails 
			WHERE (@bigIncentiveId IS NULL OR @bigIncentiveId='' OR BattaId=@bigIncentiveId)
				AND(@bigOrgId IS NULL OR @bigOrgId='' OR OrganizationId=@bigOrgId)
				AND(FromTime IS NOT NULL AND ToTime IS NOT NULL)
				
			SELECT BattaId,Description,OtherAmt,
				VehicleType,CAST(CASE WHEN Active=1 THEN 'Active' ELSE 'InActive' END AS VARCHAR) AS Active,
				OrganizationId,ViolationPoints as Violations,OtherAmt,
				CASE WHEN IsAllowance=1 THEN 'Less than '+ CAST(ViolationPoints as varchar) ELSE 'More than '+ CAST(ViolationPoints as varchar) END AS ViolationPoints,
				PercentageOfAmt,CASE WHEN IsAllowance=1 THEN 'Incentive' WHEN  IsAllowance=0 THEN 'Deduction' ELSE NULL END AS ViolationType     
			FROM rvlfDriverBattaDetails 
			WHERE (@bigIncentiveId IS NULL OR @bigIncentiveId='' OR BattaId=@bigIncentiveId)
				AND(@bigOrgId IS NULL OR @bigOrgId='' OR OrganizationId=@bigOrgId)
				AND(ViolationPoints IS NOT NULL AND PercentageOfAmt IS NOT NULL)
				AND(ViolationPoints !=0 AND PercentageOfAmt !=0) 				
		END
	ELSE
		BEGIN
			DELETE rvlfDriverBattaDetails WHERE BattaId=@bigIncentiveId AND OrganizationId=@bigOrgId 
		END
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetItemCatogory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvlf_sp_GetItemCatogory]      
(      
	@bigOrganizationId bigint = Null,        
	@bigUserId bigint = Null,  
	@ItemCategoryName varchar(150)=null,  
	@ItemCatDesc Varchar(200)=null,  
	@operation char='S'  
)      
as      
begin      
if(@operation='S')  
	begin
		select ItemCatID,ItemCategoryName from rvlfItemCategory where OrganizatioID=@bigOrganizationId order by ItemCategoryName  
	end
else if (@operation='I')  
	begin  
		insert into rvlfItemCategory values (@ItemCategoryName,0,@bigOrganizationId,@bigUserId,GETUTCDATE(),null,null,@ItemCatDesc)  
	end  
else if (@operation='D')  
	begin  
		declare @CategoryID bigint
		select @CategoryID=ItemCatID from rvlfItemCategory where ItemCategoryName=@ItemCategoryName  
		if(@CategoryID is null)
			begin
				Select 'Please check the Item Category name.' as ConfrimMessage
			end
		else
			begin
				if exists(select * from rvlfInvItemMaster where ItemCatID=@CategoryID AND IsActive=1)
					begin
						Select 'This Item Category has been already assigned to item master. Cannot be deleted.' as ConfrimMessage
					end
				else
					begin
						delete from rvlfItemCategory where ItemCategoryName=@ItemCategoryName  
						Select 'Item Category Deleted Successfully.' as ConfrimMessage
					end
			end
	end  
end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetItemName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc  [dbo].[rvlf_sp_GetItemName] 
(        
@Prefix varchar(20),      
@ItemCategory INT=NULL,      
@bigOrganizationId bigint = Null,        
@bigUserId bigint = Null         
)        
as        
/******************************************************************************/                                                  
-- Name  : rvlf_sp_GetItemName 'te'         
-- Description : Get Item Name code                                                 
-- Author  : Gopal.R          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--Created Date -01-Dec-2014           
/******************************************************************************/          
begin        
select ItemSNo,ItemName,Itemcode,Itemcode +'_'+ CAST(UnitPrice as varchar(18))+'_'+u.UOM +'_'+cast(ITM.AvailQty as varchar)  as Itemcodeprice  
from rvlfInvItemMaster ITM inner join rvlfUOM u on ITM.UOM=u.Uno
where ItemName like @Prefix + '%' and    
(@ItemCategory is null or @ItemCategory=0 OR ItemCatID=@ItemCategory ) AND         
(@bigOrganizationId is null or OrganizatioID=@bigOrganizationId) and IsActive=1      
end

GO
/****** Object:  StoredProcedure [dbo].[RVLF_SP_GETKPIDETAILS]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLF_SP_GETKPIDETAILS]
@BIGORGANIZATIONID BIGINT = NULL,
@BIGQUERYINGUSER BIGINT=NULL,
@nIsAdmin BIT = NULL,
@ReferenceId Bigint = NULL
AS
/***********************************************************************************************************************
-- PROCEDURE NAME	: RVLF_SP_GETKPIDETAILS 6,219,0
-- DESCRIPTION		: TO GETS THE DETAILS OF THE KPI
-- AUTHOR			: S SAKTHI GOPINATH
-- COMPANY			: TRINETRA WIRELESS (P) LTD
-- HISTORY			: <<DATE(DD-MON-YYYY)>> INITIAL REASON
--					: 09-NOV-2015 SS CREATED INTIAL VERSION
--					: 19-NOV-2015 SS Include Grid data query
***********************************************************************************************************************/
BEGIN
SET NOCOUNT ON
	SELECT KPIID,KPINAME,KPIDESC,(CASE WHEN ISUNIT = 1 THEN UNITNAME ELSE '' END) AS UNITNAME FROM RVLFKPIMASTER  order by KPINAME asc

	SELECT ReferenceId,KPIId,KPITitle AS KPIName,UserId,UserGroupId,FilterId FROM RVLFKPIREFERENCE_LOG WHERE 
	ReferenceId IN (SELECT ReferenceId FROM RVLFKPIUSERASSIGNMENT WHERE ASSIGNEDBY=@BIGQUERYINGUSER AND ISASSIGN=1 AND ISDELETE=0)
	
	DECLARE @nDesc VARCHAR(600) = ''

	SELECT ku.ASSIGNMENTID,km.KPIID,km.KPINAME,ku.CUSTOMTITLE,ku.CUSTOMDESC,f.FleetId,f.FleetName,ku.BOXID,
	(CASE WHEN ku.BOXID='0' THEN 'All' ELSE
	(STUFF( (SELECT ', ' + v.VehicleDescription FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId
	INNER JOIN (SELECT FieldValue FROM rvlf_fn_ConvertArrayToTable(ku.BOXID,',')) A ON va.BoxId=A.FieldValue
	ORDER BY va.BoxId FOR XML PATH('')), 1, 1, '')) END) AS VehicleCount,
	(SELECT CASE WHEN ku.TemperatureType IS NULL THEN '-' ELSE VT.VehicleTypeName END FROM rvlfVehicleType VT WHERE VT.VehicleTypeId = ku.TemperatureType) AS ESPTYPE,
	--(SELECT t.VehicleTypeName FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId
	--INNER JOIN (SELECT FieldValue FROM rvlf_fn_ConvertArrayToTable(ku.BOXID,',')) A ON va.BoxId=A.FieldValue) AS TYPEID,
	--(SELECT CASE WHEN COUNT(FieldValue)=0 OR MIN(FieldValue)=0 THEN 'All' ELSE CAST(COUNT(FieldValue) AS VARCHAR) END 
	--FROM dbo.rvlf_fn_ConvertArrayToTable(ku.BoxId,',')) AS VehicleCount,
	ku.DISPTYPEID AS DISPLAYID,(CASE WHEN ku.DISPTYPEID = 1 THEN 'TILE' WHEN ku.DISPTYPEID = 5 THEN 'GRID' WHEN ku.DISPTYPEID = 4 THEN 'CHART' END) AS DISPLAYNAME,
	ku.CostKPIsValue, ku.TemperatureType, sr.RefreshFrequencyValue AS REFRESHFREQUENCY, ku.DURATION,
	CASE WHEN ku.Duration < 72 THEN 'Last '+CAST(ku.Duration AS VARCHAR(3)) + ' hours' 
	WHEN ku.Duration < 168 THEN 'Last '+CAST((ku.Duration / 24) AS VARCHAR(3)) + ' days' 
	WHEN ku.Duration < 336 THEN 'Last Week' 
	ELSE 'Last 2 Weeks'  END AS DurationInText,
	CAST(ku.MINRANGE AS VARCHAR)+' - '+CAST(ku.MAXrange AS VARCHAR)+' ('+km.UNITNAME+')' AS Ranges,ku.MINRANGE,ku.MAXRANGE,ku.ISASSIGN,
	CASE WHEN ku.ISASSIGN IS NULL OR ku.ISASSIGN=0 THEN 'In-Active' ELSE 'Active' END AS ActiveStatusDisp,
	u.UserName,us.DisplayName AS AssignedUser,ISNULL(ku.IsReversed,0) AS IsReversed, ku.ASSIGNEDBY,ku.REFERENCEID,ku.CurrEnergytype
	FROM RVLFKPIUSERASSIGNMENT ku 
	INNER JOIN RVLFKPIMASTER km ON km.KPIID=ku.KPIID 
	INNER JOIN rvlfUser u ON u.UserId=ku.USERID
	INNER JOIN rvlfUser us ON us.UserId=ku.ASSIGNEDBY
	INNER JOIN rvlfFleet f ON f.FleetId=ku.FLEETID
	INNER JOIN rvlfScreenRefreshFrequency sr ON sr.FrequencyId=ku.REFRESHFREQUENCY
	WHERE u.OrganizationId=@BIGORGANIZATIONID AND ku.ISDELETE=0 AND 
	(@nIsAdmin=1 OR ku.IsAssign = 1) AND
	--(ku.ASSIGNEDBY IN (CASE WHEN @nIsAdmin=1 THEN @BIGQUERYINGUSER ELSE NULL END) OR 
	((@nIsAdmin=1 AND u.IsHidden=0) OR ku.USERID IN (CASE WHEN @nIsAdmin IS NULL OR @nIsAdmin=0 THEN @BIGQUERYINGUSER ELSE NULL END)) --Order  by K desc

	--SELECT ASSIGNMENTID,KPIID,CUSTOMTITLE AS KPIName,CUSTOMDESC,FLEETID,VEHICLEID,TITLECLRCODE,DISPTYPEID,REFRESHFREQUENCY,DURATION,MINRANGE,MAXRANGE
	--FROM RVLFKPIUSERASSIGNMENT WHERE ASSIGNEDBY=303 AND ISASSIGN=1

	SELECT ReferenceId,KPIId,KPITitle AS KPIName,UserId,UserGroupId,FilterId FROM RVLFKPIREFERENCE_LOG WHERE 
    ReferenceId IN (SELECT ReferenceId FROM RVLFKPIUSERASSIGNMENT WHERE (@ReferenceId IS NULL OR @ReferenceId='' OR REFERENCEID=@ReferenceId) AND ISASSIGN=1 AND ISDELETE=0)

	SELECT Sno,Category,CR FROM rvlf_CurrentandEnergyCategory WHERE Isdelete =0

SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[RVLF_SP_GETKPIFILTERS]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLF_SP_GETKPIFILTERS]
@BIGORGANIZATIONID BIGINT = NULL
AS
/***********************************************************************************************************************
-- PROCEDURE NAME	: RVLF_SP_GETKPIFILTERS
-- DESCRIPTION		: TO GETS THE DETAILS OF THE KPI FILTERS
-- AUTHOR			: S SAKTHI GOPINATH
-- COMPANY			: TRINETRA WIRELESS (P) LTD
-- HISTORY			: <<DATE(DD-MON-YYYY)>> INITIAL REASON
--					: 09-NOV-2015 SS CREATED INTIAL VERSION
***********************************************************************************************************************/
BEGIN
SET NOCOUNT ON
	SELECT FILTERID,FILTERNAME,FILTERDESC FROM RVLFKPIFILTERS WHERE ISDELETE=0
	--SELECT FILTERID,CASE WHEN FILTERID = 1 THEN REPLACE(FILTERNAME,'FLEET','SITE') WHEN FILTERID =2 THEN REPLACE(FILTERNAME,'VEHICLE','DEVICE') ELSE FILTERNAME END AS FILTERNAME ,FILTERDESC FROM RVLFKPIFILTERS WHERE ISDELETE=0
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[RVLF_SP_GETKPIUSERSETTINGS_FILTERS]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLF_SP_GETKPIUSERSETTINGS_FILTERS]
@nASSIGNMENTID INT = NULL,
@nUSERID INT = NULL,
@BIGORGANIZATIONID BIGINT = NULL
AS
/***********************************************************************************************************************
-- PROCEDURE NAME	: RVLF_SP_GETKPIUSERSETTINGS_FILTERS 0,1530,292
-- DESCRIPTION		: TO GETS THE Filter Enabling Details OF THE KPI
-- AUTHOR			: S SAKTHI GOPINATH
-- COMPANY			: TRINETRA WIRELESS (P) LTD
-- HISTORY			: <<DATE(DD-MON-YYYY)>> INITIAL REASON
--					: 16-NOV-2015 SS CREATED INTIAL VERSION
***********************************************************************************************************************/
BEGIN
SET NOCOUNT ON
	--SELECT USERId,FilterId FROM RVLFKPIFILTERUSERASSIGNMENT WHERE USERID=@nUSERID
	
	IF @nASSIGNMENTID IS NULL OR @nASSIGNMENTID = 0
	BEGIN
		SELECT @nUSERID AS UserId,FilterId FROM rvlfKPIFilters WHERE FilterId IN 
		(SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable((SELECT ISNULL(STUFF((SELECT ',' + 
		l.filterid FROM rvlfKPIUserAssignment ku 
		INNER JOIN rvlfKPIReference_Log l ON l.kpiId=ku.KpiId AND ku.UserId IN (SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(l.UserId,','))
		WHERE  (@nASSIGNMENTID IS NULL OR @nASSIGNMENTID = '' OR @nASSIGNMENTID = 0 OR ku.assignmentId=@nASSIGNMENTID) AND ku.UserId=@nUSERID
		FOR XML PATH('')), 1, 1, ''),'1,2,6,7')),','))
	END
	ELSE 
	BEGIN
		SELECT @nUSERID AS UserId,FilterId FROM rvlfKPIFilters WHERE FilterId IN 
		(SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(
		(SELECT TOP 1 l.filterid FROM rvlfKPIUserAssignment ku INNER JOIN rvlfKPIReference_Log l ON l.kpiId=ku.KpiId AND l.referenceid=ku.referenceId
		WHERE ku.assignmentId=@nASSIGNMENTID),
		','))
	END

SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLandingPages]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

      
CREATE Procedure [dbo].[rvlf_sp_GetLandingPages]      
 @bigModuleId bigint=null,      
 @bigUserId bigint=null,      
 @bitIsLogin bit=null      
AS      
/******************************************************************************/      
-- Name  : [rvlf_sp_GetLandingPages] NULL,14,1      
-- Description : To get the landing pages based on the user licenses.      
-- Author  : V.Narayanasamy      
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--    : 11-Jan-2011 VN Created Intial Version       
/******************************************************************************/      
BEGIN     
DECLARE @Lang varchar(50)                                      
select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigUserId        
 IF(@bitIsLogin =0)      
  BEGIN      
   SELECT M.ModuleID,case when @Lang ='LanguageArNew' then isnull(M.ModuleName_Ar,M.ModuleName) else M.ModuleName end as ModuleName,M.ModuleDesc,M.PagePath        
    FROM rvlfModule M      
     INNER JOIN rvlfUserGroupSecurity US ON US.ModuleId=M.ModuleID       
     INNER JOIN rvlfUserGroupAssignment UA ON UA.UserGroupId=US.UserGroupId       
     INNER JOIN rvlfUser U ON U.UserId=UA.UserId        
    WHERE (@bigUserId IS NULL OR @bigUserId='' OR U.UserId=@bigUserId)      
     AND(@bigModuleId IS NULL OR @bigModuleId='' OR M.ModuleID=@bigModuleId)         
     AND PagePath IS NOT NULL AND  ParentModuleId IS NULL      
    GROUP BY M.ModuleID,M.ModuleName,M.ModuleDesc,M.PagePath,M.ModuleName_Ar      
    ORDER BY M.ModuleID       
  END      
 ELSE      
  BEGIN      
 --Declare @cnt int    
 --SELECT @cnt=COUNT(*) FROM rvlfUserPreferences UP INNER JOIN (SELECT DISTINCT UGS.ModuleId  FROM rvlfUserGroupSecurity UGS      
 --INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId WHERE UGA.UserId=@bigUserId) M ON M.ModuleId=UP.LandingPageId    
 --WHERE UP.UserId=@bigUserId    
 IF  EXISTS(SELECT DISTINCT UP.LandingPageId  FROM rvlfUserPreferences UP    
 INNER JOIN rvlfUserGroupAssignment UA ON UA.UserId=UP.UserId     
 INNER JOIN rvlfUserGroupSecurity US ON US.UserGroupId =UA.UserGroupId     
 WHERE UA.UserId =@bigUserId  AND US.ModuleId=UP.LandingPageId)    
 BEGIN    
  SELECT REPLACE(M.PagePath,'..','~') as PagePath,M.ModuleName FROM rvlfUserPreferences UP      
  INNER JOIN rvlfModule M ON M.ModuleID = UP.LandingPageId WHERE UP.UserId =@bigUserId       
  AND M.ModuleID IN(SELECT DISTINCT UGS.ModuleId  FROM rvlfUserGroupSecurity UGS      
  INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId WHERE UGA.UserId=@bigUserId)    
 END    
 ELSE    
 BEGIN    
     
  SELECT TOP 1 CASE WHEN a.ParentModuleId IS NULL THEN REPLACE(a.PagePath,'..','~')     
  ELSE (SELECT REPLACE(b.PagePath,'..','~') FROM rvlfModule b WHERE b.ModuleID=a.ParentModuleId)END as PagePath,ModuleName         
  FROM rvlfModule a WHERE ModuleID IN (SELECT DISTINCT UGS.ModuleId FROM rvlfUserGroupSecurity UGS      
  INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId WHERE UGA.UserId=@bigUserId)    
     
  --SELECT TOP 1 REPLACE(PagePath,'..','~') as PagePath,ModuleName         
  --FROM rvlfModule WHERE ModuleID IN(SELECT DISTINCT UGS.ModuleId  FROM rvlfUserGroupSecurity UGS      
  --INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId WHERE UGA.UserId=@bigUserId)    
 END    
    
   --SELECT REPLACE(M.PagePath,'..','~') as PagePath,M.ModuleName         
   --FROM rvlfUserPreferences UP      
   --INNER JOIN rvlfModule M ON M.ModuleID =UP.LandingPageId      
   --WHERE UP.UserId =@bigUserId       
   --AND M.ModuleID IN(SELECT DISTINCT UGS.ModuleId  FROM rvlfUserGroupSecurity UGS      
   --INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserGroupId=UGS.UserGroupId       
   --WHERE UGA.UserId=@bigUserId)      
                
  END      
END  
  
  
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLandmarkCategories]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetLandmarkCategories]  
 @bigCategoryID bigint = null,  
 @bigOrganizationID bigint = null   
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetLandmarkCategories  
-- Description : To get the landmark categories.  
-- Author  : P. Devi.  
-- Company  : Angler Technologies  
-- History  : To create landmark categories  
--    : 8-Oct-2009    
--    : 08-Feb-2010 MJJC Included check for landmark category is asisgned or not.  
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
 SELECT   
  lc.LandmarkCategoryID, lc.CategoryName , lc.Description, lc.ImagePath,   
  CASE WHEN EXISTS (SELECT * FROM rvlfLandmark m WHERE m.LandmarkCategoryID = lc.LandmarkCategoryID)  
   THEN 1 ELSE 0 END as IsAssigned  
 FROM rvlfLandmarkCategory lc    
 WHERE  
  (@bigCategoryID IS NULL OR @bigCategoryID='' OR lc.LandmarkCategoryID  = @bigCategoryID) AND  
  (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR @bigOrganizationID = 0 OR lc.OrganizationId= @bigOrganizationID)  
 ORDER BY lc.CategoryName  
   
 SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLandmarksForSelectedVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[rvlf_sp_GetLandmarksForSelectedVehicles]    
@OrganizationId int = 107,    
@vehId bigint = null    
AS    
-- ========================================================================      
-- Procedure Name:  rvlf_sp_GetLandmarksForSelectedVehicles 6,34    
-- Create date: 29-Jun-2012    
-- Description: Get the landmark names for the corresponding vehicles    
-- ===========================================================================      
BEGIN    
SET NOCOUNT ON    
    
 Declare @landmark nvarchar(max),@lndForRoute nvarchar(max),@lndnameForRoute nvarchar(max)    
 SET @landmark=''    
 SET @lndForRoute=''    
 SET @lndnameForRoute = ''    
         
 --SELECT @landmark += CAST(Latitude AS VARCHAR)+'~#~'+CAST(Longitude AS VARCHAR)+'~#~'+CAST(Radius AS VARCHAR)+'~#~'+CAST(LandmarkName AS NVARCHAR)+        
 --'~#~'+CAST(StreetAddress AS NVARCHAR)+'~&~',    
 --@lndForRoute +=CAST(Latitude AS VARCHAR)+','+CAST(Longitude AS VARCHAR)+'$',    
 --@lndnameForRoute +=l.LandmarkName FROM rvlfLandmark l INNER JOIN rvlfOrganization o ON l.OrganizationId=o.OrganizationId        
 --INNER JOIN rvlfRouteDetails rd ON rd.LndID=l.LandmarkID INNER JOIN rvlfRouteVehicleAssignment rv ON rv.RouteId=rd.RouteID    
 --INNER JOIN rvlfVehicle v ON v.VehicleId=rv.VehicleId     
 --INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId    
 --WHERE o.OrganizationId=@OrganizationId AND v.VehicleId=@vehId    
 --ORDER BY rd.SeqID ASC    
 IF EXISTS (SELECT TOP 1 RouteId FROM rvlfRouteVehicleAssignment WHERE VehicleId=@vehId)    
 BEGIN    
 SELECT @landmark += CAST(Latitude AS VARCHAR)+'~#~'+CAST(Longitude AS VARCHAR)+'~#~'+CAST(Radius AS VARCHAR)+'~#~'+CAST(LandmarkName AS NVARCHAR)+        
 '~#~'+CAST(StreetAddress AS NVARCHAR)+'~&~',    
 @lndForRoute +=CAST(l.Latitude AS VARCHAR)+','+CAST(l.Longitude AS VARCHAR)+'$',    
 @lndnameForRoute +=l.LandmarkName+'$' FROM rvlfLandmark l INNER JOIN    
 (SELECT lndId,SeqID FROM rvlfRouteDetails WHERE RouteID IN    
 (SELECT RouteID FROM rvlfRouteVehicleAssignment WHERE VehicleId=@vehId)) RLnd ON RLnd.LndID=l.LandmarkID    
 WHERE l.OrganizationId=@OrganizationId ORDER BY RLnd.SeqID ASC    
 END    
 --ELSE    
 --BEGIN    
 --SELECT @landmark += CAST(Latitude AS VARCHAR)+'~#~'+CAST(Longitude AS VARCHAR)+'~#~'+CAST(Radius AS VARCHAR)+'~#~'+CAST(LandmarkName AS NVARCHAR)+        
 --'~#~'+CAST(StreetAddress AS NVARCHAR)+'~&~' FROM rvlfLandmark l INNER JOIN rvlfOrganization o ON l.OrganizationId=o.OrganizationId        
 --WHERE o.OrganizationId=@OrganizationId     
 --END    
     
 SELECT @landmark AS LandmarkEntries      
 IF LEN(@lndForRoute) > 0    
 BEGIN    
 SELECT SUBSTRING(@lndForRoute,0,LEN(@lndForRoute)-1) AS RouteDetails,    
 SUBSTRING(@lndnameForRoute,0,LEN(@lndnameForRoute)) AS LandmarkNames    
 END    
SET NOCOUNT OFF    
END

--SELECT TOP 1 RouteId FROM rvlfRouteVehicleAssignment WHERE VehicleId=34

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLandMarkTripSummary]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetLandMarkTripSummary]               
 @bigFleetID bigint =  NULL,           
 @intBoxID varchar(max) =  NULL,          
 @bigFromLandmarkId bigint=  NULL,           
 @bigToLandmarkId bigint=  NULL,          
 @dtStartDate datetime =  NULL,           
 @dtEndDate datetime =  NULL,           
 @bigOrganizationID bigint =  NULL,          
 @bigQueryingUser bigint =  NULL             
AS               
/***********************************************************************************************************************/              
-- Name  : [rvlf_sp_GetLandMarkTripSummary] 186,4193,1101,2397,'Jun  3 2014  3:30PM', 'Jun  4 2014 10:30PM',121,494    
-- Description : To get the trip summary based on the landmarks              
-- Author  : V.Narayanasamy              
-- Company  : Angler Technologies              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
--   : 04-Mar-2011 VN Created Intial Version               
--          : 09-Aug-2011 Ranjith Date format Included              
--          : 30-Nov-2011 Sakthi Distance calculation based on organization            
--          : 27-Apr-2013 Sakthi Condition checking for mobile application    
/***********************************************************************************************************************/              
              
BEGIN              
 SET NOCOUNT ON                
 Declare @dtFDate datetime =@dtStartDate                
 Declare @dtEDate datetime =@dtEndDate        
         
 IF @bigFleetID IS NULL              
  BEGIN              
   SELECT @bigFleetID=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)             
 DECLARE @DefaultDateFormat INT = 0     
   DECLARE @Lang varchar(50),  @LangSetting varchar(20)             
    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 '(Km)' END,              
     @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' 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              
               
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))              
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))          
        
               
 DECLARE @tblBoxes TABLE (BoxID int)                
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va               
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId              
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId              
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0'          
    or BoxId in (select * from DBO.rvlf_fn_ConvertArrayToTable(@intBoxID,',')))               
    AND V.OrganizationId=@bigOrganizationID              
   ORDER BY BoxId                
                 
 DECLARE @tblLandmarkDetails TABLE              
 (              
  Boxid int,              
  ProcessId bigint identity(1,1),               
  LandmarkId bigint,              
  LandTime datetime,              
  OdoMeter bigint,              
  StreetAdd nvarchar(300),              
  CustomProp varchar(600),              
  Boxmsgintypeid int,              
  TripId bigint,              
  Speed int              
 )              
               
 DECLARE @tblTripDetailsForTD TABLE(              
  [TripId] [INT] IDENTITY(1,1) NOT NULL,              [TripdupId] [bigint] NULL,              
  [BoxId] [int] NOT NULL,              
  [StartDate] [datetime] NOT NULL,              
  [EndDate] [datetime] NULL,              
  [OdometerStart] [bigint] NULL,              
  [OdometerEnd] [bigint] NULL,              
  [IsTripClosed] [bit] NULL,                
  [TripDuration] [int] NULL,                
  [StartAddress] nvarchar(300) NULL,              
  [EndAddress] nvarchar(300) NULL,              
  Speed int NULL              
 )              
               
 SELECT @intBoxID=MIN(BoxID) FROM @tblBoxes               
           
 WHILE @intBoxID IS NOT NULL              
  BEGIN              
   IF EXISTS(SELECT BoxId FROM rvlfMsgInHst WHERE BoxId =@intBoxID AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
    AND LandMarkID IN(@bigFromLandmarkId,@bigToLandmarkId))              
    BEGIN              
     --DELETE  FROM @tblLandmarkDetails               
     INSERT INTO @tblLandmarkDetails (LandmarkId,LandTime,OdoMeter,StreetAdd,Boxid,CustomProp,Boxmsgintypeid,Speed)               
      SELECT H.LandMarkID,OriginDateTime,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,              
        CASE WHEN H.LandMarkID IS NULL OR L.LandmarkName IS NULL THEN     
         (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)    
        ELSE L.LandmarkName END,              
        @intBoxID,CustomProp,BoxMsgInTypeId,Speed                 
       FROM rvlfMsgInHst h              
        LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID               
        WHERE BoxId =@intBoxID              
         AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate  and BoxMsgInTypeId not in (114)        
         --AND H.LandMarkID IS NOT NULL               
        ORDER BY OriginDateTime                
     DECLARE @IntProcessId int =(SELECT MIN(ProcessId) FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)              
     DECLARE @dtStartTime datetime =null,@intTripid int=1,@dtStopTime datetime=null,@vcEndAddress nvarchar(250)=null,@bigOdoEnd bigint=null,@BITTRIPSTATUS BIT=1,              
       @intIdlingDuration int=0,@bigOdoStart bigint=NULL,@vcStartAddress nvarchar(250)=null,@intTrip int=null,@dtdupStartTime datetime=null              
     WHILE @IntProcessId IS NOT NULL              
      BEGIN                       
       IF EXISTS(SELECT TOP 1 Boxid FROM @tblLandmarkDetails WHERE LandmarkId =@bigFromLandmarkId AND LandmarkId IS NOT NULL AND ProcessId >=@IntProcessId AND Boxid =@intBoxID)               
       BEGIN                
        IF (@bigFromLandmarkId !=@bigToLandmarkId )              
        BEGIN                                
         SET @dtStopTime =NULL                 
        END                 
        IF NOT EXISTS(SELECT TOP 1 ProcessId                  
         FROM @tblLandmarkDetails               
         WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)              
          AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL)              
          --AND LandTime<(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId IS NOT NULL  AND LandmarkId !=@bigFromLandmarkId               
          --  AND Boxid =@intBoxID AND ProcessId >@IntProcessId AND(@dtStopTime IS NULL OR LandTime >@dtStopTime)              
          --  AND LandTime>(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)) ORDER BY LandTime DESC)              
         BEGIN                        
          BREAK              
         END               
        ELSE              
         BEGIN              
          SELECT TOP 1 @IntProcessId=ProcessId  FROM @tblLandmarkDetails               
           WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)              
           AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL               
         END               
                                         
       --GET THE START TIME                                   
         IF(@bigFromLandmarkId =@bigToLandmarkId)              
         BEGIN                                
        SELECT TOP 1 @IntProcessId=ProcessId,@dtStartTime=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter                  
         FROM @tblLandmarkDetails               
         WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)              
          AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL               
          AND LandTime<(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId IS NOT NULL  AND LandmarkId !=@bigFromLandmarkId               
            AND Boxid =@intBoxID AND ProcessId >@IntProcessId AND(@dtStopTime IS NULL OR LandTime >@dtStopTime)              
            AND LandTime>(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)) ORDER BY LandTime DESC                            
         END              
        ELSE              
         BEGIN              
         SELECT TOP 1 @IntProcessId=ProcessId,@dtStartTime=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter                  
          FROM @tblLandmarkDetails               
          WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)              
           AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL               
           AND LandTime<(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId IS NOT NULL  AND LandmarkId =@bigToLandmarkId               
             AND Boxid =@intBoxID AND ProcessId >@IntProcessId AND(@dtStopTime IS NULL OR LandTime >@dtStopTime)              
             AND LandTime>(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)) ORDER BY LandTime DESC               
         END              
       IF (@dtStartTime=@dtdupStartTime)              
        BEGIN              
         BREAK              
        END                                           
        --GET THE STOP TIME              
       IF EXISTS(SELECT LandTime FROM @tblLandmarkDetails               
        WHERE LandTime >=(SELECT TOP 1 LandTime FROM @tblLandmarkDetails               
         WHERE LandmarkId NOT IN(@bigFromLandmarkId) AND (@dtStartTime IS NULL OR LandTime>@dtStartTime) AND Boxid =@intBoxID  )              
         AND (@dtStopTime IS NULL OR LandTime>@dtStopTime AND LandMarkID IS NOT NULL)              
         AND LandmarkId =@bigToLandmarkId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL)              
        BEGIN               
                                 
         SELECT TOP 1 @IntProcessId=ProcessId, @dtStopTime =LandTime,@vcEndAddress =StreetAdd ,@bigOdoEnd =OdoMeter                
          FROM @tblLandmarkDetails               
          WHERE LandTime >=(SELECT TOP 1 LandTime FROM @tblLandmarkDetails               
           WHERE LandmarkId NOT IN(@bigFromLandmarkId) AND (@dtStartTime IS NULL OR LandTime>@dtStartTime) AND Boxid =@intBoxID )              
           AND (@dtStopTime IS NULL OR LandTime>@dtStopTime)              
           AND LandmarkId =@bigToLandmarkId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL                
                    
        END              
       ELSE              
        BEGIN              
         SELECT @dtStopTime = CASE WHEN CONVERT(DATE,GETUTCDATE())=CONVERT(DATE,@dtEndDate) THEN GETUTCDATE()               
          ELSE @dtEndDate END,@BITTRIPSTATUS=0,@bigOdoEnd=NULL,@vcEndAddress =NULL              
         SELECT TOP 1 @bigOdoEnd = CAST( SUBSTRING (CustomProp,CHARINDEX('Odometer=',CustomProp,1)+9,CHARINDEX(';',CustomProp,              
          CHARINDEX('Odometer=',CustomProp,1)) - (CHARINDEX('Odometer=',CustomProp,1)+9)) as bigint) FROM rvlfMsgInHst               
         WHERE BoxId =@intBoxID AND CustomProp LIKE '%Odometer=%' AND OriginDateTime BETWEEN @dtStartDate AND @dtStopTime  ORDER BY OriginDateTime DESC                        
        END                
                        
       SET @intIdlingDuration=(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 @tblLandmarkDetails                
         WHERE LandTime  BETWEEN @dtStartTime AND @dtStopTime AND Boxid =@intBoxID  AND BoxMsgInTypeId =9               
         AND CustomProp NOT LIKE '%Idling:0;%')                                
                    
      DECLARE @maxSpeed int=0              
       SET @maxSpeed = (SELECT MAX(Speed) from @tblLandmarkDetails where BoxId=@intBoxID and LandTime between @dtStartTime and @dtStopTime)              
                     
       IF(@dtStartTime IS NOT NULL)              
       BEGIN                             
       INSERT INTO @tblTripDetailsForTD (BoxId,StartDate,EndDate,OdometerStart,OdometerEnd,              
      StartAddress,EndAddress,IsTripClosed,Speed,TripDuration,TripdupId)              
       VALUES(@intBoxID,@dtStartTime,@dtStopTime,@bigOdoStart,@bigOdoEnd,@vcStartAddress,              
        @vcEndAddress,@BITTRIPSTATUS,@maxSpeed,DATEDIFF(S,@dtStartTime,@dtStopTime),@intTripid)                     
       SET @intTrip=@@IDENTITY               
       SET @intTripid =@intTripid+1                     
       UPDATE @tblLandmarkDetails SET TripId =@intTrip WHERE LandTime =@dtStartTime AND Boxid =@intBoxID AND TripId IS NULL              
       UPDATE @tblLandmarkDetails SET TripId =@intTrip WHERE LandTime =@dtStopTime AND Boxid =@intBoxID AND TripId IS NULL               
       END               
       ELSE              
        SELECT @IntProcessId =NULL FROM @tblLandmarkDetails                
       END                
       SET @dtdupStartTime=@dtStartTime                      
       SELECT @IntProcessId = MIN(ProcessId) FROM @tblLandmarkDetails WHERE ProcessId >@IntProcessId AND (@dtStopTime IS NULL OR LandTime >@dtStopTime )              
      END                   
    END              
                       
   SELECT @intBoxID=MIN(BoxID) FROM @tblBoxes WHERE BoxID >@intBoxID               
  END              
                
                
DECLARE @TBLTRIPDETAILS TABLE              
  (              
 BoxID bigint null,      
 TripId bigint null,              
 StartTime datetime null,              
 StartPlace nvarchar(250),              
 EndTime datetime null,              
 EndPlace nvarchar(250),              
 OdoStart bigint null,              
 OdoEnd bigint null,              
 Idling int null,              
 Ignition int null,              
 MaxSpeed tinyint null,              
 StopTime int null              
  )              
              
  SET @IntProcessId=NULL              
  SELECT @IntProcessId=MIN(TRIPID) FROM @tblTripDetailsForTD              
  WHILE @IntProcessId IS NOT NULL              
 BEGIN              
  DECLARE @DTSTART DATETIME=NULL,@DTSTARTSTOPTIME DATETIME=NULL,              
   @DTEND DATETIME=NULL,@bigTripID BIGINT =NULL              
  SET @vcEndAddress=null; SET @bigOdoEnd =null;              
  SET @intIdlingDuration=0;SET @bigOdoStart=NULL; SET @vcStartAddress=null;SET @bigFromLandmarkId =NULL;              
  SET @bigToLandmarkId =NULL;SET @intBoxID =NULL              
                
  SELECT @DTSTART =StartDate,@DTEND =EndDate,@intBoxID=BoxId FROM @tblTripDetailsForTD WHERE TripId=@IntProcessId               
  DECLARE @INC INT=0              
  WHILE @DTSTART < @DTEND               
   BEGIN              
    DECLARE @DTTRIPEND DATETIME=NULL,@IntIgnition INT =NULL              
    --GET THE FROM PLACE DETAILS BETWEEN THE TRIPS              
    SELECT TOP 1 @bigFromLandmarkId = LandMarkID,@DTSTART=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter                
     FROM @tblLandmarkDetails               
      WHERE BoxId =@intBoxID              
       AND LandTime BETWEEN @DTSTART AND @DTEND           
       AND(@bigFromLandmarkId IS NULL OR LandMarkID!=@bigFromLandmarkId)               
    IF(@INC!=0)              
     BEGIN                
      DECLARE @dtNextLandTime datetime=null              
      SELECT TOP 1 @dtNextLandTime=LandTime FROM @tblLandmarkDetails WHERE Boxid=@intBoxID AND LandTime BETWEEN @DTSTART AND @DTEND AND  LandmarkId IS NOT NULL AND LandmarkId !=@bigFromLandmarkId ORDER BY LandTime ASC              
      SELECT TOP 1 @bigFromLandmarkId = LandMarkID,@DTSTART=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter                
       FROM @tblLandmarkDetails               
        WHERE BoxId =@intBoxID              
         AND LandTime BETWEEN @DTSTART AND CASE WHEN @dtNextLandTime IS NULL OR @dtNextLandTime='' THEN @DTEND ELSE @dtNextLandTime END              
         AND(@bigFromLandmarkId IS NULL OR @bigFromLandmarkId='' OR LandMarkID=@bigFromLandmarkId)ORDER BY LandTime DESC              
     END                       
    SET @INC=@INC+1              
                 
    --GET THE TO PLACE DETAILS BETWEEN THE TRIPS              
    SELECT TOP 1 @bigToLandmarkId = LandMarkID,@DTTRIPEND=LandTime,@vcEndAddress= StreetAdd,@bigOdoEnd =OdoMeter               
     FROM @tblLandmarkDetails                     
      WHERE BoxId =@intBoxID              
       AND LandTime BETWEEN @DTSTART AND @DTEND               
       AND(@bigFromLandmarkId IS NULL OR @bigFromLandmarkId='' OR LandMarkID!=@bigFromLandmarkId)               
    IF(@DTTRIPEND IS NULL OR @DTTRIPEND ='')              
     BEGIN              
      SELECT TOP 1 @vcEndAddress= 'Ongoing Trip',@bigOdoEnd =OdoMeter               
       FROM @tblLandmarkDetails                     
      WHERE BoxId =@intBoxID              
       AND LandTime BETWEEN @DTSTART AND @DTEND  ORDER BY LandTime DESC              
     END              
                             
  IF(@DTSTART IS NOT NULL AND @DTTRIPEND IS NOT NULL)              
  BEGIN                    
   --CALCULATE THE IDLING TIME                     
     SET @intIdlingDuration=(SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)as int)),0)              
     FROM @tblLandmarkDetails                
     WHERE BoxMsgInTypeId=9 AND BoxId=@intBoxID               
      AND LandTime> @DTSTART AND LandTime<= ISNULL(@DTTRIPEND,@DTEND)              
       GROUP BY BoxId)              
                 
    SET @maxSpeed =0              
    SET @maxSpeed = (SELECT MAX(Speed) FROM @tblLandmarkDetails WHERE BoxId=@intBoxID AND LandTime BETWEEN @DTSTART AND ISNULL(@DTTRIPEND,@DTEND))              
                   
    SELECT @IntIgnition=SUM(a.Duration) FROM               
    (SELECT CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,              
     (CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-              
      (CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT) as Duration              
     FROM @tblLandmarkDetails  WHERE BoxId=@intBoxID AND LandTime BETWEEN @DTSTART AND ISNULL(@DTTRIPEND,@DTEND) AND BoxMsgInTypeId=3               
     AND LandTime >(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE BoxId=@intBoxID AND LandTime               
      BETWEEN @DTSTART AND ISNULL(@DTTRIPEND,@DTEND) AND BoxMsgInTypeId=2 ORDER BY LandTime)) A               
    DECLARE @DTIGINITION DATETIME=NULL              
    IF(@IntIgnition IS NULL OR @IntIgnition=0)              
     BEGIN              
      SELECT TOP 1 @DTIGINITION=LandTime FROM @tblLandmarkDetails WHERE Boxid =@intBoxID AND LandTime BETWEEN @DTSTART AND @DTTRIPEND AND Boxmsgintypeid =2              
     END               
                   
    IF(@DTIGINITION IS NULL OR @DTIGINITION=0)              
     BEGIN              
      SELECT TOP 1 @DTIGINITION=LandTime FROM @tblLandmarkDetails WHERE Boxid =@intBoxID AND LandTime BETWEEN @DTSTART AND @DTTRIPEND               
     END                      
                           
    INSERT INTO @TBLTRIPDETAILS (BoxId,TripId,StartTime,EndTime,StartPlace,EndPlace,OdoStart,OdoEnd,MaxSpeed,Idling,Ignition)              
     VALUES(@intBoxID,@IntProcessId,@DTSTART,@DTTRIPEND,@vcStartAddress,@vcEndAddress,@bigOdoStart,@bigOdoEnd,@maxSpeed,              
     CASE WHEN @intIdlingDuration !=0 AND @intIdlingDuration >DATEDIFF(S,@DTSTART,@DTTRIPEND) THEN DATEDIFF(S,@DTSTART,@DTTRIPEND) ELSE @intIdlingDuration END,              
     CASE WHEN @IntIgnition IS NULL OR @IntIgnition>DATEDIFF(MINUTE,@DTSTART,@DTTRIPEND) THEN (DATEDIFF(S,ISNULL(@DTIGINITION,@DTSTART),@DTTRIPEND)) ELSE (@IntIgnition*60) END)                                    
                  
    UPDATE @TBLTRIPDETAILS SET StopTime =DATEDIFF(S,@DTSTARTSTOPTIME,@DTSTART) WHERE EndTime=@DTSTARTSTOPTIME                 
                  
    SET @DTSTARTSTOPTIME =@DTTRIPEND                 
    END                
    SET @DTSTART=@DTTRIPEND                        
   END                
  SELECT @IntProcessId= MIN(TripId) FROM @tblTripDetailsForTD WHERE TripId>@IntProcessId                 
 END              
 UPDATE @TBLTRIPDETAILS SET Idling =Ignition WHERE Idling>Ignition                
              
DECLARE @tblIdlingSummary TABLE         
(               
 TripId bigint null,              
 Idling int null,              
 Speed int null              
)              
INSERT INTO @tblIdlingSummary(TripId,Idling,Speed)              
 SELECT TripId,SUM(Idling),MAX(MaxSpeed) FROM @TBLTRIPDETAILS GROUP BY TripId               
               
                
 DECLARE @TBLSUMMARY TABLE              
  (              
 Boxid int null,              
 TripDuration int null,              
 IdlingDuration int null,              
 TotRunningTime BIGINT null,    
 TripId int null              
  )              
    
IF @bigOrganizationID IN (191)    
BEGIN    
INSERT INTO @TBLSUMMARY (Boxid,TripDuration,IdlingDuration,TotRunningTime,TripId)    
 SELECT TD.BoxId,SUM(ISNULL(TripDuration,0)),SUM(ISNULL(ID.Idling,0)),    
 SUM(ISNULL(TDD.Ignition,DateDiff(SS,ISNULL(TDD.StartTime,TD.StartDate),ISNULL(TDD.EndTime,TD.EndDate)))),TD.TripId      
 FROM  @tblTripDetailsForTD TD    
  INNER JOIN @tblIdlingSummary ID ON ID.TripId=TD.TripId     
  INNER JOIN @TBLTRIPDETAILS TDD ON TDD.TripId=TD.TripId     
 GROUP BY TD.BoxId,TD.TripId     
END    
ELSE    
BEGIN                
 INSERT INTO @TBLSUMMARY (Boxid,TripDuration,IdlingDuration,TotRunningTime,TripId)              
 SELECT TD.BoxId,SUM(ISNULL(TD.TripDuration,0)),SUM(ISNULL(ID.Idling,0)),              
 SUM(ISNULL(TDD.Ignition,DateDiff(SS,ISNULL(TDD.StartTime,TD.StartDate),ISNULL(TDD.EndTime,TD.EndDate)))),NULL                
 FROM  @tblTripDetailsForTD TD              
 INNER JOIN @tblIdlingSummary ID ON ID.TripId=TD.TripId    
 CROSS APPLY (SELECT TOP 1 * FROM @TBLTRIPDETAILS WHERE BoxID=TD.BoxId AND TripId = TD.TripId) TDD               
 --INNER JOIN @TBLTRIPDETAILS TDD ON TDD.TripId=TD.TripId               
 GROUP BY TD.BoxId               
END    
       
SELECT T.TripId,T.TripdupId,V.VehicleId,V.VehicleDescription,V.LicensePlate,V.Vin,      
StartDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,StartDate),            
EndDate = dbo.rvlf_fn_DayLightSavings(@dtEDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,EndDate)                  
 --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)) as StartDate,              
 --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as EndDate              
 --StartDate,EndDate              
 ,ID.Speed,              
 CASE WHEN IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,              
 dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,StartDate,EndDate)) as Duration,               
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))))) as Distance,          
 
    
      
 StartAddress,CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END AS EndAddress  ,              
 CASE WHEN ID.Idling IS NULL OR ID.Idling='' OR ID.Idling=0 THEN '-' ELSE               
 dbo.rvlf_fn_GetTimeFromSeconds(ID.Idling) END AS IdlingTime,            
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(OdometerStart * @ConversionFactor))) AS OdometerStart,            
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(t.OdometerEnd * @ConversionFactor))),'-') as OdometerEnd ,              
 @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,              
 dbo.rvlf_fn_getTimeFromSeconds(S.TripDuration) AS TotDuration,              
 CASE WHEN S.IdlingDuration IS NULL OR S.IdlingDuration='' OR S.IdlingDuration=0 THEN '-' ELSE               
 dbo.rvlf_fn_getTimeFromSeconds(S.IdlingDuration) END AS TotIdling,              
 StartTime = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,ISNULL(td.StartTime,T.StartDate)),            
 EndTime = dbo.rvlf_fn_DayLightSavings(@dtEDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,ISNULL(td.EndTime,T.EndDate)),            
--DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,ISNULL(td.StartTime,T.StartDate))) as StartTime,              
--DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,ISNULL(td.EndTime,T.EndDate))) as EndTime,              
 ISNULL(TD.StartPlace,CASE WHEN TD.TripId IS NULL THEN T.StartAddress ELSE '-' END) AS StartPlace,              
 ISNULL(TD.EndPlace,CASE WHEN TD.TripId IS NULL THEN CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END ELSE '-' END) AS EndPlace,              
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(TD.OdoStart* @ConversionFactor))),CASE WHEN TD.TripId IS NULL THEN
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(T.OdometerStart * @ConversionFactor))) ELSE '-' END) AS OdoStart ,              
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(TD.OdoEnd* @ConversionFactor))),CASE WHEN TD.TripId IS NULL THEN 
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(T.OdometerEnd * @ConversionFactor))),'-') ELSE '-' END) AS OdoEnd,              
 ISNULL(TD.MaxSpeed,CASE WHEN TD.TripId IS NULL THEN T.Speed ELSE 0 END) AS MaxSpeed,              
 CASE WHEN TD.Idling IS NULL OR TD.Idling='' OR TD.Idling=0 THEN '-' ELSE               
  dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(TD.Idling, CASE WHEN TD.TripId IS NULL THEN ISNULL(ID.Idling,0) ELSE 0 END)) END AS Idling,               
 dbo.rvlf_fn_getTimeFromSeconds(ISNULL(TD.Ignition,DateDiff(SS,ISNULL(TD.StartTime,T.StartDate),ISNULL(TD.EndTime,T.EndDate)))) as DetailDuration,              
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(CAST((ABS(ISNULL((ISNULL(TD.OdoEnd,CASE WHEN TD.TripId IS NULL THEN T.OdometerEnd ELSE 0 END)-ISNULL(TD.OdoStart
   
  ,CASE WHEN TD.TripId IS NULL THEN T.OdometerStart ELSE 0 END)), 0)) * @ConversionFactor) as varchar(20))))) as DetailDistance,              
 dbo.rvlf_fn_getTimeFromSeconds(S.TotRunningTime) AS TotRunningTime,ISNULL(dbo.rvlf_fn_getTimeFromSeconds(TD.StopTime),'-') AS StopTime,            
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,            
 PasGeneratedDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())            
 --Convert(varchar,getdate(),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(getdate() as time),22) as PasGeneratedDate                 
FROM @tblTripDetailsForTD T              
 INNER JOIN @tblIdlingSummary ID ON ID.TripId =T.TripId               
 INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=T.BoxId               
 INNER JOIN @TBLSUMMARY S ON S.Boxid=T.BoxId               
 INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId               
 LEFT OUTER JOIN @TBLTRIPDETAILS TD ON TD.TripId=T.TripId               
ORDER BY T.TripId                
              
--SELECT * FROM @tblLandmarkDetails where LandmarkId is not null              
--SELECT * FROM @tblTripDetailsForTD               
--SELECT * FROM @TBLTRIPDETAILS               
--SELECT * FROM @TBLSUMMARY               
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLandMarkTripSummary_New]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetLandMarkTripSummary_New]         
 @bigFleetID bigint =  NULL,     
 @intBoxID varchar(max) =  NULL,    
 @bigFromLandmarkId bigint=  NULL,     
 @bigToLandmarkId bigint=  NULL,    
 @dtStartDate datetime =  NULL,     
 @dtEndDate datetime =  NULL,     
 @bigOrganizationID bigint =  NULL,    
 @bigQueryingUser bigint =  NULL       
AS         
/***********************************************************************************************************************/        
-- Name  : [rvlf_sp_GetLandMarkTripSummary_New] 186,'4240',1101,1101,'2014-08-19 08:00:00 AM', '2014-08-22 08:00:00 PM',121, 19        
-- Description : To get the trip summary based on the landmarks        
-- Author  : V.Narayanasamy        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--   : 04-Mar-2011 VN Created Intial Version         
--          : 09-Aug-2011 Ranjith Date format Included        
--          : 30-Nov-2011 Sakthi Distance calculation based on organization      
/***********************************************************************************************************************/        
        
BEGIN        
 SET NOCOUNT ON          
 Declare @dtFDate datetime =@dtStartDate          
 Declare @dtEDate datetime =@dtEndDate  
   
 IF @bigFleetID IS NULL        
  BEGIN        
   SELECT @bigFleetID=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)       
 DECLARE @DefaultDateFormat INT = 0       
    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 '(Km)' END,        
     @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' 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 = @bigQueryingUser        
         
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))        
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))    
  
         
 DECLARE @tblBoxes TABLE (BoxID int)          
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va         
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId        
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId        
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0'    
    or BoxId in (select * from DBO.rvlf_fn_ConvertArrayToTable(@intBoxID,',')))         
    AND V.OrganizationId=@bigOrganizationID        
   ORDER BY BoxId          
           
 DECLARE @tblLandmarkDetails TABLE        
 (        
  Boxid int,        
  ProcessId bigint identity(1,1),         
  LandmarkId bigint,        
  LandTime datetime,        
  OdoMeter bigint,        
  StreetAdd varchar(300),        
  CustomProp varchar(600),        
  Boxmsgintypeid int,        
  TripId bigint,        
  Speed int        
 )        
         
 DECLARE @tblTripDetailsForTD TABLE(        
  [TripId] [INT] IDENTITY(1,1) NOT NULL,        
  [TripdupId] [bigint] NULL,        
  [BoxId] [int] NOT NULL,        
  [StartDate] [datetime] NOT NULL,        
  [EndDate] [datetime] NULL,        
  [OdometerStart] [bigint] NULL,        
  [OdometerEnd] [bigint] NULL,        
  [IsTripClosed] [bit] NULL,          
  [TripDuration] [int] NULL,          
  [StartAddress] nvarchar(300) NULL,        
  [EndAddress] nvarchar(300) NULL,        
  Speed int NULL        
 )        
         
 SELECT @intBoxID=MIN(BoxID) FROM @tblBoxes         
         
 WHILE @intBoxID IS NOT NULL        
  BEGIN        
   IF EXISTS(SELECT BoxId FROM rvlfMsgInHst WHERE BoxId =@intBoxID AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate         
    AND LandMarkID IN(@bigFromLandmarkId,@bigToLandmarkId))        
    BEGIN        
     --DELETE  FROM @tblLandmarkDetails         
     INSERT INTO @tblLandmarkDetails (LandmarkId,LandTime,OdoMeter,StreetAdd,Boxid,CustomProp,Boxmsgintypeid,Speed)         
      SELECT H.LandMarkID,OriginDateTime,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,        
        CASE WHEN H.LandMarkID IS NULL OR L.LandmarkName IS NULL THEN H.StreetAddress ELSE L.LandmarkName END,        
        @intBoxID,CustomProp,BoxMsgInTypeId,Speed           
       FROM rvlfMsgInHst h        
        LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID         
        WHERE BoxId =@intBoxID        
         AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate    
           and Odometer > 0          
         --AND H.LandMarkID IS NOT NULL         
        ORDER BY OriginDateTime          
     DECLARE @IntProcessId int =(SELECT MIN(ProcessId) FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)        
     DECLARE @dtStartTime datetime =null,@dtStopTime datetime=null,@intTripid int=1,@vcEndAddress nvarchar(250)=null,@bigOdoEnd bigint=null,@BITTRIPSTATUS BIT=1,        
       @intIdlingDuration int=0,@bigOdoStart bigint=NULL,@vcStartAddress nvarchar(250)=null,@intTrip int=null,@dtdupStartTime datetime=null        
     WHILE @IntProcessId IS NOT NULL        
      BEGIN                 
       IF EXISTS(SELECT TOP 1 Boxid FROM @tblLandmarkDetails WHERE LandmarkId =@bigFromLandmarkId AND LandmarkId IS NOT NULL AND ProcessId >@IntProcessId AND Boxid =@intBoxID)         
       BEGIN          
        IF (@bigFromLandmarkId !=@bigToLandmarkId )        
        BEGIN                          
         SET @dtStopTime =NULL           
        END           
        IF NOT EXISTS(SELECT TOP 1 ProcessId            
         FROM @tblLandmarkDetails         
         WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)        
          AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL)        
          --AND LandTime<(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId IS NOT NULL  AND LandmarkId !=@bigFromLandmarkId         
          --  AND Boxid =@intBoxID AND ProcessId >@IntProcessId AND(@dtStopTime IS NULL OR LandTime >@dtStopTime)        
          --  AND LandTime>(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)) ORDER BY LandTime DESC)        
         BEGIN                  
          BREAK        
         END         
        ELSE        
         BEGIN        
          SELECT TOP 1 @IntProcessId=ProcessId  FROM @tblLandmarkDetails         
           WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)        
           AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL         
         END         
                                   
       --GET THE START TIME                             
         IF(@bigFromLandmarkId =@bigToLandmarkId)        
         BEGIN                          
        SELECT TOP 1 @IntProcessId=ProcessId,@dtStartTime=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter            
         FROM @tblLandmarkDetails         
         WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)        
          AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL         
          AND LandTime<(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE (LandmarkId IS NULL  or LandmarkId !=@bigFromLandmarkId )         
            AND Boxid =@intBoxID AND ProcessId >@IntProcessId AND(@dtStopTime IS NULL OR LandTime >@dtStopTime)        
            AND LandTime>(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)) ORDER BY LandTime DESC                      
         END        
        ELSE        
         BEGIN        
         SELECT TOP 1 @IntProcessId=ProcessId,@dtStartTime=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter            
          FROM @tblLandmarkDetails         
          WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)        
           AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL         
           AND LandTime<(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId IS NOT NULL  AND LandmarkId =@bigToLandmarkId         
             AND Boxid =@intBoxID AND ProcessId >@IntProcessId AND(@dtStopTime IS NULL OR LandTime >@dtStopTime)        
             AND LandTime>(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)) ORDER BY LandTime DESC         
         END        
       IF (@dtStartTime=@dtdupStartTime)        
        BEGIN        
         BREAK        
        END                                     
        --GET THE STOP TIME        
       IF EXISTS(SELECT LandTime FROM @tblLandmarkDetails         
        WHERE LandTime >=(SELECT TOP 1 LandTime FROM @tblLandmarkDetails         
         WHERE LandmarkId NOT IN(@bigFromLandmarkId) AND (@dtStartTime IS NULL OR LandTime>@dtStartTime) AND Boxid =@intBoxID  )        
         AND (@dtStopTime IS NULL OR LandTime>@dtStopTime AND LandMarkID IS NOT NULL)        
         AND LandmarkId =@bigToLandmarkId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL)        
        BEGIN         
                           
         SELECT TOP 1 @IntProcessId=ProcessId, @dtStopTime =LandTime,@vcEndAddress =StreetAdd ,@bigOdoEnd =OdoMeter          
          FROM @tblLandmarkDetails         
          WHERE LandTime >=(SELECT TOP 1 LandTime FROM @tblLandmarkDetails         
           WHERE LandmarkId NOT IN(@bigFromLandmarkId) AND (@dtStartTime IS NULL OR LandTime>@dtStartTime) AND Boxid =@intBoxID )        
           AND (@dtStopTime IS NULL OR LandTime>@dtStopTime)        
           AND LandmarkId =@bigToLandmarkId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL                   
      END 
      ELSE IF EXISTS(SELECT LandTime FROM @tblLandmarkDetails WHERE LandTime >=(SELECT TOP 1 LandTime FROM @tblLandmarkDetails           
         WHERE LandmarkId IN(@bigToLandmarkId) AND (@dtStartTime IS NULL OR LandTime>@dtStartTime) AND Boxid =@intBoxID  )          
         AND (@dtStopTime IS NULL OR LandTime>@dtStopTime AND LandMarkID IS NOT NULL)
         AND LandmarkId =@bigToLandmarkId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL)          
        BEGIN           
                           
         SELECT TOP 1 @IntProcessId=ProcessId, @dtStopTime =LandTime,@vcEndAddress =StreetAdd ,@bigOdoEnd =OdoMeter            
          FROM @tblLandmarkDetails           
          WHERE LandTime >=(SELECT TOP 1 LandTime FROM @tblLandmarkDetails           
           WHERE LandmarkId IN(@bigToLandmarkId) AND (@dtStartTime IS NULL OR LandTime>@dtStartTime) AND Boxid =@intBoxID )          
           AND (@dtStopTime IS NULL OR LandTime>@dtStopTime)
           AND LandmarkId =@bigToLandmarkId AND Boxid = @intBoxID AND LandMarkID IS NOT NULL            
             --  select 'stif1', @IntProcessId, @dtStopTime       
      END       
      ELSE        
        BEGIN        
         SELECT @dtStopTime = CASE WHEN CONVERT(DATE,GETUTCDATE())=CONVERT(DATE,@dtEndDate) THEN GETUTCDATE()         
          ELSE @dtEndDate END,@BITTRIPSTATUS=0,@bigOdoEnd=NULL,@vcEndAddress =NULL        
         SELECT TOP 1 @bigOdoEnd = CAST( SUBSTRING (CustomProp,CHARINDEX('Odometer=',CustomProp,1)+9,CHARINDEX(';',CustomProp,        
          CHARINDEX('Odometer=',CustomProp,1)) - (CHARINDEX('Odometer=',CustomProp,1)+9)) as bigint) FROM rvlfMsgInHst         
         WHERE BoxId =@intBoxID AND CustomProp LIKE '%Odometer=%' AND OriginDateTime BETWEEN @dtStartDate AND @dtStopTime  ORDER BY OriginDateTime DESC                  
        END          
                  
       SET @intIdlingDuration=(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 @tblLandmarkDetails          
         WHERE LandTime  BETWEEN @dtStartTime AND @dtStopTime AND Boxid =@intBoxID  AND BoxMsgInTypeId =9         
         AND CustomProp NOT LIKE '%Idling:0;%')                          
              
       DECLARE @maxSpeed int=0        
       SET @maxSpeed = (SELECT MAX(Speed) from @tblLandmarkDetails where BoxId=@intBoxID and LandTime between @dtStartTime and @dtStopTime)        
               
       IF(@dtStartTime IS NOT NULL)        
       BEGIN                       
       INSERT INTO @tblTripDetailsForTD (BoxId,StartDate,EndDate,OdometerStart,OdometerEnd,        
        StartAddress,EndAddress,IsTripClosed,Speed,TripDuration,TripdupId)        
       VALUES(@intBoxID,@dtStartTime,@dtStopTime,@bigOdoStart,@bigOdoEnd,@vcStartAddress,        
        @vcEndAddress,@BITTRIPSTATUS,@maxSpeed,DATEDIFF(S,@dtStartTime,@dtStopTime),@intTripid)               
       SET @intTrip=@@IDENTITY         
       SET @intTripid =@intTripid+1               
       UPDATE @tblLandmarkDetails SET TripId =@intTrip WHERE LandTime =@dtStartTime AND Boxid =@intBoxID AND TripId IS NULL        
       UPDATE @tblLandmarkDetails SET TripId =@intTrip WHERE LandTime =@dtStopTime AND Boxid =@intBoxID AND TripId IS NULL         
       END         
       ELSE        
        SELECT @IntProcessId =NULL FROM @tblLandmarkDetails          
       END          
       SET @dtdupStartTime=@dtStartTime                
       SELECT @IntProcessId = MIN(ProcessId) FROM @tblLandmarkDetails WHERE ProcessId >@IntProcessId AND (@dtStopTime IS NULL OR LandTime >@dtStopTime )        
      END             
    END        
                 
   SELECT @intBoxID=MIN(BoxID) FROM @tblBoxes WHERE BoxID >@intBoxID         
  END        
          
          
DECLARE @TBLTRIPDETAILS TABLE        
  (        
 TripId bigint null,        
 StartTime datetime null,        
 StartPlace nvarchar(250),        
 EndTime datetime null,        
 EndPlace nvarchar(250),        
 OdoStart bigint null,        
 OdoEnd bigint null,        
 Idling int null,        
 Ignition int null,        
 MaxSpeed tinyint null,        
 StopTime int null        
  )        
           
                  
  SET @IntProcessId=NULL                    
  SELECT @IntProcessId=MIN(TRIPID) FROM @tblTripDetailsForTD                    
  WHILE @IntProcessId IS NOT NULL                    
 BEGIN                    
  DECLARE @DTSTART DATETIME=NULL,@DTSTARTSTOPTIME DATETIME=NULL,                    
   @DTEND DATETIME=NULL,@bigTripID BIGINT =NULL                    
  SET @vcEndAddress=null; SET @bigOdoEnd =null;                    
  SET @intIdlingDuration=0;SET @bigOdoStart=NULL; SET @vcStartAddress=null;SET @bigFromLandmarkId =NULL;                    
  SET @bigToLandmarkId =NULL;SET @intBoxID =NULL                    
                      
  SELECT @DTSTART =StartDate,@DTEND =EndDate,@intBoxID=BoxId FROM @tblTripDetailsForTD WHERE TripId=@IntProcessId                     
  DECLARE @INC INT=0  ,@procid int=0               
  --select 'whbr',@IntProcessId,@DTSTART,@vcStartAddress,@vcEndAddress,@bigOdoStart,@bigOdoEnd,@maxSpeed                   
  WHILE @DTSTART < @DTEND                     
   BEGIN                    
    DECLARE @DTTRIPEND DATETIME=NULL,@IntIgnition INT =NULL          
                           
    --GET THE FROM PLACE DETAILS BETWEEN THE TRIPS                    
    SELECT TOP 1 @bigFromLandmarkId = LandMarkID,@DTSTART=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter,@procid=ProcessId                      
     FROM @tblLandmarkDetails                     
      WHERE BoxId =@intBoxID                    
       AND LandTime BETWEEN @DTSTART AND @DTEND          
       --AND(@bigFromLandmarkId IS NULL OR LandMarkID!=@bigFromLandmarkId)              
        AND((LandMarkID is not null AND ProcessId>@procid))    --@bigFromLandmarkId IS NULL OR     
                  
 --select 'wh',@IntProcessId,@DTSTART,@DTTRIPEND,@vcStartAddress,@vcEndAddress,@bigOdoStart,@bigOdoEnd,@maxSpeed                    
    IF(@INC!=0)                    
     BEGIN                      
      DECLARE @dtNextLandTime datetime=null                    
      SELECT TOP 1 @dtNextLandTime=LandTime FROM @tblLandmarkDetails WHERE Boxid=@intBoxID AND LandTime BETWEEN @DTSTART AND @DTEND         
      AND  LandmarkId IS NOT NULL AND --LandmarkId !=@bigFromLandmarkId         
      ProcessId !=@procid ORDER BY LandTime ASC                    
--      SELECT TOP 1 @bigFromLandmarkId = LandMarkID,@DTSTART=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter                      
--FROM @tblLandmarkDetails                     
--        WHERE BoxId =@intBoxID                    
--         AND LandTime BETWEEN @DTSTART AND CASE WHEN @dtNextLandTime IS NULL OR @dtNextLandTime='' THEN @DTEND ELSE @dtNextLandTime END                    
--         AND(@bigFromLandmarkId IS NULL OR LandMarkID=@bigFromLandmarkId)ORDER BY LandTime DESC                    
     END                             
    SET @INC=@INC+1                    
       --select 'whinc1',IntProcessId=@IntProcessId ,DTSTART=@DTSTART,DTTRIPEND=@DTTRIPEND,vcStartAddress=@vcStartAddress,                
      -- vcEndAddress=@vcEndAddress,bigOdoStart=@bigOdoStart,bigOdoEnd=@bigOdoEnd,maxSpeed=@maxSpeed                    
                       
                       
    --GET THE TO PLACE DETAILS BETWEEN THE TRIPS                    
    SELECT TOP 1 @bigToLandmarkId = LandMarkID,@DTTRIPEND=LandTime,@vcEndAddress= StreetAdd,@bigOdoEnd =OdoMeter                     
     FROM @tblLandmarkDetails                           
      WHERE BoxId =@intBoxID                    
       AND LandTime BETWEEN @DTSTART AND @DTEND --AND LandMarkID IS not NULL and ProcessId !=@procid                   
        AND(@bigFromLandmarkId IS NULL OR (LandMarkID is not null AND ProcessId!=@procid))--LandMarkID!=@bigFromLandmarkId)                       
                       
    IF(@DTTRIPEND IS NULL OR @DTTRIPEND ='')                    
     BEGIN                    
      SELECT TOP 1 @vcEndAddress= 'Ongoing Trip',@bigOdoEnd =OdoMeter                     
       FROM @tblLandmarkDetails                           
      WHERE BoxId =@intBoxID                    
       AND LandTime BETWEEN @DTSTART AND @DTEND  ORDER BY LandTime DESC                    
     END                  
                       
      --  select 'idlbr',IntProcessId=@IntProcessId ,DTSTART=@DTSTART,DTTRIPEND=@DTTRIPEND,vcStartAddress=@vcStartAddress,                
      -- vcEndAddress=@vcEndAddress,bigOdoStart=@bigOdoStart,bigOdoEnd=@bigOdoEnd,maxSpeed=@maxSpeed                
                              
  IF(@DTSTART IS NOT NULL AND @DTTRIPEND IS NOT NULL)                    
  BEGIN                          
   --CALCULATE THE IDLING TIME                           
     SET @intIdlingDuration=(SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)as int)),0)                    
     FROM @tblLandmarkDetails                      
     WHERE BoxMsgInTypeId=9 AND BoxId=@intBoxID                     
      AND LandTime> @DTSTART AND LandTime<= ISNULL(@DTTRIPEND,@DTEND)                    
       GROUP BY BoxId)                    
                       
    SET @maxSpeed =0                    
    SET @maxSpeed = (SELECT MAX(Speed) FROM @tblLandmarkDetails WHERE BoxId=@intBoxID AND LandTime BETWEEN @DTSTART AND ISNULL(@DTTRIPEND,@DTEND))                    
                         
    SELECT @IntIgnition=SUM(a.Duration) FROM                     
    (SELECT CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,                    
     (CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-                    
      (CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT) as Duration                    
     FROM @tblLandmarkDetails  WHERE BoxId=@intBoxID AND LandTime BETWEEN @DTSTART AND ISNULL(@DTTRIPEND,@DTEND) AND BoxMsgInTypeId=3                     
     AND LandTime >(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE BoxId=@intBoxID AND LandTime                     
      BETWEEN @DTSTART AND ISNULL(@DTTRIPEND,@DTEND) AND BoxMsgInTypeId=2 ORDER BY LandTime)) A                     
    DECLARE @DTIGINITION DATETIME=NULL                    
    IF(@IntIgnition IS NULL OR @IntIgnition=0)                    
     BEGIN                    
      SELECT TOP 1 @DTIGINITION=LandTime FROM @tblLandmarkDetails WHERE Boxid =@intBoxID AND LandTime BETWEEN @DTSTART AND @DTTRIPEND AND Boxmsgintypeid =2                    
     END                     
                         
    IF(@DTIGINITION IS NULL OR @DTIGINITION=0)                    
     BEGIN                    
      SELECT TOP 1 @DTIGINITION=LandTime FROM @tblLandmarkDetails WHERE Boxid =@intBoxID AND LandTime BETWEEN @DTSTART AND @DTTRIPEND                     
     END          
                               
    if (@vcStartAddress<>@vcEndAddress or (@vcStartAddress=@vcEndAddress and (@bigOdoEnd-@bigOdoStart)>0))        
    begin                       
  INSERT INTO @TBLTRIPDETAILS (TripId,StartTime,EndTime,StartPlace,EndPlace,OdoStart,OdoEnd,MaxSpeed,Idling,Ignition)                    
  VALUES(@IntProcessId,@DTSTART,@DTTRIPEND,@vcStartAddress,@vcEndAddress,@bigOdoStart,@bigOdoEnd,@maxSpeed,                    
  CASE WHEN @intIdlingDuration !=0 AND @intIdlingDuration >DATEDIFF(S,@DTSTART,@DTTRIPEND) THEN DATEDIFF(S,@DTSTART,@DTTRIPEND) ELSE @intIdlingDuration END,                    
  CASE WHEN @IntIgnition IS NULL OR @IntIgnition>DATEDIFF(MINUTE,@DTSTART,@DTTRIPEND) THEN (DATEDIFF(S,ISNULL(@DTIGINITION,@DTSTART),@DTTRIPEND)) ELSE (@IntIgnition*60) END)                                      
    end         
                    
    UPDATE @TBLTRIPDETAILS SET StopTime =DATEDIFF(S,@DTSTARTSTOPTIME,@DTSTART) WHERE EndTime=@DTSTARTSTOPTIME                       
                       
    SET @DTSTARTSTOPTIME =@DTTRIPEND                       
    END                      
    SET @DTSTART=@DTTRIPEND                        
    --set @procid=@procid+1                   
   END                      
  SELECT @IntProcessId= MIN(TripId) FROM @tblTripDetailsForTD WHERE TripId>@IntProcessId               
                        
 END                    
 UPDATE @TBLTRIPDETAILS SET Idling =Ignition WHERE Idling>Ignition                      
                    
DECLARE @tblIdlingSummary TABLE                    
(                     
 TripId bigint null,                    
 Idling int null,                    
 Speed int null                    
)                    
INSERT INTO @tblIdlingSummary(TripId,Idling,Speed)                    
 SELECT TripId,SUM(Idling),MAX(MaxSpeed) FROM @TBLTRIPDETAILS GROUP BY TripId                     
                     
                      
 DECLARE @TBLSUMMARY TABLE                    
  (                    
 Boxid int null,                    
 TripDuration int null,                    
 IdlingDuration int null,                    
 TotRunningTime BIGINT null                    
  )                    
                      
  INSERT INTO @TBLSUMMARY (Boxid,TripDuration,IdlingDuration,TotRunningTime)                    
 SELECT BoxId,SUM(ISNULL(TripDuration,0)),SUM(ISNULL(ID.Idling,0)),                    
 SUM(ISNULL(TDD.Ignition,DateDiff(SS,ISNULL(TDD.StartTime,TD.StartDate),ISNULL(TDD.EndTime,TD.EndDate))))                      
 FROM  @tblTripDetailsForTD TD                    
  INNER JOIN @tblIdlingSummary ID ON ID.TripId=TD.TripId                     
  INNER JOIN @TBLTRIPDETAILS TDD ON TDD.TripId=TD.TripId                     
 GROUP BY BoxId            
      
SELECT T.TripId,T.TripdupId,V.VehicleId,V.VehicleDescription,V.LicensePlate,V.Vin,        
 DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)) as StartDate,        
 DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as EndDate        
 --StartDate,EndDate        
 ,ID.Speed,        
 CASE WHEN IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,        
 dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,StartDate,EndDate)) as Duration,         
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))))) as Distance,         
 StartAddress,CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END AS EndAddress  ,        
 CASE WHEN ID.Idling IS NULL OR ID.Idling='' OR ID.Idling=0 THEN '-' ELSE         
 dbo.rvlf_fn_GetTimeFromSeconds(ID.Idling) END AS IdlingTime,      
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStart)) AS OdometerStart,      
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,t.OdometerEnd)),'-') as OdometerEnd ,        
 @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,        
 dbo.rvlf_fn_getTimeFromSeconds(S.TripDuration) AS TotDuration,        
 CASE WHEN S.IdlingDuration IS NULL OR S.IdlingDuration='' OR S.IdlingDuration=0 THEN '-' ELSE         
 dbo.rvlf_fn_getTimeFromSeconds(S.IdlingDuration) END AS TotIdling,        
 StartTime = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,ISNULL(td.StartTime,T.StartDate)),      
 EndTime = dbo.rvlf_fn_DayLightSavings(@dtEDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,ISNULL(td.EndTime,T.EndDate)),      
--DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,ISNULL(td.StartTime,T.StartDate))) as StartTime,        
--DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,ISNULL(td.EndTime,T.EndDate))) as EndTime,        
 ISNULL(TD.StartPlace,CASE WHEN TD.TripId IS NULL THEN T.StartAddress ELSE '-' END) AS StartPlace,        
 ISNULL(TD.EndPlace,CASE WHEN TD.TripId IS NULL THEN CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END ELSE '-' END) AS EndPlace,        
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,TD.OdoStart)),CASE WHEN TD.TripId IS NULL THEN (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE 
 Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,T.OdometerStart)) ELSE '-' END) AS OdoStart ,        
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,TD.OdoEnd)),CASE WHEN TD.TripId IS NULL THEN ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance 
 ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,T.OdometerEnd)),'-') ELSE '-' END) AS OdoEnd,        
 ISNULL(TD.MaxSpeed,CASE WHEN TD.TripId IS NULL THEN T.Speed ELSE 0 END) AS MaxSpeed,        
 CASE WHEN TD.Idling IS NULL OR TD.Idling='' OR TD.Idling=0 THEN '-' ELSE         
  dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(TD.Idling, CASE WHEN TD.TripId IS NULL THEN ISNULL(ID.Idling,0) ELSE 0 END)) END AS Idling,         
 dbo.rvlf_fn_getTimeFromSeconds(ISNULL(TD.Ignition,DateDiff(SS,ISNULL(TD.StartTime,T.StartDate),ISNULL(TD.EndTime,T.EndDate)))) as DetailDuration,        
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(CAST((ABS(ISNULL((ISNULL(TD.OdoEnd,CASE WHEN TD.TripId IS NULL THEN T.OdometerEnd ELSE 0 END)-ISNULL(TD.OdoStart
  
    
,CASE WHEN TD.TripId IS NULL THEN T.OdometerStart ELSE 0 END)), 0)) * @ConversionFactor) as varchar(20))))) as DetailDistance,        
 dbo.rvlf_fn_getTimeFromSeconds(S.TotRunningTime) AS TotRunningTime,ISNULL(dbo.rvlf_fn_getTimeFromSeconds(TD.StopTime),'-') AS StopTime,      
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,      
 PasGeneratedDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())      
 --Convert(varchar,getdate(),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(getdate() as time),22) as PasGeneratedDate           
FROM @tblTripDetailsForTD T        
 INNER JOIN @tblIdlingSummary ID ON ID.TripId =T.TripId         
 INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=T.BoxId         
 INNER JOIN @TBLSUMMARY S ON S.Boxid=T.BoxId         
 INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId         
 LEFT OUTER JOIN @TBLTRIPDETAILS TD ON TD.TripId=T.TripId         
ORDER BY T.TripId          
        
--SELECT * FROM @tblLandmarkDetails where LandmarkId is not null        
--SELECT * FROM @tblTripDetailsForTD         
--SELECT * FROM @TBLTRIPDETAILS         
--SELECT * FROM @TBLSUMMARY         
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLandMarkTripSummary_New_test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetLandMarkTripSummary_New_test]         
 @bigFleetID bigint =  NULL,     
 @intBoxID varchar(max) =  NULL,    
 @bigFromLandmarkId bigint=  NULL,     
 @bigToLandmarkId bigint=  NULL,    
 @dtStartDate datetime =  NULL,     
 @dtEndDate datetime =  NULL,     
 @bigOrganizationID bigint =  NULL,    
 @bigQueryingUser bigint =  NULL       
AS         
/***********************************************************************************************************************/        
-- Name  : [rvlf_sp_GetLandMarkTripSummary_New_test] 529,'4533',3157,3157,'2015-09-18 08:00:00 AM', '2015-09-18 11:00:00 PM',263, 502       -- Description : To get the trip summary based on the landmarks        
-- Author  : V.Narayanasamy        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--   : 04-Mar-2011 VN Created Intial Version         
--          : 09-Aug-2011 Ranjith Date format Included        
--          : 30-Nov-2011 Sakthi Distance calculation based on organization      
/***********************************************************************************************************************/
        
BEGIN        
 SET NOCOUNT ON          
 Declare @dtFDate datetime =@dtStartDate          
 Declare @dtEDate datetime =@dtEndDate  
   
 IF @bigFleetID IS NULL        
  BEGIN        
   SELECT @bigFleetID=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)       
 DECLARE @DefaultDateFormat INT = 0       
    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 '(Km)' END,        
     @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' 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 = @bigQueryingUser        
         
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))        
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))    
  
         
 DECLARE @tblBoxes TABLE (BoxID int)          
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va         
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId        
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId        
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID=''     
    or BoxId in (select * from DBO.rvlf_fn_ConvertArrayToTable(@intBoxID,',')))         
    AND V.OrganizationId=@bigOrganizationID        
   ORDER BY BoxId          
           
 DECLARE @tblLandmarkDetails TABLE        
 (        
  Boxid int,        
  ProcessId bigint identity(1,1),         
  LandmarkId bigint,        
  LandTime datetime,        
  OdoMeter bigint,        
  StreetAdd varchar(300),        
  CustomProp varchar(600),        
  Boxmsgintypeid int,        
  TripId bigint,        
  Speed int        
 )        
         
 DECLARE @tblTripDetailsForTD TABLE(        
  [TripId] [INT] IDENTITY(1,1) NOT NULL,        
  [TripdupId] [bigint] NULL,        
  [BoxId] [int] NOT NULL,        
  [StartDate] [datetime] NOT NULL,        
  [EndDate] [datetime] NULL,        
  [OdometerStart] [bigint] NULL,        
  [OdometerEnd] [bigint] NULL,        
  [IsTripClosed] [bit] NULL,          
  [TripDuration] [int] NULL,          
  [StartAddress] nvarchar(300) NULL,        
  [EndAddress] nvarchar(300) NULL,        
  Speed int NULL        
 )        
         
 SELECT @intBoxID=MIN(BoxID) FROM @tblBoxes         
         
 WHILE @intBoxID IS NOT NULL        
  BEGIN        
   IF EXISTS(SELECT BoxId FROM rvlfMsgInHst WHERE BoxId =@intBoxID AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate         
    AND LandMarkID IN(@bigFromLandmarkId,@bigToLandmarkId))        
    BEGIN        
     --DELETE  FROM @tblLandmarkDetails         
     INSERT INTO @tblLandmarkDetails (LandmarkId,LandTime,OdoMeter,StreetAdd,Boxid,CustomProp,Boxmsgintypeid,Speed)         
      SELECT H.LandMarkID,OriginDateTime,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,        
        CASE WHEN H.LandMarkID IS NULL OR L.LandmarkName IS NULL THEN H.StreetAddress ELSE L.LandmarkName END,        
        @intBoxID,CustomProp,BoxMsgInTypeId,Speed           
       FROM rvlfMsgInHst h        
        LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID         
        WHERE BoxId =@intBoxID        
         AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate    
           and Odometer > 0          
                
        ORDER BY OriginDateTime   
   select '1',* from @tblLandmarkDetails 
     DECLARE @IntProcessId int =(SELECT MIN(ProcessId) FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)        
     DECLARE @dtStartTime datetime =null,@dtStopTime datetime=null,@intTripid int=1,@vcEndAddress nvarchar(250)=null,@bigOdoEnd bigint=null,@BITTRIPSTATUS BIT=1,        
       @intIdlingDuration int=0,@bigOdoStart bigint=NULL,@vcStartAddress nvarchar(250)=null,@intTrip int=null,@dtdupStartTime datetime=null        
     WHILE @IntProcessId IS NOT NULL        
      BEGIN                 
       IF EXISTS(SELECT TOP 1 Boxid FROM @tblLandmarkDetails WHERE LandmarkId =@bigFromLandmarkId AND LandmarkId IS NOT NULL AND ProcessId >@IntProcessId AND Boxid =@intBoxID)         
       BEGIN          
        IF (@bigFromLandmarkId !=@bigToLandmarkId)        
        BEGIN                          
         SET @dtStopTime =NULL           
        END           
        IF NOT EXISTS(SELECT TOP 1 ProcessId            
         FROM @tblLandmarkDetails         
         WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)        
          AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL)        
         BEGIN                  
          BREAK        
         END         
        ELSE        
         BEGIN        
          SELECT TOP 1 @IntProcessId=ProcessId  FROM @tblLandmarkDetails         
           WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)        
           AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL         
         END         
                                   
       --GET THE START TIME                             
         IF(@bigFromLandmarkId =@bigToLandmarkId)        
         BEGIN   
                               
        SELECT TOP 1 @IntProcessId=ProcessId,@dtStartTime=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter            
         FROM @tblLandmarkDetails         
         WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)        
          AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL         
          AND LandTime<(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId IS NOT NULL  AND LandmarkId !=@bigFromLandmarkId
           AND Boxid =@intBoxID AND ProcessId >@IntProcessId AND(@dtStopTime IS NULL OR LandTime >@dtStopTime)        
          AND LandTime>(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)) 
            
            ORDER BY LandTime DESC         
            SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId IS NOT NULL  AND LandmarkId !=@bigFromLandmarkId
           AND Boxid =@intBoxID AND ProcessId >@IntProcessId AND(@dtStopTime IS NULL OR LandTime >@dtStopTime)        
          AND LandTime>(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)  
             select 's1',@IntProcessId , @dtStartTime,@bigFromLandmarkId,@dtStopTime
         END        
        ELSE        
         BEGIN        
         SELECT TOP 1 @IntProcessId=ProcessId,@dtStartTime=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter            
          FROM @tblLandmarkDetails         
          WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)        
           AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL         
           AND LandTime<(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId IS NOT NULL  AND LandmarkId =@bigToLandmarkId         
             AND Boxid =@intBoxID AND ProcessId >@IntProcessId AND(@dtStopTime IS NULL OR LandTime >@dtStopTime)        
             AND LandTime>(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)) ORDER BY LandTime DESC         select 'se1',@IntProcessId, @dtStartTime
         END        
       IF (@dtStartTime=@dtdupStartTime)        
        BEGIN        
         BREAK        
        END                                     
        --GET THE STOP TIME        
       IF EXISTS(SELECT LandTime FROM @tblLandmarkDetails         
        WHERE LandTime >=(SELECT TOP 1 LandTime FROM @tblLandmarkDetails         
         WHERE LandmarkId NOT IN(@bigFromLandmarkId) AND (@dtStartTime IS NULL OR LandTime>@dtStartTime) AND Boxid =@intBoxID  )        
         AND (@dtStopTime IS NULL OR LandTime>@dtStopTime AND LandMarkID IS NOT NULL)        
         AND LandmarkId =@bigToLandmarkId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL)        
        BEGIN         
                         
         SELECT TOP 1 @IntProcessId=ProcessId, @dtStopTime =LandTime,@vcEndAddress =StreetAdd ,@bigOdoEnd =OdoMeter          
          FROM @tblLandmarkDetails         
          WHERE LandTime >=(SELECT TOP 1 LandTime FROM @tblLandmarkDetails         
           WHERE LandmarkId NOT IN(@bigFromLandmarkId) AND (@dtStartTime IS NULL OR LandTime>@dtStartTime) AND Boxid =@intBoxID )        
           AND (@dtStopTime IS NULL OR LandTime>@dtStopTime)        
           AND LandmarkId =@bigToLandmarkId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL          
               select 'st1', @IntProcessId, @dtStopTime     
        END        
       ELSE        
        BEGIN        
         SELECT @dtStopTime = CASE WHEN CONVERT(DATE,GETUTCDATE())=CONVERT(DATE,@dtEndDate) THEN GETUTCDATE()         
          ELSE @dtEndDate END,@BITTRIPSTATUS=0,@bigOdoEnd=NULL,@vcEndAddress =NULL        
         SELECT TOP 1 @bigOdoEnd = CAST( SUBSTRING (CustomProp,CHARINDEX('Odometer=',CustomProp,1)+9,CHARINDEX(';',CustomProp,        
          CHARINDEX('Odometer=',CustomProp,1)) - (CHARINDEX('Odometer=',CustomProp,1)+9)) as bigint) FROM rvlfMsgInHst         
         WHERE BoxId =@intBoxID AND CustomProp LIKE '%Odometer=%' AND OriginDateTime BETWEEN @dtStartDate AND @dtStopTime  ORDER BY OriginDateTime DESC   
         select 'ste1' ,@IntProcessId , @dtStopTime                
        END          
                  
       SET @intIdlingDuration=(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 @tblLandmarkDetails          
         WHERE LandTime  BETWEEN @dtStartTime AND @dtStopTime AND Boxid =@intBoxID  AND BoxMsgInTypeId =9         
         AND CustomProp NOT LIKE '%Idling:0;%')                          
              
       DECLARE @maxSpeed int=0        
       SET @maxSpeed = (SELECT MAX(Speed) from @tblLandmarkDetails where BoxId=@intBoxID and LandTime between @dtStartTime and @dtStopTime)        
               
       IF(@dtStartTime IS NOT NULL)        
       BEGIN 
       select '22'                      
       INSERT INTO @tblTripDetailsForTD (BoxId,StartDate,EndDate,OdometerStart,OdometerEnd,        
        StartAddress,EndAddress,IsTripClosed,Speed,TripDuration,TripdupId)        
       VALUES(@intBoxID,@dtStartTime,@dtStopTime,@bigOdoStart,@bigOdoEnd,@vcStartAddress,        
        @vcEndAddress,@BITTRIPSTATUS,@maxSpeed,DATEDIFF(S,@dtStartTime,@dtStopTime),@intTripid)               
       SET @intTrip=@@IDENTITY         
       SET @intTripid =@intTripid+1               
       UPDATE @tblLandmarkDetails SET TripId =@intTrip WHERE LandTime =@dtStartTime AND Boxid =@intBoxID AND TripId IS NULL        
       UPDATE @tblLandmarkDetails SET TripId =@intTrip WHERE LandTime =@dtStopTime AND Boxid =@intBoxID AND TripId IS NULL         
       END         
       ELSE        
        SELECT @IntProcessId =NULL FROM @tblLandmarkDetails          
       END          
       SET @dtdupStartTime=@dtStartTime                
       SELECT @IntProcessId = MIN(ProcessId) FROM @tblLandmarkDetails WHERE ProcessId >@IntProcessId AND (@dtStopTime IS NULL OR LandTime >@dtStopTime )        
      END             
    END        
                 
   SELECT @intBoxID=MIN(BoxID) FROM @tblBoxes WHERE BoxID >@intBoxID         
  END        
          

select '2',* from @tblTripDetailsForTD   
DECLARE @TBLTRIPDETAILS TABLE        
  (        
 TripId bigint null,        
 StartTime datetime null,        
 StartPlace nvarchar(250),        
 EndTime datetime null,        
 EndPlace nvarchar(250),        
 OdoStart bigint null,        
 OdoEnd bigint null,        
 Idling int null,        
 Ignition int null,        
 MaxSpeed tinyint null,        
 StopTime int null        
  )        
        
  SET @IntProcessId=NULL        
  SELECT @IntProcessId=MIN(TRIPID) FROM @tblTripDetailsForTD        
  WHILE @IntProcessId IS NOT NULL        
 BEGIN        
  DECLARE @DTSTART DATETIME=NULL,@DTSTARTSTOPTIME DATETIME=NULL,        
   @DTEND DATETIME=NULL,@bigTripID BIGINT =NULL        
  SET @vcEndAddress=null; SET @bigOdoEnd =null;        
  SET @intIdlingDuration=0;SET @bigOdoStart=NULL; SET @vcStartAddress=null;SET @bigFromLandmarkId =NULL;        
  SET @bigToLandmarkId =NULL;SET @intBoxID =NULL        
          
  SELECT @DTSTART =StartDate,@DTEND =EndDate,@intBoxID=BoxId FROM @tblTripDetailsForTD WHERE TripId=@IntProcessId         
  DECLARE @INC INT=0        
  WHILE @DTSTART < @DTEND         
   BEGIN        
    DECLARE @DTTRIPEND DATETIME=NULL,@IntIgnition INT =NULL        
    --GET THE FROM PLACE DETAILS BETWEEN THE TRIPS        
    SELECT TOP 1 @bigFromLandmarkId = LandMarkID,@DTSTART=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter          
     FROM @tblLandmarkDetails         
      WHERE BoxId =@intBoxID        
       AND LandTime BETWEEN @DTSTART AND @DTEND         
       AND(@bigFromLandmarkId IS NULL OR LandMarkID!=@bigFromLandmarkId)         
    IF(@INC!=0)        
     BEGIN          
      DECLARE @dtNextLandTime datetime=null        
      SELECT TOP 1 @dtNextLandTime=LandTime FROM @tblLandmarkDetails WHERE Boxid=@intBoxID AND LandTime BETWEEN @DTSTART AND @DTEND AND  LandmarkId IS NOT NULL AND LandmarkId !=@bigFromLandmarkId ORDER BY LandTime ASC        
      SELECT TOP 1 @bigFromLandmarkId = LandMarkID,@DTSTART=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter          
       FROM @tblLandmarkDetails         
        WHERE BoxId =@intBoxID        
         AND LandTime BETWEEN @DTSTART AND CASE WHEN @dtNextLandTime IS NULL OR @dtNextLandTime='' THEN @DTEND ELSE @dtNextLandTime END        
         AND(@bigFromLandmarkId IS NULL OR @bigFromLandmarkId='' OR LandMarkID=@bigFromLandmarkId)ORDER BY LandTime DESC        
     END                 
    SET @INC=@INC+1        
           
    --GET THE TO PLACE DETAILS BETWEEN THE TRIPS        
    SELECT TOP 1 @bigToLandmarkId = LandMarkID,@DTTRIPEND=LandTime,@vcEndAddress= StreetAdd,@bigOdoEnd =OdoMeter         
     FROM @tblLandmarkDetails               
      WHERE BoxId =@intBoxID        
       AND LandTime BETWEEN @DTSTART AND @DTEND         
       AND(@bigFromLandmarkId IS NULL OR @bigFromLandmarkId='' OR LandMarkID!=@bigFromLandmarkId)         
    IF(@DTTRIPEND IS NULL OR @DTTRIPEND ='')        
     BEGIN        
      SELECT TOP 1 @vcEndAddress= 'Ongoing Trip',@bigOdoEnd =OdoMeter         
       FROM @tblLandmarkDetails               
      WHERE BoxId =@intBoxID        
       AND LandTime BETWEEN @DTSTART AND @DTEND  ORDER BY LandTime DESC        
     END        
                       
  IF(@DTSTART IS NOT NULL AND @DTTRIPEND IS NOT NULL)        
  BEGIN              
   --CALCULATE THE IDLING TIME               
     SET @intIdlingDuration=(SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)as int)),0)        
     FROM @tblLandmarkDetails          
     WHERE BoxMsgInTypeId=9 AND BoxId=@intBoxID         
      AND LandTime> @DTSTART AND LandTime<= ISNULL(@DTTRIPEND,@DTEND)        
       GROUP BY BoxId)        
           
    SET @maxSpeed =0        
    SET @maxSpeed = (SELECT MAX(Speed) FROM @tblLandmarkDetails WHERE BoxId=@intBoxID AND LandTime BETWEEN @DTSTART AND ISNULL(@DTTRIPEND,@DTEND))        
             
    SELECT @IntIgnition=SUM(a.Duration) FROM         
    (SELECT CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,        
     (CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-        
      (CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT) as Duration        
     FROM @tblLandmarkDetails  WHERE BoxId=@intBoxID AND LandTime BETWEEN @DTSTART AND ISNULL(@DTTRIPEND,@DTEND) AND BoxMsgInTypeId=3         
     AND LandTime >(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE BoxId=@intBoxID AND LandTime         
      BETWEEN @DTSTART AND ISNULL(@DTTRIPEND,@DTEND) AND BoxMsgInTypeId=2 ORDER BY LandTime)) A         
    DECLARE @DTIGINITION DATETIME=NULL        
    IF(@IntIgnition IS NULL OR @IntIgnition=0)        
     BEGIN        
      SELECT TOP 1 @DTIGINITION=LandTime FROM @tblLandmarkDetails WHERE Boxid =@intBoxID AND LandTime BETWEEN @DTSTART AND @DTTRIPEND AND Boxmsgintypeid =2        
     END         
             
    IF(@DTIGINITION IS NULL OR @DTIGINITION=0)        
     BEGIN        
      SELECT TOP 1 @DTIGINITION=LandTime FROM @tblLandmarkDetails WHERE Boxid =@intBoxID AND LandTime BETWEEN @DTSTART AND @DTTRIPEND         
     END                
                     
    INSERT INTO @TBLTRIPDETAILS (TripId,StartTime,EndTime,StartPlace,EndPlace,OdoStart,OdoEnd,MaxSpeed,Idling,Ignition)        
     VALUES(@IntProcessId,@DTSTART,@DTTRIPEND,@vcStartAddress,@vcEndAddress,@bigOdoStart,@bigOdoEnd,@maxSpeed,        
     CASE WHEN @intIdlingDuration !=0 AND @intIdlingDuration >DATEDIFF(S,@DTSTART,@DTTRIPEND) THEN DATEDIFF(S,@DTSTART,@DTTRIPEND) ELSE @intIdlingDuration END,        
     CASE WHEN @IntIgnition IS NULL OR @IntIgnition>DATEDIFF(MINUTE,@DTSTART,@DTTRIPEND) THEN (DATEDIFF(S,ISNULL(@DTIGINITION,@DTSTART),@DTTRIPEND)) ELSE (@IntIgnition*60) END)                              
            
    UPDATE @TBLTRIPDETAILS SET StopTime =DATEDIFF(S,@DTSTARTSTOPTIME,@DTSTART) WHERE EndTime=@DTSTARTSTOPTIME           
            
    SET @DTSTARTSTOPTIME =@DTTRIPEND           
    END          
    SET @DTSTART=@DTTRIPEND                  
   END          
  SELECT @IntProcessId= MIN(TripId) FROM @tblTripDetailsForTD WHERE TripId>@IntProcessId           
 END        
 UPDATE @TBLTRIPDETAILS SET Idling =Ignition WHERE Idling>Ignition          
        
DECLARE @tblIdlingSummary TABLE        
(         
 TripId bigint null,        
 Idling int null,        
 Speed int null        
)        
INSERT INTO @tblIdlingSummary(TripId,Idling,Speed)        
 SELECT TripId,SUM(Idling),MAX(MaxSpeed) FROM @TBLTRIPDETAILS GROUP BY TripId         
         
select * from  @TBLTRIPDETAILS
select * from  @tblIdlingSummary

 DECLARE @TBLSUMMARY TABLE        
  (        
 Boxid int null,        
 TripDuration int null,        
 IdlingDuration int null,        
 TotRunningTime BIGINT null        
  )        
          
  INSERT INTO @TBLSUMMARY (Boxid,TripDuration,IdlingDuration,TotRunningTime)        
 SELECT BoxId,SUM(ISNULL(TripDuration,0)),SUM(ISNULL(ID.Idling,0)),        
 SUM(ISNULL(TDD.Ignition,DateDiff(SS,ISNULL(TDD.StartTime,TD.StartDate),ISNULL(TDD.EndTime,TD.EndDate))))          
 FROM  @tblTripDetailsForTD TD        
  INNER JOIN @tblIdlingSummary ID ON ID.TripId=TD.TripId         
  INNER JOIN @TBLTRIPDETAILS TDD ON TDD.TripId=TD.TripId         
 GROUP BY BoxId         

select * from @TBLSUMMARY
      
SELECT T.TripId,T.TripdupId,V.VehicleId,V.VehicleDescription,V.LicensePlate,V.Vin,        
 DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)) as StartDate,        
 DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as EndDate        
 --StartDate,EndDate        
 ,ID.Speed,        
 CASE WHEN IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,        
 dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,StartDate,EndDate)) as Duration,         
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))))) as Distance,         
 StartAddress,CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END AS EndAddress  ,        
 CASE WHEN ID.Idling IS NULL OR ID.Idling='' OR ID.Idling=0 THEN '-' ELSE         
 dbo.rvlf_fn_GetTimeFromSeconds(ID.Idling) END AS IdlingTime,      
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStart)) AS OdometerStart,      
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,t.OdometerEnd)),'-') as OdometerEnd ,        
 @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,        
 dbo.rvlf_fn_getTimeFromSeconds(S.TripDuration) AS TotDuration,        
 CASE WHEN S.IdlingDuration IS NULL OR S.IdlingDuration='' OR S.IdlingDuration=0 THEN '-' ELSE         
 dbo.rvlf_fn_getTimeFromSeconds(S.IdlingDuration) END AS TotIdling,        
 StartTime = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,ISNULL(td.StartTime,T.StartDate)),      
 EndTime = dbo.rvlf_fn_DayLightSavings(@dtEDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,ISNULL(td.EndTime,T.EndDate)),      
--DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,ISNULL(td.StartTime,T.StartDate))) as StartTime,        
--DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,ISNULL(td.EndTime,T.EndDate))) as EndTime,        
 ISNULL(TD.StartPlace,CASE WHEN TD.TripId IS NULL THEN T.StartAddress ELSE '-' END) AS StartPlace,        
 ISNULL(TD.EndPlace,CASE WHEN TD.TripId IS NULL THEN CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END ELSE '-' END) AS EndPlace,        
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,TD.OdoStart)),CASE WHEN TD.TripId IS NULL THEN (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE 
 Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,T.OdometerStart)) ELSE '-' END) AS OdoStart ,        
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,TD.OdoEnd)),CASE WHEN TD.TripId IS NULL THEN ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance 
 ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,T.OdometerEnd)),'-') ELSE '-' END) AS OdoEnd,        
 ISNULL(TD.MaxSpeed,CASE WHEN TD.TripId IS NULL THEN T.Speed ELSE 0 END) AS MaxSpeed,        
 CASE WHEN TD.Idling IS NULL OR TD.Idling='' OR TD.Idling=0 THEN '-' ELSE         
  dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(TD.Idling, CASE WHEN TD.TripId IS NULL THEN ISNULL(ID.Idling,0) ELSE 0 END)) END AS Idling,         
 dbo.rvlf_fn_getTimeFromSeconds(ISNULL(TD.Ignition,DateDiff(SS,ISNULL(TD.StartTime,T.StartDate),ISNULL(TD.EndTime,T.EndDate)))) as DetailDuration,        
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(CAST((ABS(ISNULL((ISNULL(TD.OdoEnd,CASE WHEN TD.TripId IS NULL THEN T.OdometerEnd ELSE 0 END)-ISNULL(TD.OdoStart
  
    
,CASE WHEN TD.TripId IS NULL THEN T.OdometerStart ELSE 0 END)), 0)) * @ConversionFactor) as varchar(20))))) as DetailDistance,        
 dbo.rvlf_fn_getTimeFromSeconds(S.TotRunningTime) AS TotRunningTime,ISNULL(dbo.rvlf_fn_getTimeFromSeconds(TD.StopTime),'-') AS StopTime,      
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,      
 PasGeneratedDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())      
 --Convert(varchar,getdate(),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(getdate() as time),22) as PasGeneratedDate           
FROM @tblTripDetailsForTD T        
 INNER JOIN @tblIdlingSummary ID ON ID.TripId =T.TripId         
 INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=T.BoxId         
 INNER JOIN @TBLSUMMARY S ON S.Boxid=T.BoxId         
 INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId         
 LEFT OUTER JOIN @TBLTRIPDETAILS TD ON TD.TripId=T.TripId         
ORDER BY T.TripId          
        
--SELECT * FROM @tblLandmarkDetails where LandmarkId is not null        
--SELECT * FROM @tblTripDetailsForTD         
--SELECT * FROM @TBLTRIPDETAILS         
--SELECT * FROM @TBLSUMMARY         
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLandMarkTripSummary_New-bkp22sep15]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetLandMarkTripSummary_New-bkp22sep15]         
 @bigFleetID bigint =  NULL,     
 @intBoxID varchar(max) =  NULL,    
 @bigFromLandmarkId bigint=  NULL,     
 @bigToLandmarkId bigint=  NULL,    
 @dtStartDate datetime =  NULL,     
 @dtEndDate datetime =  NULL,     
 @bigOrganizationID bigint =  NULL,    
 @bigQueryingUser bigint =  NULL       
AS         
/***********************************************************************************************************************/        
-- Name  : [rvlf_sp_GetLandMarkTripSummary_New] 186,'4240',1101,1101,'2014-08-19 08:00:00 AM', '2014-08-22 08:00:00 PM',121, 19        
-- Description : To get the trip summary based on the landmarks        
-- Author  : V.Narayanasamy        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--   : 04-Mar-2011 VN Created Intial Version         
--          : 09-Aug-2011 Ranjith Date format Included        
--          : 30-Nov-2011 Sakthi Distance calculation based on organization      
/***********************************************************************************************************************/        
        
BEGIN        
 SET NOCOUNT ON          
 Declare @dtFDate datetime =@dtStartDate          
 Declare @dtEDate datetime =@dtEndDate  
   
 IF @bigFleetID IS NULL        
  BEGIN        
   SELECT @bigFleetID=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)       
 DECLARE @DefaultDateFormat INT = 0       
    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 '(Km)' END,        
     @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' 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 = @bigQueryingUser        
         
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))        
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))    
  
         
 DECLARE @tblBoxes TABLE (BoxID int)          
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va         
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId        
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId        
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID=''     
    or BoxId in (select * from DBO.rvlf_fn_ConvertArrayToTable(@intBoxID,',')))         
    AND V.OrganizationId=@bigOrganizationID        
   ORDER BY BoxId          
           
 DECLARE @tblLandmarkDetails TABLE        
 (        
  Boxid int,        
  ProcessId bigint identity(1,1),         
  LandmarkId bigint,        
  LandTime datetime,        
  OdoMeter bigint,        
  StreetAdd varchar(300),        
  CustomProp varchar(600),        
  Boxmsgintypeid int,        
  TripId bigint,        
  Speed int        
 )        
         
 DECLARE @tblTripDetailsForTD TABLE(        
  [TripId] [INT] IDENTITY(1,1) NOT NULL,        
  [TripdupId] [bigint] NULL,        
  [BoxId] [int] NOT NULL,        
  [StartDate] [datetime] NOT NULL,        
  [EndDate] [datetime] NULL,        
  [OdometerStart] [bigint] NULL,        
  [OdometerEnd] [bigint] NULL,        
  [IsTripClosed] [bit] NULL,          
  [TripDuration] [int] NULL,          
  [StartAddress] nvarchar(300) NULL,        
  [EndAddress] nvarchar(300) NULL,        
  Speed int NULL        
 )        
         
 SELECT @intBoxID=MIN(BoxID) FROM @tblBoxes         
         
 WHILE @intBoxID IS NOT NULL        
  BEGIN        
   IF EXISTS(SELECT BoxId FROM rvlfMsgInHst WHERE BoxId =@intBoxID AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate         
    AND LandMarkID IN(@bigFromLandmarkId,@bigToLandmarkId))        
    BEGIN        
     --DELETE  FROM @tblLandmarkDetails         
     INSERT INTO @tblLandmarkDetails (LandmarkId,LandTime,OdoMeter,StreetAdd,Boxid,CustomProp,Boxmsgintypeid,Speed)         
      SELECT H.LandMarkID,OriginDateTime,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,        
        CASE WHEN H.LandMarkID IS NULL OR L.LandmarkName IS NULL THEN H.StreetAddress ELSE L.LandmarkName END,        
        @intBoxID,CustomProp,BoxMsgInTypeId,Speed           
       FROM rvlfMsgInHst h        
        LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID         
        WHERE BoxId =@intBoxID        
         AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate    
           and Odometer > 0          
         --AND H.LandMarkID IS NOT NULL         
        ORDER BY OriginDateTime          
     DECLARE @IntProcessId int =(SELECT MIN(ProcessId) FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)        
     DECLARE @dtStartTime datetime =null,@dtStopTime datetime=null,@intTripid int=1,@vcEndAddress nvarchar(250)=null,@bigOdoEnd bigint=null,@BITTRIPSTATUS BIT=1,        
       @intIdlingDuration int=0,@bigOdoStart bigint=NULL,@vcStartAddress nvarchar(250)=null,@intTrip int=null,@dtdupStartTime datetime=null        
     WHILE @IntProcessId IS NOT NULL        
      BEGIN                 
       IF EXISTS(SELECT TOP 1 Boxid FROM @tblLandmarkDetails WHERE LandmarkId =@bigFromLandmarkId AND LandmarkId IS NOT NULL AND ProcessId >@IntProcessId AND Boxid =@intBoxID)         
       BEGIN          
        IF (@bigFromLandmarkId !=@bigToLandmarkId )        
        BEGIN                          
         SET @dtStopTime =NULL           
        END           
        IF NOT EXISTS(SELECT TOP 1 ProcessId            
         FROM @tblLandmarkDetails         
         WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)        
          AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL)        
          --AND LandTime<(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId IS NOT NULL  AND LandmarkId !=@bigFromLandmarkId         
          --  AND Boxid =@intBoxID AND ProcessId >@IntProcessId AND(@dtStopTime IS NULL OR LandTime >@dtStopTime)        
          --  AND LandTime>(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)) ORDER BY LandTime DESC)        
         BEGIN                  
          BREAK        
         END         
        ELSE        
         BEGIN        
          SELECT TOP 1 @IntProcessId=ProcessId  FROM @tblLandmarkDetails         
           WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)        
           AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL         
         END         
                                   
       --GET THE START TIME                             
         IF(@bigFromLandmarkId =@bigToLandmarkId)        
         BEGIN                          
        SELECT TOP 1 @IntProcessId=ProcessId,@dtStartTime=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter            
         FROM @tblLandmarkDetails         
         WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)        
          AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL         
          AND LandTime<(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId IS NOT NULL  AND LandmarkId !=@bigFromLandmarkId         
            AND Boxid =@intBoxID AND ProcessId >@IntProcessId AND(@dtStopTime IS NULL OR LandTime >@dtStopTime)        
            AND LandTime>(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)) ORDER BY LandTime DESC                      
         END        
        ELSE        
         BEGIN        
         SELECT TOP 1 @IntProcessId=ProcessId,@dtStartTime=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter            
          FROM @tblLandmarkDetails         
          WHERE (@dtStopTime IS NULL OR LandTime >@dtStopTime)        
           AND LandmarkId =@bigFromLandmarkId AND ProcessId>=@IntProcessId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL         
           AND LandTime<(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId IS NOT NULL  AND LandmarkId =@bigToLandmarkId         
             AND Boxid =@intBoxID AND ProcessId >@IntProcessId AND(@dtStopTime IS NULL OR LandTime >@dtStopTime)        
             AND LandTime>(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE LandmarkId=@bigFromLandmarkId)) ORDER BY LandTime DESC         
         END        
       IF (@dtStartTime=@dtdupStartTime)        
        BEGIN        
         BREAK        
        END                                     
        --GET THE STOP TIME        
       IF EXISTS(SELECT LandTime FROM @tblLandmarkDetails         
        WHERE LandTime >=(SELECT TOP 1 LandTime FROM @tblLandmarkDetails         
         WHERE LandmarkId NOT IN(@bigFromLandmarkId) AND (@dtStartTime IS NULL OR LandTime>@dtStartTime) AND Boxid =@intBoxID  )        
         AND (@dtStopTime IS NULL OR LandTime>@dtStopTime AND LandMarkID IS NOT NULL)        
         AND LandmarkId =@bigToLandmarkId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL)        
        BEGIN         
                           
         SELECT TOP 1 @IntProcessId=ProcessId, @dtStopTime =LandTime,@vcEndAddress =StreetAdd ,@bigOdoEnd =OdoMeter          
          FROM @tblLandmarkDetails         
          WHERE LandTime >=(SELECT TOP 1 LandTime FROM @tblLandmarkDetails         
           WHERE LandmarkId NOT IN(@bigFromLandmarkId) AND (@dtStartTime IS NULL OR LandTime>@dtStartTime) AND Boxid =@intBoxID )        
           AND (@dtStopTime IS NULL OR LandTime>@dtStopTime)        
           AND LandmarkId =@bigToLandmarkId AND Boxid =@intBoxID AND LandMarkID IS NOT NULL          
                   
        END        
       ELSE        
        BEGIN        
         SELECT @dtStopTime = CASE WHEN CONVERT(DATE,GETUTCDATE())=CONVERT(DATE,@dtEndDate) THEN GETUTCDATE()         
          ELSE @dtEndDate END,@BITTRIPSTATUS=0,@bigOdoEnd=NULL,@vcEndAddress =NULL        
         SELECT TOP 1 @bigOdoEnd = CAST( SUBSTRING (CustomProp,CHARINDEX('Odometer=',CustomProp,1)+9,CHARINDEX(';',CustomProp,        
          CHARINDEX('Odometer=',CustomProp,1)) - (CHARINDEX('Odometer=',CustomProp,1)+9)) as bigint) FROM rvlfMsgInHst         
         WHERE BoxId =@intBoxID AND CustomProp LIKE '%Odometer=%' AND OriginDateTime BETWEEN @dtStartDate AND @dtStopTime  ORDER BY OriginDateTime DESC                  
        END          
                  
       SET @intIdlingDuration=(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 @tblLandmarkDetails          
         WHERE LandTime  BETWEEN @dtStartTime AND @dtStopTime AND Boxid =@intBoxID  AND BoxMsgInTypeId =9         
         AND CustomProp NOT LIKE '%Idling:0;%')                          
              
       DECLARE @maxSpeed int=0        
       SET @maxSpeed = (SELECT MAX(Speed) from @tblLandmarkDetails where BoxId=@intBoxID and LandTime between @dtStartTime and @dtStopTime)        
               
       IF(@dtStartTime IS NOT NULL)        
       BEGIN                       
       INSERT INTO @tblTripDetailsForTD (BoxId,StartDate,EndDate,OdometerStart,OdometerEnd,        
        StartAddress,EndAddress,IsTripClosed,Speed,TripDuration,TripdupId)        
       VALUES(@intBoxID,@dtStartTime,@dtStopTime,@bigOdoStart,@bigOdoEnd,@vcStartAddress,        
        @vcEndAddress,@BITTRIPSTATUS,@maxSpeed,DATEDIFF(S,@dtStartTime,@dtStopTime),@intTripid)               
       SET @intTrip=@@IDENTITY         
       SET @intTripid =@intTripid+1               
       UPDATE @tblLandmarkDetails SET TripId =@intTrip WHERE LandTime =@dtStartTime AND Boxid =@intBoxID AND TripId IS NULL        
       UPDATE @tblLandmarkDetails SET TripId =@intTrip WHERE LandTime =@dtStopTime AND Boxid =@intBoxID AND TripId IS NULL         
       END         
       ELSE        
        SELECT @IntProcessId =NULL FROM @tblLandmarkDetails          
       END          
       SET @dtdupStartTime=@dtStartTime                
       SELECT @IntProcessId = MIN(ProcessId) FROM @tblLandmarkDetails WHERE ProcessId >@IntProcessId AND (@dtStopTime IS NULL OR LandTime >@dtStopTime )        
      END             
    END        
                 
   SELECT @intBoxID=MIN(BoxID) FROM @tblBoxes WHERE BoxID >@intBoxID         
  END        
          
          
DECLARE @TBLTRIPDETAILS TABLE        
  (        
 TripId bigint null,        
 StartTime datetime null,        
 StartPlace nvarchar(250),        
 EndTime datetime null,        
 EndPlace nvarchar(250),        
 OdoStart bigint null,        
 OdoEnd bigint null,        
 Idling int null,        
 Ignition int null,        
 MaxSpeed tinyint null,        
 StopTime int null        
  )        
        
  SET @IntProcessId=NULL        
  SELECT @IntProcessId=MIN(TRIPID) FROM @tblTripDetailsForTD        
  WHILE @IntProcessId IS NOT NULL        
 BEGIN        
  DECLARE @DTSTART DATETIME=NULL,@DTSTARTSTOPTIME DATETIME=NULL,        
   @DTEND DATETIME=NULL,@bigTripID BIGINT =NULL        
  SET @vcEndAddress=null; SET @bigOdoEnd =null;        
  SET @intIdlingDuration=0;SET @bigOdoStart=NULL; SET @vcStartAddress=null;SET @bigFromLandmarkId =NULL;        
  SET @bigToLandmarkId =NULL;SET @intBoxID =NULL        
          
  SELECT @DTSTART =StartDate,@DTEND =EndDate,@intBoxID=BoxId FROM @tblTripDetailsForTD WHERE TripId=@IntProcessId         
  DECLARE @INC INT=0        
  WHILE @DTSTART < @DTEND         
   BEGIN        
    DECLARE @DTTRIPEND DATETIME=NULL,@IntIgnition INT =NULL        
    --GET THE FROM PLACE DETAILS BETWEEN THE TRIPS        
    SELECT TOP 1 @bigFromLandmarkId = LandMarkID,@DTSTART=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter          
     FROM @tblLandmarkDetails         
      WHERE BoxId =@intBoxID        
       AND LandTime BETWEEN @DTSTART AND @DTEND         
       AND(@bigFromLandmarkId IS NULL OR LandMarkID!=@bigFromLandmarkId)         
    IF(@INC!=0)        
     BEGIN          
      DECLARE @dtNextLandTime datetime=null        
      SELECT TOP 1 @dtNextLandTime=LandTime FROM @tblLandmarkDetails WHERE Boxid=@intBoxID AND LandTime BETWEEN @DTSTART AND @DTEND AND  LandmarkId IS NOT NULL AND LandmarkId !=@bigFromLandmarkId ORDER BY LandTime ASC        
      SELECT TOP 1 @bigFromLandmarkId = LandMarkID,@DTSTART=LandTime,@vcStartAddress=StreetAdd,@bigOdoStart=OdoMeter          
       FROM @tblLandmarkDetails         
        WHERE BoxId =@intBoxID        
         AND LandTime BETWEEN @DTSTART AND CASE WHEN @dtNextLandTime IS NULL OR @dtNextLandTime='' THEN @DTEND ELSE @dtNextLandTime END        
         AND(@bigFromLandmarkId IS NULL OR @bigFromLandmarkId='' OR LandMarkID=@bigFromLandmarkId)ORDER BY LandTime DESC        
     END                 
    SET @INC=@INC+1        
           
    --GET THE TO PLACE DETAILS BETWEEN THE TRIPS        
    SELECT TOP 1 @bigToLandmarkId = LandMarkID,@DTTRIPEND=LandTime,@vcEndAddress= StreetAdd,@bigOdoEnd =OdoMeter         
     FROM @tblLandmarkDetails               
      WHERE BoxId =@intBoxID        
       AND LandTime BETWEEN @DTSTART AND @DTEND         
       AND(@bigFromLandmarkId IS NULL OR @bigFromLandmarkId='' OR LandMarkID!=@bigFromLandmarkId)         
    IF(@DTTRIPEND IS NULL OR @DTTRIPEND ='')        
     BEGIN        
      SELECT TOP 1 @vcEndAddress= 'Ongoing Trip',@bigOdoEnd =OdoMeter         
       FROM @tblLandmarkDetails               
      WHERE BoxId =@intBoxID        
       AND LandTime BETWEEN @DTSTART AND @DTEND  ORDER BY LandTime DESC        
     END        
                       
  IF(@DTSTART IS NOT NULL AND @DTTRIPEND IS NOT NULL)        
  BEGIN              
   --CALCULATE THE IDLING TIME               
     SET @intIdlingDuration=(SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)as int)),0)        
     FROM @tblLandmarkDetails          
     WHERE BoxMsgInTypeId=9 AND BoxId=@intBoxID         
      AND LandTime> @DTSTART AND LandTime<= ISNULL(@DTTRIPEND,@DTEND)        
       GROUP BY BoxId)        
           
    SET @maxSpeed =0        
    SET @maxSpeed = (SELECT MAX(Speed) FROM @tblLandmarkDetails WHERE BoxId=@intBoxID AND LandTime BETWEEN @DTSTART AND ISNULL(@DTTRIPEND,@DTEND))        
             
    SELECT @IntIgnition=SUM(a.Duration) FROM         
    (SELECT CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,        
     (CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-        
      (CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT) as Duration        
     FROM @tblLandmarkDetails  WHERE BoxId=@intBoxID AND LandTime BETWEEN @DTSTART AND ISNULL(@DTTRIPEND,@DTEND) AND BoxMsgInTypeId=3         
     AND LandTime >(SELECT TOP 1 LandTime FROM @tblLandmarkDetails WHERE BoxId=@intBoxID AND LandTime         
      BETWEEN @DTSTART AND ISNULL(@DTTRIPEND,@DTEND) AND BoxMsgInTypeId=2 ORDER BY LandTime)) A         
    DECLARE @DTIGINITION DATETIME=NULL        
    IF(@IntIgnition IS NULL OR @IntIgnition=0)        
     BEGIN        
      SELECT TOP 1 @DTIGINITION=LandTime FROM @tblLandmarkDetails WHERE Boxid =@intBoxID AND LandTime BETWEEN @DTSTART AND @DTTRIPEND AND Boxmsgintypeid =2        
     END         
             
    IF(@DTIGINITION IS NULL OR @DTIGINITION=0)        
     BEGIN        
      SELECT TOP 1 @DTIGINITION=LandTime FROM @tblLandmarkDetails WHERE Boxid =@intBoxID AND LandTime BETWEEN @DTSTART AND @DTTRIPEND         
     END                
                     
    INSERT INTO @TBLTRIPDETAILS (TripId,StartTime,EndTime,StartPlace,EndPlace,OdoStart,OdoEnd,MaxSpeed,Idling,Ignition)        
     VALUES(@IntProcessId,@DTSTART,@DTTRIPEND,@vcStartAddress,@vcEndAddress,@bigOdoStart,@bigOdoEnd,@maxSpeed,        
     CASE WHEN @intIdlingDuration !=0 AND @intIdlingDuration >DATEDIFF(S,@DTSTART,@DTTRIPEND) THEN DATEDIFF(S,@DTSTART,@DTTRIPEND) ELSE @intIdlingDuration END,        
     CASE WHEN @IntIgnition IS NULL OR @IntIgnition>DATEDIFF(MINUTE,@DTSTART,@DTTRIPEND) THEN (DATEDIFF(S,ISNULL(@DTIGINITION,@DTSTART),@DTTRIPEND)) ELSE (@IntIgnition*60) END)                              
            
    UPDATE @TBLTRIPDETAILS SET StopTime =DATEDIFF(S,@DTSTARTSTOPTIME,@DTSTART) WHERE EndTime=@DTSTARTSTOPTIME           
            
    SET @DTSTARTSTOPTIME =@DTTRIPEND           
    END          
    SET @DTSTART=@DTTRIPEND                  
   END          
  SELECT @IntProcessId= MIN(TripId) FROM @tblTripDetailsForTD WHERE TripId>@IntProcessId           
 END        
 UPDATE @TBLTRIPDETAILS SET Idling =Ignition WHERE Idling>Ignition          
        
DECLARE @tblIdlingSummary TABLE        
(         
 TripId bigint null,        
 Idling int null,        
 Speed int null        
)        
INSERT INTO @tblIdlingSummary(TripId,Idling,Speed)        
 SELECT TripId,SUM(Idling),MAX(MaxSpeed) FROM @TBLTRIPDETAILS GROUP BY TripId         
         
          
 DECLARE @TBLSUMMARY TABLE        
  (        
 Boxid int null,        
 TripDuration int null,        
 IdlingDuration int null,        
 TotRunningTime BIGINT null        
  )        
          
  INSERT INTO @TBLSUMMARY (Boxid,TripDuration,IdlingDuration,TotRunningTime)        
 SELECT BoxId,SUM(ISNULL(TripDuration,0)),SUM(ISNULL(ID.Idling,0)),        
 SUM(ISNULL(TDD.Ignition,DateDiff(SS,ISNULL(TDD.StartTime,TD.StartDate),ISNULL(TDD.EndTime,TD.EndDate))))          
 FROM  @tblTripDetailsForTD TD        
  INNER JOIN @tblIdlingSummary ID ON ID.TripId=TD.TripId         
  INNER JOIN @TBLTRIPDETAILS TDD ON TDD.TripId=TD.TripId         
 GROUP BY BoxId         
      
SELECT T.TripId,T.TripdupId,V.VehicleId,V.VehicleDescription,V.LicensePlate,V.Vin,        
 DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)) as StartDate,        
 DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as EndDate        
 --StartDate,EndDate        
 ,ID.Speed,        
 CASE WHEN IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,        
 dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,StartDate,EndDate)) as Duration,         
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))))) as Distance,         
 StartAddress,CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END AS EndAddress  ,        
 CASE WHEN ID.Idling IS NULL OR ID.Idling='' OR ID.Idling=0 THEN '-' ELSE         
 dbo.rvlf_fn_GetTimeFromSeconds(ID.Idling) END AS IdlingTime,      
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStart)) AS OdometerStart,      
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,t.OdometerEnd)),'-') as OdometerEnd ,        
 @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,        
 dbo.rvlf_fn_getTimeFromSeconds(S.TripDuration) AS TotDuration,        
 CASE WHEN S.IdlingDuration IS NULL OR S.IdlingDuration='' OR S.IdlingDuration=0 THEN '-' ELSE         
 dbo.rvlf_fn_getTimeFromSeconds(S.IdlingDuration) END AS TotIdling,        
 StartTime = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,ISNULL(td.StartTime,T.StartDate)),      
 EndTime = dbo.rvlf_fn_DayLightSavings(@dtEDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,ISNULL(td.EndTime,T.EndDate)),      
--DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,ISNULL(td.StartTime,T.StartDate))) as StartTime,        
--DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,ISNULL(td.EndTime,T.EndDate))) as EndTime,        
 ISNULL(TD.StartPlace,CASE WHEN TD.TripId IS NULL THEN T.StartAddress ELSE '-' END) AS StartPlace,        
 ISNULL(TD.EndPlace,CASE WHEN TD.TripId IS NULL THEN CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END ELSE '-' END) AS EndPlace,        
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,TD.OdoStart)),CASE WHEN TD.TripId IS NULL THEN (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE 
 Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,T.OdometerStart)) ELSE '-' END) AS OdoStart ,        
 ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,TD.OdoEnd)),CASE WHEN TD.TripId IS NULL THEN ISNULL((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance 
 ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,T.OdometerEnd)),'-') ELSE '-' END) AS OdoEnd,        
 ISNULL(TD.MaxSpeed,CASE WHEN TD.TripId IS NULL THEN T.Speed ELSE 0 END) AS MaxSpeed,        
 CASE WHEN TD.Idling IS NULL OR TD.Idling='' OR TD.Idling=0 THEN '-' ELSE         
  dbo.rvlf_fn_GetTimeFromSeconds(ISNULL(TD.Idling, CASE WHEN TD.TripId IS NULL THEN ISNULL(ID.Idling,0) ELSE 0 END)) END AS Idling,         
 dbo.rvlf_fn_getTimeFromSeconds(ISNULL(TD.Ignition,DateDiff(SS,ISNULL(TD.StartTime,T.StartDate),ISNULL(TD.EndTime,T.EndDate)))) as DetailDuration,        
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(CAST((ABS(ISNULL((ISNULL(TD.OdoEnd,CASE WHEN TD.TripId IS NULL THEN T.OdometerEnd ELSE 0 END)-ISNULL(TD.OdoStart
  
    
,CASE WHEN TD.TripId IS NULL THEN T.OdometerStart ELSE 0 END)), 0)) * @ConversionFactor) as varchar(20))))) as DetailDistance,        
 dbo.rvlf_fn_getTimeFromSeconds(S.TotRunningTime) AS TotRunningTime,ISNULL(dbo.rvlf_fn_getTimeFromSeconds(TD.StopTime),'-') AS StopTime,      
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,      
 PasGeneratedDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())      
 --Convert(varchar,getdate(),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(getdate() as time),22) as PasGeneratedDate           
FROM @tblTripDetailsForTD T        
 INNER JOIN @tblIdlingSummary ID ON ID.TripId =T.TripId         
 INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=T.BoxId         
 INNER JOIN @TBLSUMMARY S ON S.Boxid=T.BoxId         
 INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId         
 LEFT OUTER JOIN @TBLTRIPDETAILS TD ON TD.TripId=T.TripId         
ORDER BY T.TripId          
        
--SELECT * FROM @tblLandmarkDetails where LandmarkId is not null        
--SELECT * FROM @tblTripDetailsForTD         
--SELECT * FROM @TBLTRIPDETAILS         
--SELECT * FROM @TBLSUMMARY         
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLatestNewsAndTips]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetLatestNewsAndTips]    
(    
  @bigOrganizationId bigint=null,    
  @bigTopNos bigint=5,  
  @bigUserId bigint = null      
)    
AS    
/****************************************************************************************/    
-- Name    : [rvlf_sp_GetLatestNewsAndTips] 6    
-- Description : To get the latest news details    
-- Author    : Jeyanthi.S    
-- Created Date  : 19-Oct-2010    
--  Modified Date :    
/***************************************************************************************/    
BEGIN    
  
SET NOCOUNT ON            
 SET @bigTopNos =100         
  DECLARE @DefaultDateFormat INT = 0;            
  DECLARE @HoursToBeAdded INT = 0                        
  DECLARE @MinsToBeAdded INT = 0                               
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,          
    @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                
   INNER JOIN rvlfUser U on U.UserId = up.UserId             
           
    declare @NewLine char(2)        
    set @NewLine=char(13)+char(10)        
            
 --used to get latest news          
 SELECT * FROM (          
 SELECT top (@bigTopNos) NewsId , NewsName,      
 --(NewsName + ' - ' + AuthorName) as NewsNameAuthor,      
 --NewsName as NewsNameAuthor,      
 NavigateURL,[Type],ExpiryDate,        
 REPLACE(REPLACE(REPLACE(NewsDescription,'&#39;','\'''),@NewLine,''),'"','') as  NewsDescription,isnull(AuthorName,'-') as AuthorName,ImageName,          
 CONVERT(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,PublishDate)),@DefaultDateFormat) as PublishDate,          
 --+ ' ' + CONVERT(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,PublishDate)) as time),22)        
 (case when DATEDIFF(DD,PublishDate,GETUTCDATE()) >= 7 then 0 else 1 end) as IsValid        
   FROM rvlfNews  --top (@bigTopNos)        
 WHERE CASE WHEN ExpiryDate IS NOT NULL THEN CONVERT(date,ExpiryDate)           
    ELSE  CONVERT(date,GETDATE()) END >=CONVERT(DATE,GETDATE())               
    AND CASE WHEN PublishDate IS NOT NULL THEN CONVERT(date,PublishDate)           
        ELSE  CONVERT(date,GETDATE()) END <=CONVERT(DATE,GETDATE())          
    AND [Type] <> 'Tips' --and OrganizationId =@bigOrganizationId            
    ORDER BY NewsId DESC)A          
    ORDER BY NewsId ASC          
                  
    --used to get the Tips          
    DECLARE @tipsCount bigint = (Select Count(NewsId) from rvlfNews WHERE [Type]='Tips')          
    IF @tipsCount=(Select Count(NewsId) from rvlfNews where TipsShownDate IS NOT NULL and [Type]='Tips')          
  BEGIN          
  Print 'A'          
    Update rvlfNews Set TipsShownDate=NULL          
    WHERE [Type]= 'Tips'          
  END          
            
 DECLARE @bigIsTipsShown bit=0           
 SET @bigIsTipsShown =(SELECT Count(NewsId) FROM  rvlfNews WHERE CONVERT(Date,TipsShownDate) =CONVERT(Date,GETDATE()) AND [Type]='Tips')          
          
           
 --IF (@bigIsTipsShown = 0)          
 -- BEGIN          
 --  PRINT 'B'          
 --   Update TOP (1) rvlfNews Set TipsShownDate=GETDATE()           
 --   WHERE [Type]= 'Tips' AND (TipsShownDate IS NULL)          
 -- END                   
    
    
           
 --SELECT TOP 1 NewsId As 'TipsID', NewsName AS 'TipsName',NewsDescription AS 'TipsDescription'           
 --   FROM rvlfNews WHERE Convert(Date,TipsShownDate)=CONVERT(Date,GetDate())           
 --   AND [Type] = 'Tips'          
 --   ORDER BY NewsId ASC      
      
      
         
    SELECT TOP 1 NewsId As 'TipsID', NewsName AS 'TipsName',NewsDescription AS 'TipsDescription'         
    FROM rvlfNews WHERE     
     [Type] = 'Tips'        
    ORDER BY CreatedDate DESC        
          
                  
 SET NOCOUNT OFF     
   
 --SET NOCOUNT ON      
----used to get latest news    
 --SELECT * FROM (    
 --SELECT top (@bigTopNos) NewsId , NewsName,NavigateURL,[Type],ExpiryDate  FROM rvlfNews    
 --WHERE CASE WHEN ExpiryDate IS NOT NULL THEN CONVERT(date,ExpiryDate)     
 --   ELSE  CONVERT(date,GETDATE()) END >=CONVERT(DATE,GETDATE())         
 --   AND CASE WHEN PublishDate IS NOT NULL THEN CONVERT(date,PublishDate)     
 --       ELSE  CONVERT(date,GETDATE()) END <=CONVERT(DATE,GETDATE())    
 --   AND [Type] <> 'Tips'    
 --   ORDER BY NewsId DESC)A    
 --   ORDER BY NewsId ASC    
            
 --   --used to get the Tips    
 --   DECLARE @tipsCount bigint = (Select Count(NewsId) from rvlfNews WHERE [Type]='Tips')    
 --   IF @tipsCount=(Select Count(NewsId) from rvlfNews where TipsShownDate IS NOT NULL and [Type]='Tips')    
 -- BEGIN    
 -- Print 'A'    
 --   Update rvlfNews Set TipsShownDate=NULL    
 --   WHERE [Type]= 'Tips'    
 -- END    
      
 --DECLARE @bigIsTipsShown bit=0     
 --SET @bigIsTipsShown =(SELECT Count(NewsId) FROM  rvlfNews WHERE CONVERT(Date,TipsShownDate) =CONVERT(Date,GETDATE()) AND [Type]='Tips')    
    
     
 --IF (@bigIsTipsShown = 0)    
 -- BEGIN    
 --  PRINT 'B'    
 --   Update TOP (1) rvlfNews Set TipsShownDate=GETDATE()     
 --   WHERE [Type]= 'Tips' AND (TipsShownDate IS NULL)    
 -- END    
     
     
 --SELECT TOP 1 NewsId As 'TipsID', NewsName AS 'TipsName',NewsDescription AS 'TipsDescription'     
 --   FROM rvlfNews WHERE Convert(Date,TipsShownDate)=CONVERT(Date,GetDate())     
 --   AND [Type] = 'Tips'    
 --   ORDER BY NewsId ASC    
            
 --SET NOCOUNT OFF    
END    
    
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLatestPopupNews]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
        
              
CREATE Procedure [dbo].[rvlf_sp_GetLatestPopupNews]    
(    
@UserId bigint  = 0,    
@UpdateRemnder bit = null    
)              
AS              
/****************************************************************************************/              
-- Name    : rvlf_sp_GetLatestPopupNews 19             
-- Description   : To get the news details              
-- Author    : ranjith N           
-- Created Date  : 16-Apr-2014              
/***************************************************************************************/              
BEGIN              
 SET NOCOUNT ON               
               
 if @UpdateRemnder is not null    
 Begin    
 Update rvlfUser set NewsReminder = GETUTCDATE() where UserId =@UserId    
 end    
 else    
 Begin    
 if not exists(select UserId from rvlfUser where UserId = @UserId and convert(date,NewsReminder) = CONVERT(date,getutcdate()))    
 Begin    
 SELECT top 10 NewsId,NewsName,NewsDescription,CONVERT(varchar(20),PublishDate,106) as PublishDate,AuthorName,isnull(ReleasePDFLink,'') as ReleasePDFLink            
 FROM rvlfNews                    
 WHERE --(@bigOrganizationId IS NULL OR OrganizationID=@bigOrganizationId) AND                         
 CONVERT(date,ExpiryDate) >=CONVERT(DATE,GETDATE())       
 AND [Type] <> 'Tips' and ExpiryDate is not null and PublishDate is not null and IsPushNotification = 0
 ORDER BY NewsId Desc      
 End      
 End      
                         
 --SELECT top 10 NewsId,NewsName,NewsDescription,CONVERT(varchar(20),PublishDate,106) as PublishDate,AuthorName          
 -- FROM rvlfNews                      
 --WHERE --(@bigOrganizationId IS NULL OR OrganizationID=@bigOrganizationId) AND                           
 --CONVERT(date,ExpiryDate) >=CONVERT(DATE,GETDATE())         
 --AND [Type] <> 'Tips' and ExpiryDate is not null and PublishDate is not null                  
 --ORDER BY NewsId Desc              
           
 SET NOCOUNT OFF              
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLatLng_ForBG]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetLatLng_ForBG]                                
as                                
/******************************************************************************/                                
-- Name  : [rvlf_sp_GetLatLng_ForBG]    
-- Description : To get the Latitude, Longitude to fill the street address                                
-- Author  : T.Sathish                                
-- Company  : Angler Technologies                                
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                
--    : 04-Aug-2009 TSK Created Intial Version                                 
--    : 10-Aug-2010 TSK Included the Isolation Level to avoid Deadlock                                
--    :   16-Aug-2010 LK  Included unresolved message count                                 
--              :   18-Aug-2010 LK  Blocked the address resolving for Org 'GVK EMRI'                                
--              :   18-Aug-2010 TSK Modified condition to Block the address resolving for Org 'GVK EMRI'                                
--    : 05-JAN-2011 VN update the valid address details in the msginhst table                       
--    : 3-Apr-2012 Vijay - select set of LatLngs for batch Process in google and NavTeq.                      
/******************************************************************************/                                
BEGIN                                
--SET ROWCOUNT 21                          
 -- Get the unresolved message count                                
 --SELECT COUNT(IsProcessed) AS 'MessageCount' FROM rvlfMsgInHst WHERE       
 ---- Latitude <> 0 AND Longitude <> 0 AND     
 --ValidGps = 0 AND IsProcessed=1         
 
 Select 100 as MessageCount                                
                                 
 DECLARE @tinycount tinyint                                
 DECLARE @requestCount bigint = 0                                
 DECLARE @bigNavTeqrequestCount bigint = 0                                
                                 
 SELECT @requestCount = RequestCount FROM rvlfGoogleRequest WHERE CONVERT(date,RequestDate) = CONVERT(date,GETUTCDATE())--RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110)                                
 SELECT @bigNavTeqrequestCount = RequestCount FROM rvlfNavTeqRequest WHERE CONVERT(date,RequestDate) = CONVERT(date,GETUTCDATE())                            
                                 
print @requestCount                       
 IF (@requestCount <= 50000 AND @bigNavTeqrequestCount  <= 500000)                            
 BEGIN                                    
  DECLARE @uiMsgInID uniqueidentifier=null, @dLatitude decimal(10,6) =null,@dLongitude decimal(10,6) =null,@vcStreetAddress varchar(250)=null                                                 
  DECLARE @bigBoxId AS BIGINT                            
  DECLARE @bigOrgId AS BIGINT                                  
                               
  -- Resolve the address for all the organization except GVK EMRI - 19                                
  --SELECT Top 1 @bigBoxId = BoxId FROM rvlfMsginhst                         
  --WHERE  Latitude<> 0 AND Longitude<>0 AND ValidGPS = 0 AND IsProcessed =1 --ORDER BY OriginDateTime DESC                                
      
      
   -- Resolve the address for all the organization except GVK EMRI - 19                                  
  SELECT Top 1 @uiMsgInID=MessageInID, @dLatitude=Latitude,@dLongitude=Longitude,@bigBoxId = BoxId FROM rvlfMsginhst WITH (READPAST)                                   
   WHERE      
   Latitude<> 0 AND Longitude<>0 AND     
   ValidGPS = 0 AND IsProcessed =1 ORDER BY OriginDateTime DESC                                  
                            
  --To get the organization map provider.                             
  SELECT TOP 1 @bigOrgId = OrganizationId FROM rvlfVehicleAssignment VA                                        
  INNER JOIN rvlfVehicle VH ON VH.VehicleId = VA.VehicleId WHERE BoxId = @bigBoxId           
                            
                            
        
                          
  -- Select TOP 20 distinct lat lngs for batch process based on the map provider                      
  --IF (@intMapProvider = 0)                        
  --BEGIN                        
  -- SELECT DISTINCT Latitude,Longitude,BoxId,StreetAddress FROM rvlfMsginhst msg WITH (NOLOCK)                         
  -- INNER JOIN rvlfOrganization org ON msg.BoxId =                         
  -- --WHERE  ValidGPS = 0 AND IsProcessed =1 AND org.OrgMapProvider = 0                        
  -- --IF (@requestCount <= 50000)                      
  -- --BEGIN                      
  -- ----print 'IN'                    
  -- -- SELECT DISTINCT Latitude,Longitude,msg.BoxId,StreetAddress,@intMapProvider AS MapProvider                         
  -- -- -- SELECT TOP 1 Latitude,Longitude,msg.BoxId,StreetAddress,@intMapProvider AS MapProvider                         
  -- -- FROM rvlfMsginhst msg WITH (NOLOCK)                         
  -- -- INNER JOIN rvlfBoxId Box ON Box.BoxId = msg.BoxId                          
  -- -- INNER JOIN rvlfOrganization org ON org.OrganizationId = Box.OrganizationId                         
  -- -- WHERE  ValidGPS = 0  AND IsProcessed =1 AND org.OrgMapProvider = @intMapProvider                     
  -- -- AND Latitude<> 0 AND Longitude<>0                   
  -- -- --AND msg.BoxId IN (Select boxid from rvlfBoxId where OrganizationId IN(121))          
  -- -- --138,118,59,        
  -- --END                           
  --END                        
  --ELSE IF(@intMapProvider = 1)                        
  --BEGIN                        
  -- SELECT DISTINCT Latitude,Longitude,BoxId,StreetAddress                        
  -- FROM rvlfMsginhst WITH (NOLOCK) WHERE  ValidGPS = 0 AND IsProcessed =1                          
  -- --SELECT DISTINCT Latitude,Longitude,msg.BoxId,StreetAddress,@intMapProvider AS MapProvider                         
  -- --FROM rvlfMsginhst msg WITH (NOLOCK)                         
  -- --INNER JOIN rvlfBoxId Box ON Box.BoxId = msg.BoxId                          
  -- --INNER JOIN rvlfOrganization org ON org.OrganizationId = Box.OrganizationId                         
  -- --WHERE  ValidGPS = 0 AND IsProcessed =1 AND org.OrgMapProvider = @intMapProvider                   
  -- --AND Latitude<> 0 AND Longitude<>0                    
  -- --AND msg.BoxId IN (Select boxid from rvlfBoxId where OrganizationId IN(121,118,119,138))      
  --END                                         
      
      
                                  
                                
  DECLARE @intMapProvider AS INT; --ISNULL(OrgMapProvider,1)                            
  SELECT @intMapProvider =ISNULL(OrgMapProvider,0)  FROM rvlfOrganization WHERE OrganizationId = @bigOrgId                            
                               
  SELECT TOP 1 @vcStreetAddress= StreetAddress FROM rvlfMsgInHst WHERE Latitude=@dLatitude AND Longitude = @dLongitude                                
  IF (@vcStreetAddress IS NOT NULL AND @vcStreetAddress!='' AND @vcStreetAddress!='N/A')                                
   BEGIN                                  
    EXEC rvlf_sp_UpdateAddress_BgProcess @dlatitude, @dlongitude, @vcStreetAddress, NULL,@uiMsgInid                                        
   END                                 
  ELSE                                
   BEGIN                                   
    IF(@dLatitude IS NOT NULL AND @dLatitude!=0)                                   
     SELECT @uiMsgInID as MessageInID, @dLatitude as Latitude,@dLongitude as Longitude,@intMapProvider AS MapProvider                                 
   END                                           
                                               
  SET @tinycount = @@rowcount                                 
                             
  IF(@tinycount <> 0)                                
   BEGIN                                   
   --print @intMapProvider                
   IF (@intMapProvider = 0)                              
   BEGIN                            
    IF EXISTS (SELECT RequestDate FROM rvlfGoogleRequest WHERE RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110))      
     BEGIN                                
      UPDATE rvlfGoogleRequest SET RequestCount = RequestCount + 1 WHERE RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110)                                      
     END                                
    ELSE                                
     BEGIN                                
      INSERT INTO rvlfGoogleRequest (RequestDate, RequestCount) VALUES (GETUTCDATE(), 1)                                      
     END                                
   END                              
   END                              
   ELSE IF (@intMapProvider = 1)                     
   BEGIN                            
  IF EXISTS (SELECT RequestDate FROM rvlfNavTeqRequest WHERE RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110))                                
   BEGIN                                
    UPDATE rvlfNavTeqRequest SET RequestCount = RequestCount + 1 WHERE RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110)                                      
   END                                
  ELSE                                
   BEGIN                                
    INSERT INTO rvlfNavTeqRequest (RequestDate, RequestCount) VALUES (GETUTCDATE(), 1)                                  
   END                                
    END                              
   END                            
                                
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLatLng_ForBG_Back]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetLatLng_ForBG_Back]                  
as                  
/******************************************************************************/                  
-- Name  : [rvlf_sp_GetLatLng_ForBG]                  
-- Description : To get the Latitude, Longitude to fill the street address                  
-- Author  : T.Sathish                  
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
--    : 04-Aug-2009 TSK Created Intial Version                   
--    : 10-Aug-2010 TSK Included the Isolation Level to avoid Deadlock                  
--    :   16-Aug-2010 LK  Included unresolved message count                   
--              :   18-Aug-2010 LK  Blocked the address resolving for Org 'GVK EMRI'                  
--              :   18-Aug-2010 TSK Modified condition to Block the address resolving for Org 'GVK EMRI'                  
--    : 05-JAN-2011 VN update the valid address details in the msginhst table                  
/******************************************************************************/                  
BEGIN                  
SET ROWCOUNT 20            
-- update the valid location street addresses first                  
 --UPDATE rvlfMsgInHst SET StreetAddress = NULL, IsProcessed = 0 WHERE (StreetAddress = 'Address Not Found!' OR StreetAddress IS NULL OR StreetAddress ='N/A') AND ValidGps=0 and BoxMsgInTypeId =8                  
 -- Get the unresolved message count                  
 --SELECT COUNT(IsProcessed) AS 'MessageCount' FROM rvlfMsgInHst WHERE Latitude<>0 AND Longitude<>0 AND ValidGps = 0 AND IsProcessed=1                  

 Select 100 as MessageCount              
                   
 DECLARE @tinycount tinyint                  
 DECLARE @requestCount bigint = 0                  
 --DECLARE @bigNavTeqrequestCount bigint = 0                  
                   
 SELECT @requestCount = RequestCount FROM rvlfGoogleRequest WHERE CONVERT(date,RequestDate) = CONVERT(date,GETUTCDATE())--RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110)                  
 --SELECT @bigNavTeqrequestCount = RequestCount FROM rvlfNavTeqRequest WHERE CONVERT(date,RequestDate) = CONVERT(date,GETUTCDATE())              
                   
 IF @requestCount  <= 50000                  
 BEGIN                  
  --DECLARE @uiMsgInID uniqueidentifier='2E28434E-3EF9-E011-94FA-00259003B373', @dLatitude decimal(10,6) ='12.802667',@dLongitude decimal(10,6) ='79.134198',                  
 -- @vcStreetAddress varchar(250)                    
  DECLARE @uiMsgInID uniqueidentifier=null, @dLatitude decimal(10,6) =null,@dLongitude decimal(10,6) =null,                  
   @vcStreetAddress varchar(250)=null                  
                         
   DECLARE @bigBoxId AS BIGINT                       
                 
  -- Resolve the address for all the organization except GVK EMRI - 19                  
  SELECT Top 1 @uiMsgInID=MessageInID, @dLatitude=Latitude,@dLongitude=Longitude,@bigBoxId = BoxId FROM rvlfMsginhst WITH (NOLOCK)                   
   WHERE  Latitude<> 0 AND Longitude<>0 AND ValidGPS = 0 AND IsProcessed =1         
   AND BoxId IN (SELECT BoxId FROM rvlfBoxId WHERE OrganizationId IN (121))        
   --ORDER BY OriginDateTime DESC                  
              
  --SELECT TOP 20 * FROM             
--SELECT DISTINCT Latitude,Longitude,BoxId,StreetAddress  FROM rvlfMsginhst WITH (NOLOCK)                   
--   WHERE  ValidGPS = 0 AND IsProcessed =1            
                           
    --To get the organization map provider.                          
  DECLARE @bigOrgId AS BIGINT                          
  SELECT @bigOrgId = OrganizationId FROM rvlfVehicleAssignment VA                          
  INNER JOIN rvlfVehicle VH ON VH.VehicleId = VA.VehicleId WHERE BoxId = @bigBoxId                   
                   
  DECLARE @intMapProvider AS INT; --ISNULL(OrgMapProvider,1)              
  SELECT @intMapProvider =ISNULL(OrgMapProvider,1)  FROM rvlfOrganization WHERE OrganizationId = @bigOrgId              
                 
  SELECT TOP 1 @vcStreetAddress= StreetAddress FROM rvlfMsgInHst WHERE Latitude=@dLatitude AND Longitude = @dLongitude                  
  IF (@vcStreetAddress IS NOT NULL AND @vcStreetAddress!='' AND @vcStreetAddress!='N/A')                  
   BEGIN                    
    EXEC rvlf_sp_UpdateAddress_BgProcess @dlatitude, @dlongitude, @vcStreetAddress, NULL,@uiMsgInid                          
   END                   
  ELSE                  
   BEGIN                     
    IF(@dLatitude IS NOT NULL AND @dLatitude!=0)           
     SELECT @uiMsgInID as MessageInID, @dLatitude as Latitude,@dLongitude as Longitude,@intMapProvider AS MapProvider                   
   END                             
                                 
  SET @tinycount = @@rowcount                   
                    
  --IF NOT FOUND ANY MESSAGES FOR RESOLVE THEN UPDATE THE STREET ADDRESS IN MSGINHST TABLE                  
  --IF(@tinycount = 0)                  
  -- BEGIN                  
  --  UPDATE rvlfMsgInHst SET StreetAddress = NULL, IsProcessed = 1 WHERE LATITUDE<>0 AND Longitude<>0 AND VALIDGPS=0 AND (StreetAddress = 'Address Not Found!' OR StreetAddress IS NULL OR StreetAddress ='N/A')                   
  -- END                  
  --ELSE                  
               
  IF(@tinycount <> 0)                  
   BEGIN                     
   IF @intMapProvider = '0'                
   BEGIN              
    IF EXISTS (SELECT RequestDate FROM rvlfGoogleRequest WHERE RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110))                  
     BEGIN                  
      UPDATE rvlfGoogleRequest SET RequestCount = RequestCount + 1 WHERE RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110)                        
     END                  
    ELSE                  
     BEGIN                  
      INSERT INTO rvlfGoogleRequest (RequestDate, RequestCount) VALUES (GETUTCDATE(), 1)                        
     END                  
   END                
   END                
   --ELSE IF @intMapProvider = '1'                  
   --BEGIN              
 --IF EXISTS (SELECT RequestDate FROM rvlfNavTeqRequest WHERE RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110))                  
 --    BEGIN                  
 --     UPDATE rvlfNavTeqRequest SET RequestCount = RequestCount + 1 WHERE RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110)                        
 --    END                  
 --   ELSE                  
 --    BEGIN                  
 --     INSERT INTO rvlfNavTeqRequest (RequestDate, RequestCount) VALUES (GETUTCDATE(), 1)                        
 --    END                  
 --  END                
 --  END              
    END          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLatLng_ForBG_BatchProcess]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetLatLng_ForBG_BatchProcess]                
as                
/******************************************************************************/                
-- Name  : [rvlf_sp_GetLatLng_ForBG]                
-- Description : To get the Latitude, Longitude to fill the street address                
-- Author  : T.Sathish                
-- Company  : Angler Technologies                
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                
--    : 04-Aug-2009 TSK Created Intial Version                 
--    : 10-Aug-2010 TSK Included the Isolation Level to avoid Deadlock                
--    :   16-Aug-2010 LK  Included unresolved message count                 
--              :   18-Aug-2010 LK  Blocked the address resolving for Org 'GVK EMRI'                
--              :   18-Aug-2010 TSK Modified condition to Block the address resolving for Org 'GVK EMRI'                
--    : 05-JAN-2011 VN update the valid address details in the msginhst table                
/******************************************************************************/                
BEGIN                
SET ROWCOUNT 20          
 -- Get the unresolved message count                
 --SELECT COUNT(IsProcessed) AS 'MessageCount' FROM rvlfMsgInHst WHERE Latitude<>0 AND Longitude<>0 AND ValidGps = 0 AND IsProcessed=1                         
 
 Select 100 as MessageCount   
                 
 DECLARE @tinycount tinyint                
 DECLARE @requestCount bigint = 0                
 DECLARE @bigNavTeqrequestCount bigint = 0                
                 
 SELECT @requestCount = RequestCount FROM rvlfGoogleRequest WHERE CONVERT(date,RequestDate) = CONVERT(date,GETUTCDATE())--RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110)                
 SELECT @bigNavTeqrequestCount = RequestCount FROM rvlfNavTeqRequest WHERE CONVERT(date,RequestDate) = CONVERT(date,GETUTCDATE())            
                 
print @requestCount       
 IF (@requestCount <= 50000 AND @bigNavTeqrequestCount  <= 50000)            
 BEGIN                    
     
  DECLARE @bigBoxId AS BIGINT            
  DECLARE @bigOrgId AS BIGINT                  
               
  -- Resolve the address for all the organization except GVK EMRI - 19                
  SELECT Top 1 @bigBoxId = BoxId FROM rvlfMsginhst         
  WHERE  Latitude<> 0 AND Longitude<>0 AND ValidGPS = 0 AND IsProcessed =1 --ORDER BY OriginDateTime DESC                
            
  --To get the organization map provider.             
  SELECT TOP 1 @bigOrgId = OrganizationId FROM rvlfVehicleAssignment VA                        
  INNER JOIN rvlfVehicle VH ON VH.VehicleId = VA.VehicleId WHERE BoxId = @bigBoxId          
            
            
  DECLARE @intMapProvider AS INT;         
  SELECT @intMapProvider =ISNULL(OrgMapProvider,0) FROM rvlfOrganization WHERE OrganizationId = @bigOrgId            
          
  -- SELECT TOP 20 distinct lat lngs for batch process based on the lat        
  IF (@intMapProvider = 0)        
  BEGIN        
           
   SELECT DISTINCT Latitude,Longitude,msg.BoxId,StreetAddress,@intMapProvider AS MapProvider         
   FROM rvlfMsginhst msg WITH (NOLOCK)         
   INNER JOIN rvlfBoxId Box ON Box.BoxId = msg.BoxId          
   INNER JOIN rvlfOrganization org ON org.OrganizationId = Box.OrganizationId         
   WHERE  ValidGPS = 0 AND Latitude<> 0 AND Longitude<>0        
   AND IsProcessed =1 AND org.OrgMapProvider = 0        
           
  END        
  ELSE IF(@intMapProvider = 1)        
  BEGIN        
          
   SELECT DISTINCT Latitude,Longitude,msg.BoxId,StreetAddress,@intMapProvider AS MapProvider         
   FROM rvlfMsginhst msg WITH (NOLOCK)         
   INNER JOIN rvlfBoxId Box ON Box.BoxId = msg.BoxId          
   INNER JOIN rvlfOrganization org ON org.OrganizationId = Box.OrganizationId         
   WHERE ValidGPS = 0 AND IsProcessed =1 AND org.OrgMapProvider = 1        
  END   
                           
   END                
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLatLng_ForBG_ByOrg]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetLatLng_ForBG_ByOrg]                          
as                          
/******************************************************************************/                          
-- Name  : [rvlf_sp_GetLatLng_ForBG]                          
-- Description : This Sp for running the Bg process for a specif organization                          
-- Author  : T.Sathish                          
-- Company  : Angler Technologies                          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                          
--    : 04-Aug-2009 TSK Created Intial Version                           
--    : 10-Aug-2010 TSK Included the Isolation Level to avoid Deadlock                  
--    :   16-Aug-2010 LK  Included unresolved message count                           
--              :   18-Aug-2010 LK  Blocked the address resolving for Org 'GVK EMRI'                          
--              :   18-Aug-2010 TSK Modified condition to Block the address resolving for Org 'GVK EMRI'                          
--    : 05-JAN-2011 VN update the valid address details in the msginhst table                          
/******************************************************************************/                          
BEGIN                          
                       
SET ROWCOUNT 1;               
-- update the valid location street addresses first                          
 --UPDATE rvlfMsgInHst SET StreetAddress = NULL, IsProcessed = 0 WHERE (StreetAddress = 'Address Not Found!' OR StreetAddress IS NULL OR StreetAddress ='N/A') AND ValidGps=0 and BoxMsgInTypeId =8                          
 -- Get the unresolved message count                          
 SELECT COUNT(IsProcessed) AS 'MessageCount' FROM rvlfMsgInHst WHERE ValidGps = 0 AND IsProcessed=1          
 --AND boxid IN (SELECT boxId FROM rvlfboxid WHERE organizationID = 121)          
            
                           
 DECLARE @tinycount tinyint                          
 DECLARE @requestCount bigint = 0          
                           
 SELECT @requestCount = RequestCount FROM rvlfGoogleRequest WHERE CONVERT(date,RequestDate) = CONVERT(date,GETUTCDATE())--RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110)                          
                           
 IF @requestCount <= 50000                          
 BEGIN                                           
  DECLARE @uiMsgInID uniqueidentifier=null, @dLatitude decimal(10,6) =null,@dLongitude decimal(10,6) =null,                          
   @vcStreetAddress varchar(250)=null                          
             
                               
   --Resolve the address for all the organization except GVK EMRI - 19               
                         
  SELECT @uiMsgInID=MessageInID, @dLatitude=Latitude,@dLongitude=Longitude          
  FROM rvlfMsginhst WITH (NOLOCK) WHERE  ValidGPS = 0 AND IsProcessed =1            
  AND Boxid IN(select Boxid from rvlfboxid where OrganizationId = 121)              
          
                            
  SELECT @vcStreetAddress= StreetAddress FROM rvlfMsgInHst WHERE Latitude=@dLatitude AND Longitude = @dLongitude                          
  IF (@vcStreetAddress IS NOT NULL AND @vcStreetAddress!='' AND @vcStreetAddress!='N/A')                          
   BEGIN                            
    EXEC rvlf_sp_UpdateAddress_BgProcess @dlatitude, @dlongitude, @vcStreetAddress, NULL,@uiMsgInid                                  
   END                       
  ELSE                          
   BEGIN                             
    IF(@dLatitude IS NOT NULL AND @dLatitude!=0)                             
     SELECT @uiMsgInID as MessageInID, @dLatitude as Latitude,@dLongitude as Longitude,'0' AS MapProvider                             
   END                                     
                                         
  SET @tinycount = @@rowcount                           
  IF(@tinycount <> 0)                          
   BEGIN                          
    IF EXISTS (SELECT RequestDate FROM rvlfGoogleRequest WHERE RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110))                          
     BEGIN                          
      UPDATE rvlfGoogleRequest SET RequestCount = RequestCount + 1 WHERE RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110)                          
     END                          
    ELSE                          
  BEGIN                          
      INSERT INTO rvlfGoogleRequest (RequestDate, RequestCount) VALUES (GETUTCDATE(), 1)                
     END                          
   END                          
 END                          
END     
    
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLatLng_ForBG_Google]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE PROCEDURE [dbo].[rvlf_sp_GetLatLng_ForBG_Google]    
as                                                                      
/******************************************************************************/                                                        
-- Name  : [rvlf_sp_GetLatLng_ForBG_Google]  
-- Description : To get the Latitude, Longitude to fill the street address for google and navteq parallel process  
-- Author  : N.Vijay  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 07-Aug-2012 Vijay N Created Intial Version  
--    : 22-Aug-2013 Sathish - Commented the unwanted condition to reset the status  
/******************************************************************************/                                                        
BEGIN                                                                      
--SET ROWCOUNT 10                                                        
 -- Get the unresolved message count                                  
 DECLARE @intCount AS BIGINT                                                       
                                                       
 --SELECT * FROM (                                                        
 SELECT @intCount = COUNT(IsProcessed) FROM rvlfMsgInHst M WITH (READPAST)  
 INNER JOIN rvlfBoxId B ON B.BoxID = M.BoxId  
  WHERE Latitude<>0 AND Longitude<>0 AND ValidGps = 0 AND IsProcessed=1 AND B.OrganizationId = 176 and CONVERT(date,M.origindatetime) = CONVERT(date,GETDATE())  
   
 --) AS tbl                                          
                                                               
SELECT @intCount AS MessageCount, ISNULL((SELECT TOP 1 RequestCount FROM rvlfGoogleRequest WHERE RequestDate = CAST(GETUTCDATE() AS DATE)),0) AS GoogleRequestCount                                                      
        
      -- Commented by Sathish (as Google BgProcess does not require this condition)  
--IF @intCount = 0                                           
--BEGIN                                          
-- UPDATE TOP(20) rvlfMsgInHst SET IsProcessed = 1 WHERE StreetAddress LIKE 'Address could not be resolved!%'                                        
-- AND CAST(OriginDateTime AS DATE) = CAST(GETDATE() AS DATE)                                          
--END                                          
          
                                                      
--IF (@intCount > 0)                            
--BEGIN                                                      
--  --DECLARE @tinycount tinyint                                                             
--  DECLARE @requestCount bigint = 0                                                                      
--  DECLARE @bigNavTeqrequestCount bigint = 0                                                                
                                                                        
--  SELECT @requestCount = RequestCount FROM rvlfGoogleRequest WHERE CONVERT(date,RequestDate) = CONVERT(date,GETUTCDATE())--RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110)                                                                      
--  SELECT @bigNavTeqrequestCount = RequestCount FROM rvlfNavTeqRequest WHERE CONVERT(date,RequestDate) = CONVERT(date,GETUTCDATE())                                                                  
                                                            
                                                            
-- --SELECT TOP 20 distinct lat lngs for batch process for Google                                                        
--  IF (@requestCount <= 50000)                                                    
--  BEGIN                                          
-- SELECT *,ROW_NUMBER() OVER(ORDER BY BoxId DESC) AS [INDEX] FROM (          
--    SELECT TOP 10 * FROM (                                            
--    SELECT DISTINCT Latitude,Longitude,msg.BoxId,StreetAddress,0 AS MapProvider                   
--    FROM rvlfMsginhst msg WITH (READPAST)                                                        
--    INNER JOIN rvlfBoxId Box ON Box.BoxId = msg.BoxId                                                                
--    INNER JOIN rvlfOrganization org ON org.OrganizationId = Box.OrganizationId                                       
--    WHERE  ValidGPS = 0 AND Latitude<> 0 AND Longitude<>0                                          
--    AND IsProcessed =1                              
--    --AND Box.OrganizationId = 138                            
--    AND org.CountryId = 100 AND Box.OrganizationId NOT IN (121)                      
--    ) AS TblGoogle ORDER BY NEWID() )AS TBL ORDER BY [INDEX]          
                                          
                                                    
--     --SELECT NULL as Latitude,NULL as Longitude,NULL As BoxId,NULL AS StreetAddress, NULL AS MapProvider                                 
--     --WHERE 1 = 2                                              
                                                          
-- END                                                        
-- ELSE                                                     
-- BEGIN                                                        
--  SELECT NULL as Latitude,NULL as Longitude,NULL As BoxId,NULL AS StreetAddress, NULL AS MapProvider                                                        
--  WHERE 1 = 2                                                        
-- END                                                    
                                                            
-- --SELECT TOP 20 distinct lat lngs for batch process for navteq                                         
-- IF(@bigNavTeqrequestCount  <= 500000)                                                             
--BEGIN                                                 
--SELECT *,ROW_NUMBER() OVER(ORDER BY BoxId DESC) AS [INDEX] FROM (                        
--SELECT TOP 20 * FROM (                                                          
--  SELECT DISTINCT Latitude,Longitude,msg.BoxId,StreetAddress,1 AS MapProvider                                                                 
--   FROM rvlfMsginhst msg WITH (READPAST)                                                               
--   INNER JOIN rvlfBoxId Box ON Box.BoxId = msg.BoxId                                                                
--   INNER JOIN rvlfOrganization org ON org.OrganizationId = Box.OrganizationId                                                               
--   WHERE  ValidGPS = 0 AND IsProcessed =1                                              
--   AND (org.CountryId <> 100 OR Box.OrganizationId IN (121))                                              
--   ) AS TblNavTeq ORDER BY NEWID()) AS TBL ORDER BY [INDEX]                    
--END                                                        
--ELSE                                                        
--BEGIN                                          
--   SELECT NULL as Latitude,NULL as Longitude,NULL As BoxId,NULL AS StreetAddress, NULL AS MapProvider                                                        
--   WHERE 1 = 2                                                        
--END                                                        
--END             
          
SELECT *,ROW_NUMBER() OVER(ORDER BY BoxId DESC) AS [INDEX] FROM (       
SELECT TOP 10 * FROM (       
SELECT DISTINCT Latitude,Longitude,msg.BoxId,StreetAddress,StreetAddress_AR    
   FROM rvlfMsginhst msg WITH (READPAST)                                              
   INNER JOIN rvlfBoxId Box ON Box.BoxId = msg.BoxId                                  
   INNER JOIN rvlfOrganization org ON org.OrganizationId = Box.OrganizationId         
   WHERE  ValidGPS = 0 AND Latitude<> 0 AND Longitude<>0                              
   AND IsProcessed = 1       
   AND Box.OrganizationId = 176    
   ) AS TblGoogle ORDER BY NEWID() )AS TBL ORDER BY [INDEX]    
       
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLatLng_ForBG_ParallelBatchProcess]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetLatLng_ForBG_ParallelBatchProcess]                                                            
as                                                                          
/******************************************************************************/                                                            
-- Name  : [rvlf_sp_GetLatLng_ForBG_ParallelBatchProcess]                                                                          
-- Description : To get the Latitude, Longitude to fill the street address for google and navteq parallel process    
-- Author : N.Vijay                                                        
-- Company  : Angler Technologies                                                                          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                                                          
--   : 07-Aug-2012 Vijay N Created Intial Version              
--   : 22-Oct-2013 - Sakthi Get landmark data for address resolving                                                                                   
--   : 07-Apr-2014 - Sakthi Increasing the address resolving limit from 20 to 50    
/******************************************************************************/                                                            
BEGIN                                                                          
--SET ROWCOUNT 10                                                            
 -- Get the unresolved message count                                      
 DECLARE @intCount AS BIGINT                                                           
                                                           
 ----SELECT * FROM (                                                            
 --SELECT @intCount = COUNT(IsProcessed) FROM rvlfMsgInHst msg WITH (READPAST)   
 --INNER JOIN rvlfBoxId Box ON Box.BoxId = msg.BoxId                                      
 --INNER JOIN rvlfOrganization org ON org.OrganizationId = Box.OrganizationId             
 --WHERE msg.Latitude<>0 AND msg.Longitude<>0 AND msg.ValidGps = 0 AND msg.IsProcessed=1                                                            
 ----) AS tbl      
 SELECT @intCount = 100                                         
                                                                   
SELECT @intCount AS MessageCount, ISNULL((SELECT TOP 1 RequestCount FROM rvlfGoogleRequest WHERE RequestDate = CAST(GETUTCDATE() AS DATE)),0) AS GoogleRequestCount                                                          
                                              
IF @intCount = 0                                               
BEGIN                                              
 UPDATE TOP(20) rvlfMsgInHst SET IsProcessed = 1 WHERE StreetAddress LIKE 'Address could not be resolved!%'                                            
 AND CAST(OriginDateTime AS DATE) = CAST(GETDATE() AS DATE) AND IsProcessed = 0    
END                                              
              
                                                          
--IF (@intCount > 0)     
--BEGIN                                                          
--  --DECLARE @tinycount tinyint                                                                 
--  DECLARE @requestCount bigint = 0                                                                          
--  DECLARE @bigNavTeqrequestCount bigint = 0                                                                    
                                                                            
--  SELECT @requestCount = RequestCount FROM rvlfGoogleRequest WHERE CONVERT(date,RequestDate) = CONVERT(date,GETUTCDATE())--RequestDate = CONVERT(Varchar(10),GETUTCDATE(), 110)                                                                          
--  SELECT @bigNavTeqrequestCount = RequestCount FROM rvlfNavTeqRequest WHERE CONVERT(date,RequestDate) = CONVERT(date,GETUTCDATE())                                                                      
                                                      
                                                                
-- --SELECT TOP 20 distinct lat lngs for batch process for Google                                                            
--  IF (@requestCount <= 50000)                                                  
--  BEGIN                                              
--SELECT *,ROW_NUMBER() OVER(ORDER BY BoxId DESC) AS [INDEX] FROM (             
--    SELECT TOP 10 * FROM (                                                
-- SELECT DISTINCT Latitude,Longitude,msg.BoxId,StreetAddress,0 AS MapProvider                                                         
--    FROM rvlfMsginhst msg WITH (READPAST)                                                            
--    INNER JOIN rvlfBoxId Box ON Box.BoxId = msg.BoxId                                                                    
--    INNER JOIN rvlfOrganization org ON org.OrganizationId = Box.OrganizationId                                           
--    WHERE  ValidGPS = 0 AND Latitude<> 0 AND Longitude<>0                                              
--    AND IsProcessed =1                                  
--    --AND Box.OrganizationId = 138                                
--    AND org.CountryId = 100 AND Box.OrganizationId NOT IN (121)                          
--    ) AS TblGoogle ORDER BY NEWID() )AS TBL ORDER BY [INDEX]              
                                              
                                                        
--     --SELECT NULL as Latitude,NULL as Longitude,NULL As BoxId,NULL AS StreetAddress, NULL AS MapProvider                                     
--     --WHERE 1 = 2                                                  
                                                              
-- END                                                            
-- ELSE                                                         
-- BEGIN                                                            
--  SELECT NULL as Latitude,NULL as Longitude,NULL As BoxId,NULL AS StreetAddress, NULL AS MapProvider                                                            
--  WHERE 1 = 2                                                            
-- END                                                        
                                                                
-- --SELECT TOP 20 distinct lat lngs for batch process for navteq                                             
-- IF(@bigNavTeqrequestCount  <= 500000)                                                                 
--BEGIN                                                     
--SELECT *,ROW_NUMBER() OVER(ORDER BY BoxId DESC) AS [INDEX] FROM (                            
--SELECT TOP 20 * FROM (                                                              
--  SELECT DISTINCT Latitude,Longitude,msg.BoxId,StreetAddress,1 AS MapProvider                                                                     
--   FROM rvlfMsginhst msg WITH (READPAST)                                                                   
--   INNER JOIN rvlfBoxId Box ON Box.BoxId = msg.BoxId                                                                    
--   INNER JOIN rvlfOrganization org ON org.OrganizationId = Box.OrganizationId                                                                   
--   WHERE  ValidGPS = 0 AND IsProcessed =1                                                  
--   AND (org.CountryId <> 100 OR Box.OrganizationId IN (121))                                                  
--   ) AS TblNavTeq ORDER BY NEWID()) AS TBL ORDER BY [INDEX]                        
--END                                                            
--ELSE                                                            
--BEGIN      
--   SELECT NULL as Latitude,NULL as Longitude,NULL As BoxId,NULL AS StreetAddress, NULL AS MapProvider                                                            
--   WHERE 1 = 2                                                   
--END                                                            
--END                 
        
    -- Commented 176 to resolve revive using NavTeq    
        
SELECT *,ROW_NUMBER() OVER(ORDER BY BoxId DESC) AS [INDEX] FROM (           
SELECT TOP 75 * FROM (           
SELECT DISTINCT Latitude,Longitude,msg.BoxId,StreetAddress     
FROM rvlfMsgInHst_Techno msg WITH (READPAST)                                                  
INNER JOIN rvlfBoxId Box ON Box.BoxId = msg.BoxId                                      
INNER JOIN rvlfOrganization org ON org.OrganizationId = Box.OrganizationId             
WHERE  ValidGPS = 0 AND Latitude<> 0 AND Longitude<>0                                  
AND IsProcessed = 1           
UNION ALL    
SELECT DISTINCT Latitude,Longitude,msg.BoxId,StreetAddress     
FROM rvlfMsgInHst_Techno_355 msg WITH (READPAST)                                                  
INNER JOIN rvlfBoxId Box ON Box.BoxId = msg.BoxId                                      
INNER JOIN rvlfOrganization org ON org.OrganizationId = Box.OrganizationId             
WHERE  ValidGPS = 0 AND Latitude<> 0 AND Longitude<>0                                  
AND IsProcessed = 1           
UNION ALL   
SELECT Latitude,Longitude,'999222',NULL FROM dbo.rvlfLandmark WHERE StreetAddress IS NULL    
   -- AND Box.OrganizationId <> 176        
) AS TblGoogle ORDER BY NEWID() )AS TBL ORDER BY [INDEX]        
              
--SELECT *,ROW_NUMBER() OVER(ORDER BY StreetAddress) AS [INDEX]  FROM (     
--SELECT TOP 20 * FROM                                                                   
--(SELECT DISTINCT Latitude,Longitude,BoxId,StreetAddress,StreetAddress_AR FROM TRINETRA_Pilot.[dbo].[rvlfMsginhst] WITH (READPAST)                                                                                           
--   WHERE  ValidGPS = 0 AND IsProcessed =1) AS TBL ORDER BY NEWID()                                                
--) AS TBL ORDER BY [INDEX]              
                                                          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLatLng_ForBG_WeatherInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 27-Apr-2017
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetLatLng_ForBG_WeatherInfo] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT	B.BoxId, B.LastLatitude, B.LastLongitude, B.WeatherInfo 
	From	rvlfBoxId B
	Inner	Join  rvlfMsgInHst H On B.MessageInId = H.MessageInID 
	Where	B.OrganizationId = 86
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLatLngDetailsForNavteq]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================    
-- EXEC rvlf_sp_GetLatLngDetailsForNavteq '7/21/2012 4:51:06 AM','7/21/2012 5:06:06 AM'  
-- Author:  Vijay N    
-- Create date: 20-Jul-2012    
-- Description: Get the lat lng Details for service.    
-- =============================================    
CREATE PROCEDURE [dbo].[rvlf_sp_GetLatLngDetailsForNavteq]    
 -- Add the parameters for the stored procedure here    
 @FromDate DATETIME,    
 @ToDate DATETIME    
AS    
BEGIN    
 -- SET NOCOUNT ON added to prevent extra result sets from    
 -- interfering with SELECT statements.    
 SET NOCOUNT ON;    
    
    -- Insert statements for procedure here    
 SELECT Boxid AS DeviceAddress,Latitude,Longitude,Heading,Speed,CONVERT(VARCHAR(23), OriginDateTime , 126)AS "Time"    
 FROM  rvlfMsgInHst WHERE OriginDateTime BETWEEN @FromDate AND @ToDate   
 AND  Latitude != 0.000000 AND Longitude != 0.000000  
 ORDER BY OriginDateTime ASC  
     
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_SP_GetLeaseSummary]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_SP_GetLeaseSummary]                
@intVendorId varchar(max) = null,
@intFleetId varchar(max) = null,         
@intVehicleId varchar(max) = null,            
@bigOrganizationID bigint =null,            
@intUserid bigint = null     
AS            
/******************************************************************************/            
-- Name  : rvlf_SP_GetLeaseSummary null,null,null,6,140        
-- Description : Getting Student History            
-- Author  : N.Ranjith  
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--    : 12-Sep-2014            
/******************************************************************************/       
BEGIN                 
 SET NOCOUNT ON;     
 DECLARE @HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                              
  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit,@Lang varchar(50),  @LangSetting varchar(20)                                 
                                 
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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')                                     
  FROM rvlfUserPreferences up                               
   INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                               
  WHERE up.UserId = @intUserid                                                              

IF OBJECT_ID ('tempdb.dbo.#tblVehicleLease') IS NOT NULL
drop table #tblVehicleLease

Create table #tblVehicleLease
  ( 
   VehicleID bigint,
   VehicleName varchar(max),
  VendorName varchar(max),
  VendorAddress varchar(max),
  ContractFrom datetime,
  ContractTo datetime,
  TotalDistance bigint,
  TotalRunningHrs bigint,
  TotalBalanceDistance bigint,
  TotalBalanceRunningHrs bigint,
  ContractStatus int,
  ExpNotificationType int,  
  ExpNotificationTypeName varchar(100),  
  ExpNotificationCurrent int,
  ExpNotification1 bigint,
  ExpNotification2 bigint,
  VendorVehicleSettingsId bigint
  
  ) 
insert into #tblVehicleLease     
select Distinct V.VehicleId,V.VehicleDescription, TVM.VendorName,(TVM.VendorAddress +','+ TVM.VendorCity +', Contact:'+ TVM.ContactNo + +', Email:'+ TVM.Email) as VendorAddress,
VVS.ContractFrom,VVS.ContractTo,
VVS.MonthlyRunningDistance as TotalDistance,VVS.MonthlyEngineHrs as TotalRunningHrs,0 as TotalBalanceDistance,0 as TotalBalanceRunningHrs,
(case when VVS.ContractTo <= getutcdate() then 1 else 0 end), VVS.ExpNotificationType,
(Case when VVS.ExpNotificationType = 1 then 'Distance' else 'RunningHrs' end),0,VVS.ExpNotification1 ,VVS.ExpNotification2,VVS.VendorVehicleSettingsId

			from rvlfVendorVehicleSettings VVS 
			inner join rvlfVendorVehicles VV on VV.VendorVehicleAssignId  = VVS.VendorVehicleAssignId
			inner join rvlfVehicle V on v.VehicleId = VV.VehicleId
			inner join rvlfFleetVehicles FV on FV.VehicleId = VV.VehicleId
			inner join rvlfTyreVendorMaster TVM on TVM.VendorId = VV.VendorId
			inner join rvlfVehicleAssignment VA on VA.VehicleId =V.VehicleId			
	       where (@intFleetId IS NULL OR @intFleetId='' OR @intFleetId=0 OR FV.FleetId = @intFleetId) and
		         (@intVendorId IS NULL OR @intVendorId='' OR @intVendorId=0 OR VV.VendorId = @intVendorId) and
				 (@intVehicleID IS NULL OR @intVehicleID='' OR @intVehicleID=0 OR VV.VehicleId = @intVehicleID) and
				  (TVM.VendorType like 'LMV' or TVM.VendorType like 'LMC') and VV.IsActive = 1 and
				 v.OrganizationId = @bigOrganizationID 

   
   DECLARE @VCintVehicleID bigint =(SELECT MIN(VehicleID) FROM #tblVehicleLease)    
      
   WHILE @VCintVehicleID IS NOT NULL    
   BEGIN
   
   Declare @VCTotalBalanceDistance bigint = 0,@VCTotalBalanceRunningHrs bigint =0
  

   select @VCTotalBalanceDistance = (MAX(isnull(h.odometer,0)) - Min(isnull(h.odometer,0))),
			@VCTotalBalanceRunningHrs = (MAX(isnull(h.duration,0)) - Min(isnull(h.duration,0)))
			from rvlfVendorVehicleSettings VVS 
			inner join rvlfVendorVehicles VV on VV.VendorVehicleAssignId  = VVS.VendorVehicleAssignId
			inner join rvlfVehicle V on v.VehicleId = VV.VehicleId				
			inner join rvlfTyreVendorMaster TVM on TVM.VendorId = VV.VendorId
			inner join rvlfVehicleAssignment VA on VA.VehicleId =V.VehicleId
			inner join rvlfMsgInHst h on h.BoxId = VA.BoxId
	       where  (VV.VehicleId = @VCintVehicleID) and month(h.OriginDateTime) = month(getutcdate()) --and h.BoxMsgInTypeId = 2
		   group by H.odometer,VVS.MonthlyRunningDistance,H.duration,VVS.MonthlyEngineHrs

   --select @VCTotalBalanceRunningHrs = (VVS.MonthlyEngineHrs - ((MAX(h.duration) - Min(h.duration))))
			--from rvlfVendorVehicleSettings VVS 
			--inner join rvlfVendorVehicles VV on VV.VendorVehicleAssignId  = VVS.VendorVehicleAssignId
			--inner join rvlfVehicle V on v.VehicleId = VV.VehicleId				
			--inner join rvlfTyreVendorMaster TVM on TVM.VendorId = VV.VendorId
			--inner join rvlfVehicleAssignment VA on VA.VehicleId =V.VehicleId
			--inner join rvlfMsgInHst h on h.BoxId = VA.BoxId
	  --     where  (VV.VehicleId = @VCintVehicleID) and h.OriginDateTime between VVS.ContractFrom and VVS.ContractTo
		 --  group by H.duration,VVS.MonthlyEngineHrs
		
        update #tblVehicleLease set TotalBalanceDistance = (TotalDistance- @VCTotalBalanceDistance),
		TotalBalanceRunningHrs = (TotalRunningHrs- @VCTotalBalanceRunningHrs),
		ExpNotificationCurrent = cast((case when ExpNotificationType = 1 then (@VCTotalBalanceDistance/TotalDistance)/100
									   when ExpNotificationType = 2 then (@VCTotalBalanceRunningHrs/TotalRunningHrs)/100 else 0 end) as bigint)
		--ExpNotificationCurrent = 86
		where VehicleID = @VCintVehicleID    
   
    select @VCintVehicleID = MIN(VehicleID) from #tblVehicleLease where VehicleID > @VCintVehicleID              
  End  
  
	Select  VehicleID,VendorVehicleSettingsId,VehicleName ,VendorName ,VendorAddress ,convert(varchar(50),ContractFrom,106) as  ContractFrom, convert(varchar(50),ContractTo,106) as  ContractTo,TotalDistance , TotalRunningHrs ,isnull(TotalBalanceDistance,0) as TotalBalanceDistance ,

	isnull(TotalBalanceRunningHrs,0) as TotalBalanceRunningHrs, ContractStatus ,  ExpNotificationType ,ExpNotificationTypeName ,   ExpNotificationCurrent , ExpNotification1 , ExpNotification2  from #tblVehicleLease

   
 SET NOCOUNT OFF;     
   
End 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLogInPreferences]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author:  Vijay.N  
-- Create date: 3-Mar-2012  
-- Description: Load all the preferences while Loging In.  
-- EXEC rvlf_sp_GetLogInPreferences 421,'watxppu5tqo1lx454amjaw55'  
-- =============================================  
CREATE PROCEDURE [dbo].[rvlf_sp_GetLogInPreferences]   
 -- Add the parameters for the stored procedure here  
 @UserId BIGINT,  
 @SessionId NVARCHAR(500)  
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
 EXEC [DBO].[rvlf_sp_GetLoginUserDetails] @SessionId   
 EXEC [DBO].[rvlt_sp_AddEditViewUserPreferences] 'View',@UserId  
 SET NOCOUNT OFF;  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLoginUserDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetLoginUserDetails]           
/***********************************************************************************************************          
Stored Procedure Name : rvlf_sp_GetLoginUserDetails    
Purpose     : To Retrieve the Login User Details    
Created by    : Kumuthini. L    
Created date   : 15-Oct-09    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 31-Dec-2009 MJJC Included the retrieval of the user preferences.    
--    : 31-Jan-2009 MJJC Included the retrieval of the user group details.    
--    : 13-Mar-2010 MJJC Included the hours & mins to be added based on Organization country    
--    : 07-Apr-2010 MJJC Included the hours & mins to be added based on the User Pref too for email report    
--   : 20-Sep-2010 SJ inluded TimeZoneID and Distance  
--   : 25-Oct-2013 Sakthi Include Currency format For ROI  
************************************************************************************************************/   
@SessionId  nvarchar(500) = NULL  
AS          
BEGIN    
    
 DECLARE @AssignedFleetCount AS INT = 0    
    
 SELECT @AssignedFleetCount = COUNT(*) FROM rvlfUserLoginDetails UL     
 INNER JOIN rvlfFleetUsers FU ON FU.UserId = UL.UserId    
 WHERE UL.SessionId = @SessionId    
    
 IF EXISTS(SELECT UL.SessionId FROM rvlfUserLoginDetails UL    
  INNER JOIN rvlfUserGroupAssignment UGA ON UGA.UserId = UL.UserId    
  INNER JOIN rvlfUserGroup UG ON UG.UserGroupId = UGA.UserGroupId    
  WHERE UG.UserGroupName = 'Angler Admin' AND UL.SessionId = @SessionId)    
 BEGIN     
  SET @AssignedFleetCount = 1    
 END     
    
 SELECT UL.*, U.OrganizationId, UG.UserGroupId,     
  G.UserGroupName, G.IsDefaultUserGroup,    
  org.EnforcePasswordPolicy, org.PwdMinCharacters,     
  p.Distance, @AssignedFleetCount AS 'AssignedFleetCount',    
  z.HoursToBeAdded as HoursToBeAdded, z.MinToBeAdded as MinsToBeAdded,z.TimezoneId, z.TimeZoneDesc,   
  pt.HoursToBeAdded as UserPrefHoursToBeAdded, pt.MinToBeAdded as UserPrefMinsToBeAdded,    
  org.OrganizationName, org.OrgDistance 'Distance',p.Fuel,ct.CurrencyName,org.CountryID ,t.TitleName as TitleName ,u.CustomerID,c.CustomerName
 FROM rvlfUserLoginDetails UL    
 INNER JOIN rvlfUserGroupAssignment UG ON UG.UserId = UL.UserId    
 INNER JOIN rvlfUserGroup G ON UG.UserGroupId = G.UserGroupId    
 INNER JOIN rvlfOrganization org ON org.OrganizationId = UL.OrgId    
 INNER JOIN rvlfCurrencyType ct ON ct.CurrencyTypeId=org.CurrencyTypeId  
 INNER JOIN rvlfUser U ON U.UserId = UL.UserId    
 Inner join rvlfTitle T on t.TitleId=u.TitleId
 LEFT OUTER JOIN rvlfUserPreferences p ON UL.UserId = p.UserId
 left outer join rvlfCustomers c on c.CustomerId=u.CustomerID    
 INNER JOIN rvlfTimeZones pt ON p.TimezoneId = pt.TimeZoneID    
 INNER JOIN rvlfTimeZones z ON org.CountryId = z.TimeZoneID    
 WHERE UL.SessionId = @SessionId    
    
END 



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetLogoOption]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetLogoOption]
	@bigOrganizationID BIGINT=NULL
AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetLogoOption
--	Description	:	To get the Logo Option
--	Author		:	S.Jeyanthi
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	18-Sep-2010 SJ	Created Intial Version 
/******************************************************************************/
BEGIN
	IF(@bigOrganizationID Is NULL)
		BEGIN
			SELECT * FROM rvlfOrganizationLogoOption 				
		END
	ELSE
		BEGIN
			SELECT O.LogoOptionId,L.LogoOptionName FROM rvlfOrganizationLogoOption O
			Join rvlfLogoOption L on L.LogoOptionID=O.LogoOptionID
			Where O.OrganizationID=@bigOrganizationID
			
		END
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMaintenanceCost]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetMaintenanceCost]    
 @bigOrganizationID bigint = NULL,    
 @bigFleetId bigint = NULL,    
 @intBoxId varchar(max) = NULL,    
 @bigVehicleId bigint = NULL,    
 @dtStartDate DateTime = NULL,    
 @dtEndDate DateTime = NULL,     
 @bigPlanId bigint = NULL,    
 @intServiceType int = NULL,    
 @intServiceID int = NULL,    
 @tiMaintenanceType tinyint = NULL,    
 @intServicedBy int = NULL,     
 @bigQueryingUser bigint = NULL    
AS       
/**************************************************************************************/    
-- Name  : rvlf_sp_GetMaintenanceCost 6,8,NULL,null,'2010-10-01 08:00:00','2011-12-04 20:00:00',null,Null,NULL,NULL,17    
-- Description : To get the vehicles that were nearing to the maintenance    
-- Author  : Jeyanthi. S    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 12-Oct-2010  Jeyanthi Created Intial Version     
--              :   11-Feb-2011  Kumuthini  Fine tunings done based on the latest logic   
--    : 10-Aug-2011 Ranjith Date format Included     
/**************************************************************************************/    
BEGIN    
SET NOCOUNT ON     
  Declare @dtFDate datetime =@dtStartDate  
 Declare @dtEDate datetime =@dtEndDate  
     
 DECLARE @Distance varchar(20)    
 DECLARE @ConversionFactor numeric (10,2) = 1.0    
  DECLARE @DefaultDateFormat INT = 0  
    DECLARE @HoursToBeAdded INT = 0    
 DECLARE @MinsToBeAdded INT = 0   
   
    SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,    
     @Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END,  
      @HoursToBeAdded = tz.HoursToBeAdded, @MinsToBeAdded = tz.MinToBeAdded ,  
     @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 = @bigQueryingUser    
     
 CREATE TABLE #tempServiceHistory(VehicleId bigint,VehicleDescription nvarchar(20),Vin nvarchar(20),LicensePlate nvarchar(20),    
     PlanId bigint,PlanName nvarchar(50),ServiceType nvarchar(20),ServiceId bigint,ServiceName nvarchar(50),     
     ServiceCost Decimal(9,2),ServicedOn DateTime, PlannedCost Decimal(9,2), [Type] nvarchar(8))    
     
 INSERT INTO #tempServiceHistory    
 SELECT v.VehicleId, VehicleDescription, Vin, LicensePlate, mp.PlanId, mp.PlanName,    
  (CASE WHEN vm.ServiceType = 0 THEN 'Engine Hours' WHEN vm.ServiceType = 1 THEN 'Odometer' WHEN vm.ServiceType = 2 THEN 'Time Based' END) ServiceType,     
   MSD.ServiceId,ServiceName,MSD.ServiceCost,MSD.ServicedOn, mps.PlannedCost, 'Planned'     
  FROM rvlfVehicleMaintenanceService VM    
   INNER JOIN rvlfMaintenanceServiceDetails MSD on MSD.ServiceDetailsId = VM.ServiceDetailsId     
   INNER JOIN rvlfMaintenanceService MS ON MS.ServiceId = MSD.ServiceId      
   INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId    
   INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId    
   INNER JOIN rvlfMaintenancePlanServices mps ON mps.PlanId = mp.PlanId AND mps.ServiceId = MSD.ServiceId      
   INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId    
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId    
   INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId = v.VehicleId    
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = VM.PlanDetailsId     
  WHERE mp.OrganizationId = @bigOrganizationID AND       
      CONVERT(DATE, vm.ExecutedOn, 101) BETWEEN CONVERT(DATE, @dtStartDate, 101) AND CONVERT(DATE, @dtEndDate, 101)    
   AND (@bigFleetId IS NULL OR @bigFleetId='' OR @bigFleetId = 0 OR fv.FleetId = @bigFleetId)    
   AND (@intBoxId IS NULL OR @intBoxId='' OR  VA.BoxId in(select * from rvlf_fn_ConvertArrayToTable(@intBoxId,',')))    
   AND (@bigPlanId IS NULL OR @bigPlanId='' OR @bigPlanId = 0 OR vp.PlanId = @bigPlanId)    
   AND (@intServiceType IS NULL OR @intServiceType='' OR VM.ServiceType = @intServiceType)    
   AND (@intServiceID IS NULL OR @intServiceID='' OR @intServiceID = 0 OR MSD.ServiceId = @intServiceID)    
   AND (@tiMaintenanceType IS NULL OR @tiMaintenanceType='' OR @tiMaintenanceType = 0 OR @tiMaintenanceType = 1)    
       
 UNION    
     
 SELECT v.VehicleId, v.VehicleDescription, Vin, LicensePlate, 0 AS PlanId, 'N/A' AS PlanName,    
 'N/A' AS ServiceType, ads.ServiceId, ms.ServiceName, ads.ServiceCost, ad.ExecutionOn, 0 AS PlannedCost, 'Adhoc'  
    
 FROM rvlfAdhocServices ad    
 INNER JOIN rvlfAdhocServiceDetails ads ON ads.AdhocServiceId = ad.AdhocServiceId    
 INNER JOIN rvlfMaintenanceService ms ON ms.ServiceId = ads.ServiceId      
 INNER JOIN rvlfVehicle v ON v.VehicleId = ad.VehicleId    
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId    
 INNER JOIN rvlfVehicleAssignment va ON va.VehicleId = v.VehicleId    
 WHERE v.OrganizationId = @bigOrganizationID AND     
 CONVERT(DATE, ad.ExecutionOn, 101) BETWEEN CONVERT(DATE, @dtStartDate, 101) AND CONVERT(DATE, @dtEndDate, 101)    
 AND (@bigFleetId IS NULL OR @bigFleetId='' OR @bigFleetId = 0 OR fv.FleetId = @bigFleetId)    
 AND ((@intBoxId IS NULL) OR (@intBoxId='') OR (VA.BoxId in(select * from rvlf_fn_ConvertArrayToTable(@intBoxId,',')))) AND (@bigPlanId IS NULL OR @bigPlanId='' OR 0 = @bigPlanId)    
 AND @intServiceType IS NULL AND (@intServiceID IS NULL OR @intServiceID='' OR @intServiceID = 0 OR ads.ServiceId = @intServiceID)    
 AND (@tiMaintenanceType IS NULL OR @tiMaintenanceType='' OR @tiMaintenanceType = 0 OR @tiMaintenanceType = 2)    
       
    ALTER TABLE #tempServiceHistory ADD NoOfPlannedServices int, TotPlannedCost numeric(18, 2), TotalServiceCost numeric(18, 2),     
        CostDeviation int, NoOfAdhocServices int, TotalAdhocServiceCost numeric(18, 2), AdhocCostDeviation int,    
  NoOfServices int, TotCostIncurred numeric(18, 2)    
     
 UPDATE sh SET sh.NoOfPlannedServices = (SELECT COUNT([Type]) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId AND sh1.Type = 'Planned'),    
  sh.TotPlannedCost = ISNULL((SELECT SUM(sh1.PlannedCost) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId AND sh1.Type = 'Planned'), 0),    
  sh.TotalServiceCost = ISNULL((SELECT SUM(sh1.ServiceCost) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId AND sh1.Type = 'Planned'), 0),    
  sh.NoOfAdhocServices = (SELECT COUNT([Type]) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId AND sh1.Type = 'Adhoc'),    
  sh.TotalAdhocServiceCost = ISNULL((SELECT SUM(sh1.ServiceCost) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId AND sh1.Type = 'Adhoc'), 0)    
 FROM #tempServiceHistory sh    
     
 UPDATE #tempServiceHistory SET NoOfServices = NoOfPlannedServices + NoOfAdhocServices, TotCostIncurred = TotalServiceCost + TotalAdhocServiceCost,    
     CostDeviation = (CASE WHEN TotPlannedCost = 0 THEN 0 ELSE (((TotalServiceCost - TotPlannedCost) * 100) / TotPlannedCost) END),    
  AdhocCostDeviation = (CASE WHEN NoOfAdhocServices > 0 THEN 100 ELSE 0 END)    
      
 DECLARE @PlannedCostSummary numeric(18, 2)    
 DECLARE @ActualCostSummary numeric(18, 2)    
 DECLARE @CostDeviationSummary int    
     
 SET @PlannedCostSummary = (SELECT SUM(PlannedCost) FROM #tempServiceHistory)    
 SET @ActualCostSummary = (SELECT SUM(ServiceCost) FROM #tempServiceHistory)    
 SET @CostDeviationSummary = (CASE WHEN @tiMaintenanceType = 2 THEN 100    
   WHEN @PlannedCostSummary = 0 THEN 0 ELSE (((@ActualCostSummary - @PlannedCostSummary) * 100) / @PlannedCostSummary) END)    
     
 SELECT sh.VehicleId, sh.VehicleDescription, sh.Vin, sh.LicensePlate, sh.PlanId, sh.PlanName, sh.ServiceType,     
 sh.ServiceId, sh.ServiceName, sh.ServiceCost, Convert(varchar,sh.ServicedOn,@DefaultDateFormat)  as ServicedOn,    
    CASE WHEN sh.[Type] = 'Adhoc' THEN 'N/A' ELSE CONVERT(VARCHAR(25), sh.PlannedCost) END AS PlannedCost,    
    sh.[Type], sh.NoOfPlannedServices, sh.TotPlannedCost, sh.TotalServiceCost, sh.CostDeviation,     
    sh.NoOfAdhocServices, sh.TotalAdhocServiceCost, sh.AdhocCostDeviation, sh.NoOfServices, sh.TotCostIncurred,    
    CONVERT(INT,(CASE WHEN @tiMaintenanceType = 2 THEN 100 WHEN sh.TotPlannedCost = 0 THEN 0     
  ELSE (((TotCostIncurred - sh.TotPlannedCost) * 100) / sh.TotPlannedCost) END)) AS TotCostDeviation,    
    @PlannedCostSummary AS PlannedCostSummary, @ActualCostSummary AS ActualCostSummary, @CostDeviationSummary AS CostDeviationSummary,    
    (@PlannedCostSummary - @ActualCostSummary) AS CostSavings ,  
    Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,  
    PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())  
    --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate     
    FROM #tempServiceHistory sh     
    ORDER BY CONVERT(DATE, sh.ServicedOn)    
        
    SELECT VehicleId, VehicleDescription, SUM(ServiceCost) AS ServiceCost FROM #tempServiceHistory     
    GROUP BY VehicleId, VehicleDescription     
        
    SELECT VehicleId, ServiceName, SUM(ServiceCost) AS ServiceCost FROM #tempServiceHistory    
    GROUP BY VehicleId, ServiceName    
        
   DROP TABLE #tempServiceHistory    
        
SET NOCOUNT OFF    
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMaintenanceNotifications]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetMaintenanceNotifications]
AS
/**************************************************************************************/
--	Name		:	[rvlf_sp_GetMaintenanceNotifications]
--	Description	:	To get the maintenance service details for notifications
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	22-Jun-2010		Created Intial Version 
/**************************************************************************************/
BEGIN
SET NOCOUNT ON 

	IF NOT EXISTS (SELECT NotificationType FROM rvlfFailSafeNotification WHERE NotificationType = 3)
	BEGIN
		
		INSERT INTO rvlfFailSafeNotification (NotificationType, NotificationDate, IsNotificationSent)
		VALUES (3, GETUTCDATE(), 0)
		
	END
    
    IF EXISTS (SELECT NotificationType FROM rvlfFailSafeNotification WHERE NotificationType = 3) --AND NotificationDate = CONVERT(DATE, GETUTCDATE()))
	BEGIN
	  
	    UPDATE rvlfFailSafeNotification SET NotificationDate = DATEADD(DD, 1, GETUTCDATE()) WHERE NotificationType = 3
		
		EXEC rvlf_sp_UpdateVehicleNearingPercentage
		
		SELECT DISTINCT u.UserId, u.DisplayName, u.Email, dbo.rvlf_fn_GetUserServiceNotifications(u.UserId) AS Notifications,
		'VXL | Maintenance Notification' AS [Subject],dbo.rvlf_fn_GetUserServicePushNotifications(u.UserId) as PushNotifications,u.DevOS,u.DevRegID,isnull(u.IsPushNotfication,0) as IsPushNotfication
		FROM rvlfVehicleMaintenanceService vm
		INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId
		INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId
		INNER JOIN rvlfNotificationList nl ON nl.TypeID = vp.PlanId
		INNER JOIN rvlfUser u ON u.UserId = nl.UserID
		inner join rvlforganization o on u.organizationid=o.organizationid
		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 ExpiresOn>getdate()

		
		declare @NotificationList table(UserID bigint,NotificationType tinyint,TypeID bigint,Email bit,SMS bit,CreateDateTime datetime)
		;WITH x AS 
		(
			SELECT UserID, NotificationType, TypeID,Email,SMS,CreateDatetime, rn = ROW_NUMBER() OVER
				(PARTITION BY NotificationType, TypeID ORDER BY UserID) 
			FROM dbo.rvlfNotificationList
		)
		insert into @NotificationList
		SELECT  UserID, NotificationType, TypeID,Email,SMS,CreateDatetime FROM x WHERE rn = 1 order by CreateDateTime desc
		
		declare @Date datetime
		set @Date=GETUTCDATE()

		SELECT DISTINCT u.UserId, u.DisplayName, u.Email,dbo.rvlf_fn_GetUserServiceComment(u.UserId,D.BoxId,@Date) as 'Comments',d.BoxId
		FROM rvlfVehicleMaintenanceService vm
		INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId
		INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId
		INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId
		inner join rvlfMAKDevices D on  D.VehicleId=v.VehicleId
		INNER JOIN @NotificationList nl ON nl.TypeID = vp.PlanId
		INNER JOIN rvlfUser u ON u.UserId = nl.UserID
		inner join rvlforganization o on u.organizationid=o.organizationid
		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 ExpiresOn>getdate()

		-------Update Previouse sent comments----
		declare @tblvehicle table(id int identity(1,1),SequenceNum bigint)
		
		insert into @tblvehicle
		SELECT DISTINCT vm.VehiclePlanId
		FROM rvlfVehicleMaintenanceService vm
		INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId
		INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId
		INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId
		inner join rvlfMAKDevices D on  D.VehicleId=v.VehicleId
		INNER JOIN @NotificationList nl ON nl.TypeID = vp.PlanId
		INNER JOIN rvlfUser u ON u.UserId = nl.UserID
		inner join rvlforganization o on u.organizationid=o.organizationid
		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 ExpiresOn>getdate()

		declare @TotalLoop int=1
		declare @Loopid int=1,@sequnNumber bigint
		select @TotalLoop=count(*) from @tblvehicle
		while(@TotalLoop>=@Loopid)
		begin
			select @sequnNumber=SequenceNum from @tblvehicle where id=@Loopid
			update rvlfMsgOutHst set isCommentSentStatus=2,isCommentSentUpdateDate=getdate() where SequenceNum=@sequnNumber
			Select @Loopid=@Loopid+1
			--Status
			--1 Need to sent comment(The comment reached 8 hours and above and the status is 1 then the mail send to the client and update the status to 3)
			--2 Comment Expiry No need to send the mail(becuase then msg will be update in other comments)
			--3 Comment Expiry mail also sent(Completed)
			--4 The comment sent to the device status is successfully.
		end

		--------END--------------------------


		insert into rvlfMsgOutHst(BoxId,SentDateTime,UserId,Priority,ServiceId,BoxCmdOutTypeId,BoxProtocolTypeId,CommInfo1,CommInfo2,CustomProp,SequenceNum,Acknowledged,MessageInID,Scheduled,ScheduleId,isCommentSentStatus,isCommentSentUpdateDate)
		SELECT DISTINCT D.BoxId,@Date SentDateTime,u.UserId,0 'Priority',1 ServiceId,43 BoxCmdOutTypeId,1 BoxProtocolTypeId,0 CommInfo1,0 CommInfo2,
		'#' + 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|' CustomProp,vm.VehiclePlanId as 'SequenceNum',null Acknowledged,null MessageInID,0 Scheduled,null ScheduleId
      WHEN (vm.NearingPercentage >= 100) THEN '3' ELSE '3' END) as varchar) + '|' + mp.PlanName + '|**|END|' CustomProp,vm.VehiclePlanId as 'SequenceNum',null Acknowledged,null MessageInID,0 Scheduled,null ScheduleId,1,getdate()
		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 @NotificationList 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  group by D.BoxId,u.UserId,vm.RunningSerial,vm.NearingPercentage,pd.Notification2,pd.Notification1,pd.Notification3,vm.ServiceType,VM.VehiclePlanId,mp.PlanName

		

		--Get Un-Success comment details and sent again
			Select *,CustomProp as Comments from rvlfMsgOutHst where BoxCmdOutTypeId=43 and SentDateTime between (DATEADD(hour,-1,GETUTCDATE())) and GETUTCDATE() and Acknowledged is null and isCommentSentStatus=1
			and (isnull(TriggerCount,0)<3 or BoxId in (Select distinct BoxId from rvlfMsgInHst where OriginDateTime between dateadd(HOUR,-1,GETUTCDATE()) and GETUTCDATE())) 

			update rvlfMsgOutHst set TriggerCount=isnull(Triggercount,0)+ 1 where BoxCmdOutTypeId=43 and SentDateTime between (DATEADD(hour,-1,GETUTCDATE())) and GETUTCDATE() and Acknowledged is null and isCommentSentStatus=1
			and (isnull(TriggerCount,0)<3 or BoxId in (Select distinct BoxId from rvlfMsgInHst where OriginDateTime between dateadd(HOUR,-1,GETUTCDATE()) and GETUTCDATE()))
		--End

		--Get the User list for send un-success comment to the mapped users
			Select ms.BoxId,ms.CustomProp,nl.Email,nl.SMS,nl.TypeID,u.UserId,u.UserName,nl.Email as EmailID,u.MobileNo,'<b>Dear ' + u.DisplayName + '</b>,<br><br> The below mentioned nearing maintenance command sending failed to device. Kindly noted the same. <br><br> <b>Device name: </b> ' + D.EquipmentName + '<br><br> <b>Command Message:</b> ' + ms.CustomProp +'<br><br><br><br><br><br><br><br><br><br><br><br><br><b>Best Regards,</b><br>VXL<br><br><br><br><br><br><br><br>This is system generated mail' as StrMessage from rvlfMsgOutHst ms
			inner join rvlfVehicleMaintenanceService vm on ms.SequenceNum=vm.VehiclePlanId
			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 @NotificationList nl ON nl.TypeID = vp.PlanId    
			INNER JOIN rvlfUser u ON u.UserId = nl.UserID    
			where BoxCmdOutTypeId=43 and SentDateTime between (DATEADD(hour,-1,DATEADD(MINUTE,-30,GETUTCDATE()))) and (DATEADD(hour,-1,GETUTCDATE())) and Acknowledged is null and isCommentSentStatus=1
		--End

		--Update the un-success comment status
			update rvlfMsgOutHst set isCommentSentStatus=3,isCommentSentUpdateDate=GETUTCDATE() where BoxCmdOutTypeId=43 and isCommentSentStatus=1 and
			SentDateTime in (Select SentDateTime from rvlfMsgOutHst where BoxCmdOutTypeId=43 and SentDateTime between (DATEADD(hour,-1,DATEADD(MINUTE,-30,GETUTCDATE()))) and (DATEADD(hour,-1,GETUTCDATE())) and Acknowledged is null and isCommentSentStatus=1)
		--End

		--Select * from rvlfMsgOutHst where BoxCmdOutTypeId=43 and SentDateTime between (DATEADD(hour,-9,getdate())) and (DATEADD(hour,-8,getdate())) and Acknowledged is null
		--update VM set
		--VM.IsNearing=0
		--FROM rvlfVehicleMaintenanceService vm
		--INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId
		--INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId
		--INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId
		--inner join rvlfMAKDevices D on  D.VehicleId=v.VehicleId
		--INNER JOIN @NotificationList nl ON nl.TypeID = vp.PlanId
		--INNER JOIN rvlfUser u ON u.UserId = nl.UserID
		--inner join rvlforganization o on u.organizationid=o.organizationid
		--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 ExpiresOn>getdate() 

	END
	ELSE
	BEGIN
	    
		SELECT NULL AS UserId, NULL AS DisplayName, NULL AS Email, NULL AS Notifications, NULL AS [Subject]
	    
		SELECT null UserId, null DisplayName, null Email,null as 'Comments',null BoxId


	END

SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMaintenancePlanDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE Procedure [dbo].[rvlf_sp_GetMaintenancePlanDetails]  
 @chrType char(1) = NULL,  
 @bigPlanId bigint = NULL,  
 @bigOrganizationId bigint,  
 @bigQueryingUser bigint = 0  
AS  
/**************************************************************************************/  
-- Name  : rvlf_sp_GetMaintenancePlanDetails   
-- Description : To get the maintenance plan details  
-- Author  : Kumuthini. L  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 10-Jun-2010  Kumuthini Created Intial Version   
--                  25-Jun-2010  Kumuthini  Included the User Preferences for Odometer Reading Service Interval  
/**************************************************************************************/  
BEGIN  
SET NOCOUNT ON   
    
 IF @chrType = 'A' OR @chrType = 'P'  
 BEGIN  
   
  DECLARE @Distance varchar(20)  
  DECLARE @ConversionFactor numeric (10,2) = 1.0  
  SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,  
      @Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END  
  FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz  
  ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser  
    
 END  
    
 IF @chrType = 'A'  
 BEGIN  
      
  SELECT M.PlanId, M.PlanName, CASE WHEN M.PlanDescription ='' THEN '-' ELSE M.PlanDescription END AS PlanDescription, M.TotalPlannedCost,  
  CASE WHEN EXISTS(SELECT ms.PlanDetailsId FROM rvlfVehicleMaintenanceService ms   
     INNER JOIN rvlfVehiclePlanAssignment va ON va.VehiclePlanId = ms.VehiclePlanId  
     WHERE va.PlanId = M.PlanId)  
  THEN 1 ELSE 0 END AssignedStatus,  
  ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 1,1,0),'') as EmailList,   
  ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 0,1,0),'') as SMSList,  
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 1,0,1),'-'),',',', ') as EmailUserNameList,      
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 0,0,1),'-'),',',', ') as SMSUserNameList 
  FROM rvlfMaintenancePlan M  
  WHERE M.OrganizationId = @bigOrganizationId AND (@bigPlanId IS NULL OR @bigPlanId = '' OR M.PlanId = @bigPlanId)  
  ORDER BY M.PlanName  
    
 END  
 ELSE IF @chrType = 'P'  
 BEGIN  
   
  SELECT M.PlanId, M.PlanName, M.PlanDescription, M.RecurringService, M.OverdueReminder, M.TotalPlannedCost,  isnull(M.VAT,0) as VAT,  
  CASE WHEN EXISTS(SELECT ms.PlanDetailsId FROM rvlfVehicleMaintenanceService ms   
      INNER JOIN rvlfVehiclePlanAssignment va ON va.VehiclePlanId = ms.VehiclePlanId  
      WHERE va.PlanId = M.PlanId)  
  THEN 1 ELSE 0 END AssignedStatus,  
  ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 1,1,0),'') as EmailList,   
  ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 0,1,0),'') as SMSList,  
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 1,0,1),'-'),',',', ') as EmailUserNameList,      
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 0,0,1),'-'),',',', ') as SMSUserNameList,   
  dbo.rvlf_fn_GetMaintenanceServices(4, M.PlanId, NULL) AS ServiceIds, dbo.rvlf_fn_GetMaintenanceServices(5, M.PlanId, NULL) AS ServicesApplicable  
  FROM rvlfMaintenancePlan M  
  WHERE M.OrganizationId = @bigOrganizationId AND (@bigPlanId IS NULL OR @bigPlanId = '' OR M.PlanId = @bigPlanId) order by M.PlanName
    
  SELECT PlanDetailsId, mp.PlanId, ServiceType, CONVERT(BIGINT, CASE WHEN ServiceType = 1 THEN (ServiceInterval * @ConversionFactor) ELSE ServiceInterval END) AS ServiceInterval,   
  Frequency, CASE WHEN EXISTS(SELECT ms.PlanDetailsId FROM rvlfVehicleMaintenanceService ms WHERE ms.PlanDetailsId = rvlfMaintenancePlanDetails.PlanDetailsId)  
  THEN 1 ELSE 0 END AssignedStatus, @Distance AS DistanceUnits, Notification1, Notification2, Notification3   
  FROM rvlfMaintenancePlanDetails  
  INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = rvlfMaintenancePlanDetails.PlanId  
  WHERE mp.PlanId = ISNULL(@bigPlanId,0) order by ServiceType
    
  SELECT ms.ServiceId, ms.ServiceName, dbo.rvlf_fn_GetMaintenanceServiceCategories(ms.ServiceId) AS ServiceCategory, ps.PlannedCost   
  FROM rvlfMaintenanceService ms  
  LEFT OUTER JOIN rvlfMaintenancePlanServices ps ON ps.ServiceId = ms.ServiceId AND ps.PlanId = ISNULL(@bigPlanId,0)   
  WHERE ms.OrganizationId = @bigOrganizationId  order by ms.ServiceName
    
 END  
 ELSE  
 BEGIN  
   
  SELECT PlanId, PlanName FROM rvlfMaintenancePlan WHERE OrganizationId = @bigOrganizationId  order by PlanName
   
 END  
  
SET NOCOUNT OFF  
END  
  


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMaintenancePlanDetails_WO]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    
Create Procedure [dbo].[rvlf_sp_GetMaintenancePlanDetails_WO]    
 @chrType char(1) = NULL,    
 @bigPlanId bigint = NULL,    
 @bigOrganizationId bigint,    
 @bigQueryingUser bigint = 0    
AS    
/**************************************************************************************/    
-- Name  : rvlf_sp_GetMaintenancePlanDetails_WO     
-- Description : To get the maintenance plan details    
-- Author  : Ranjith. N    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 17-Nov-2015  Ranjith Created Intial Version     
/**************************************************************************************/    
BEGIN    
SET NOCOUNT ON     
      
 IF @chrType = 'A' OR @chrType = 'P'    
 BEGIN    
     
  DECLARE @Distance varchar(20)    
  DECLARE @ConversionFactor numeric (10,2) = 1.0    
  SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,    
      @Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END    
  FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz    
  ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser    
      
 END    
      
 IF @chrType = 'A'    
 BEGIN    
        
  SELECT M.PlanId, M.PlanName,CASE WHEN M.PlanDescription ='' THEN '-' ELSE M.PlanDescription END AS PlanDescription , M.TotalPlannedCost,    
  CASE WHEN EXISTS(SELECT ms.PlanDetailsId FROM rvlfVehicleMaintenanceService ms     
     INNER JOIN rvlfVehiclePlanAssignment va ON va.VehiclePlanId = ms.VehiclePlanId    
     WHERE va.PlanId = M.PlanId)    
  THEN 1 ELSE 0 END AssignedStatus,    
  ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 1,1,0),'') as EmailList,     
  ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 0,1,0),'') as SMSList,    
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 1,0,1),'-'),',',', ') as EmailUserNameList,    
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 0,0,1),'-'),',',', ') as SMSUserNameList    
  FROM rvlfMaintenancePlan M    
  WHERE M.OrganizationId = @bigOrganizationId AND (@bigPlanId IS NULL OR @bigPlanId = '' OR M.PlanId = @bigPlanId)    
  ORDER BY M.PlanName    
      
 END    
 ELSE IF @chrType = 'P'    
 BEGIN    
     
  SELECT M.PlanId, M.PlanName, M.PlanDescription, M.RecurringService, M.OverdueReminder, M.TotalPlannedCost,    
  CASE WHEN EXISTS(SELECT ms.PlanDetailsId FROM rvlfVehicleMaintenanceService ms     
      INNER JOIN rvlfVehiclePlanAssignment va ON va.VehiclePlanId = ms.VehiclePlanId    
      WHERE va.PlanId = M.PlanId)    
  THEN 1 ELSE 0 END AssignedStatus,    
  ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 1,1,0),'') as EmailList,     
  ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 0,1,0),'') as SMSList,    
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 1,0,1),'-'),',',', ') as EmailUserNameList,    
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 0,0,1),'-'),',',', ') as SMSUserNameList,    
  dbo.rvlf_fn_GetMaintenanceServices(4, M.PlanId, NULL) AS ServiceIds, dbo.rvlf_fn_GetMaintenanceServices(5, M.PlanId, NULL) AS ServicesApplicable    
  FROM rvlfMaintenancePlan M    
  WHERE M.OrganizationId = @bigOrganizationId AND (@bigPlanId IS NULL OR @bigPlanId = '' OR M.PlanId = @bigPlanId)     
      
  SELECT PlanDetailsId, mp.PlanId, ServiceType, CONVERT(BIGINT, CASE WHEN ServiceType = 1 THEN (ServiceInterval * @ConversionFactor) ELSE ServiceInterval END) AS ServiceInterval,     
  Frequency, CASE WHEN EXISTS(SELECT ms.PlanDetailsId FROM rvlfVehicleMaintenanceService ms WHERE ms.PlanDetailsId = rvlfMaintenancePlanDetails.PlanDetailsId)    
  THEN 1 ELSE 0 END AssignedStatus, @Distance AS DistanceUnits, Notification1, Notification2, Notification3     
  FROM rvlfMaintenancePlanDetails    
  INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = rvlfMaintenancePlanDetails.PlanId    
  WHERE mp.PlanId = ISNULL(@bigPlanId,0)     
      
  SELECT ms.ServiceId, ms.ServiceName, dbo.rvlf_fn_GetMaintenanceServiceCategories(ms.ServiceId) AS ServiceCategory, ps.PlannedCost     
  FROM rvlfMaintenanceService ms    
  LEFT OUTER JOIN rvlfMaintenancePlanServices ps ON ps.ServiceId = ms.ServiceId AND ps.PlanId = ISNULL(@bigPlanId,0)     
  WHERE ms.OrganizationId = @bigOrganizationId    
      
 END    
 ELSE    
 BEGIN    
     
  SELECT PlanId, PlanName FROM rvlfMaintenancePlan WHERE OrganizationId = @bigOrganizationId    
     
 END    
    
SET NOCOUNT OFF    
END    


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMaintenancePlanDetailsWO]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    
CREATE Procedure [dbo].[rvlf_sp_GetMaintenancePlanDetailsWO]    
 @chrType char(1) = NULL,    
 @bigPlanId bigint = NULL,    
 @bigOrganizationId bigint,    
 @bigQueryingUser bigint = 0    
AS    
/**************************************************************************************/    
-- Name  : rvlf_sp_GetMaintenancePlanDetailsWO     
-- Description : To get the maintenance plan details    
-- Author  : Ranjith. N    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 19-Jul-2015  Ranjith Created Intial Version     
/**************************************************************************************/    
BEGIN    
SET NOCOUNT ON     
      
 IF @chrType = 'A' OR @chrType = 'P'    
 BEGIN    
     
  DECLARE @Distance varchar(20)    
  DECLARE @ConversionFactor numeric (10,2) = 1.0    
  SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,    
      @Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END    
  FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz    
  ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser    
      
 END    
      
 IF @chrType = 'A'    
 BEGIN    
        
  SELECT M.PlanId, M.PlanName,CASE WHEN M.PlanDescription ='' THEN '-' ELSE M.PlanDescription END AS PlanDescription , M.TotalPlannedCost,    
  CASE WHEN EXISTS(SELECT ms.PlanDetailsId FROM rvlfVehicleMaintenanceService ms     
     INNER JOIN rvlfVehiclePlanAssignment va ON va.VehiclePlanId = ms.VehiclePlanId    
     WHERE va.PlanId = M.PlanId)    
  THEN 1 ELSE 0 END AssignedStatus,    
  ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 1,1,0),'') as EmailList,     
  ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 0,1,0),'') as SMSList,    
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 1,0,1),'-'),',',', ') as EmailUserNameList,    
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 0,0,1),'-'),',',', ') as SMSUserNameList , isnull(M.VAT,0) as VAT      
  FROM rvlfMaintenancePlan M    
  WHERE M.OrganizationId = @bigOrganizationId AND (@bigPlanId IS NULL OR @bigPlanId = '' OR M.PlanId = @bigPlanId)    
  ORDER BY M.PlanName    
      
 END    
 ELSE IF @chrType = 'P'    
 BEGIN    
     
  SELECT M.PlanId, M.PlanName, M.PlanDescription, M.RecurringService, M.OverdueReminder, M.TotalPlannedCost,    
  CASE WHEN EXISTS(SELECT ms.PlanDetailsId FROM rvlfVehicleMaintenanceService ms     
      INNER JOIN rvlfVehiclePlanAssignment va ON va.VehiclePlanId = ms.VehiclePlanId    
      WHERE va.PlanId = M.PlanId)    
  THEN 1 ELSE 0 END AssignedStatus,    
  ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 1,1,0),'') as EmailList,     
  ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 0,1,0),'') as SMSList,    
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 1,0,1),'-'),',',', ') as EmailUserNameList,    
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(8, M.PlanId, 0,0,1),'-'),',',', ') as SMSUserNameList,    
  dbo.rvlf_fn_GetMaintenanceServices(4, M.PlanId, NULL) AS ServiceIds, dbo.rvlf_fn_GetMaintenanceServices(5, M.PlanId, NULL) AS ServicesApplicable, isnull(M.VAT,0) as VAT     
  FROM rvlfMaintenancePlan M    
  WHERE M.OrganizationId = @bigOrganizationId AND (@bigPlanId IS NULL OR @bigPlanId = '' OR M.PlanId = @bigPlanId)     
      
  SELECT PlanDetailsId, mp.PlanId, ServiceType, CONVERT(BIGINT, CASE WHEN ServiceType = 1 THEN (ServiceInterval * @ConversionFactor) ELSE ServiceInterval END) AS ServiceInterval,     
  Frequency, CASE WHEN EXISTS(SELECT ms.PlanDetailsId FROM rvlfVehicleMaintenanceService ms WHERE ms.PlanDetailsId = rvlfMaintenancePlanDetails.PlanDetailsId)    
  THEN 1 ELSE 0 END AssignedStatus, @Distance AS DistanceUnits, Notification1, Notification2, Notification3, isnull(mp.VAT,0)as VAT     
  FROM rvlfMaintenancePlanDetails    
  INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = rvlfMaintenancePlanDetails.PlanId    
  WHERE mp.PlanId = ISNULL(@bigPlanId,0)  
      
  SELECT ms.ServiceId, ms.ServiceName, dbo.rvlf_fn_GetMaintenanceServiceCategories(ms.ServiceId) AS ServiceCategory, ps.PlannedCost     
  FROM rvlfMaintenanceService ms    
  LEFT OUTER JOIN rvlfMaintenancePlanServices ps ON ps.ServiceId = ms.ServiceId AND ps.PlanId = ISNULL(@bigPlanId,0)     
  WHERE ms.OrganizationId = @bigOrganizationId    
      
 END    
 ELSE    
 BEGIN    
     
  SELECT PlanId, PlanName FROM rvlfMaintenancePlan WHERE OrganizationId = @bigOrganizationId    
     
 END    
    
SET NOCOUNT OFF    
END    


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMaintenanceServiceDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE Procedure [dbo].[rvlf_sp_GetMaintenanceServiceDetails]  
 @bigServiceId bigint = NULL,  
 @bigOrganizationId bigint  
AS  
/**************************************************************************************/  
-- Name  : rvlf_sp_GetMaintenanceServiceDetails '',183 
-- Description : To get the maintenance service details  
-- Author  : Kumuthini. L  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 09-Jun-2010  Created Intial Version   
/**************************************************************************************/  
BEGIN  
SET NOCOUNT ON

    declare @chk int    
    set @chk = 0 
    IF EXISTS(select * from rvlfMaintenanceCategoryService where ServiceId = @bigServiceId)
    set @chk = 1
    IF EXISTS(select * from rvlfAdhocServiceDetails where ServiceId = @bigServiceId)
    set @chk = 1
      
    
 SELECT M.ServiceId, M.ServiceName, M.[Description],  
 --CASE WHEN EXISTS(SELECT MC.ServiceId FROM rvlfMaintenanceCategoryService MC WHERE MC.ServiceId = M.ServiceId)  
 --THEN 1 ELSE 0 END AssignedStatus,
 CASE WHEN EXISTS(SELECT MC.ServiceId FROM rvlfMaintenanceCategoryService MC WHERE MC.ServiceId = M.ServiceId)
 OR  EXISTS(SELECT AM.ServiceId FROM rvlfAdhocServiceDetails AM WHERE AM.ServiceId = M.ServiceId) 
 THEN 1 ELSE 0 END AssignedStatus,  
 
  --CASE WHEN @chk = 1 THEN 1 ELSE 0 END AssignedStatus,
  dbo.rvlf_fn_GetMaintenanceServiceCategories(M.ServiceId) AS ServiceCategory, NULL AS PlannedCost,  
 ISNULL(dbo.rvlf_fn_GetNotificationsList(7, M.ServiceId, 1,1,0),'') as EmailList,       
    ISNULL(dbo.rvlf_fn_GetNotificationsList(7, M.ServiceId, 0,1,0),'') as SMSList,      
    REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(7, M.ServiceId, 1,0,1),'-'),',',', ') as EmailUserNameList,      
    REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(7, M.ServiceId, 0,0,1),'-'),',',', ') as SMSUserNameList     
 FROM rvlfMaintenanceService M  
 WHERE M.OrganizationId = @bigOrganizationId AND   
 (@bigServiceId IS NULL OR @bigServiceId = '' OR M.ServiceId = @bigServiceId)  order by ServiceName
  
SET NOCOUNT OFF  
END  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMaintenanceServiceNotifications]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetMaintenanceServiceNotifications]
(
	@intBoxID INT,
	@vcBoxMsgInTypeName varchar(50) = null,
 	@vcCustomProp varchar(600)= null 
)
AS
/*****************************************************************************************************/
--	Name		:	[rvlf_sp_GetMaintenanceServiceNotifications]
--	Description	:	To set the current odometer readings & engine hours and get the maintenance 
--				:   service details for notifications
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	22-Jul-2010	Kumuthini. L	Created Intial Version
--              :   04-Nov-2010 Kumuthini. L    Fine tunings while taking current Engine Hours 
/****************************************************************************************************/
BEGIN
SET NOCOUNT ON 

 DECLARE @VehicleId AS BIGINT = 0
 
 -- Get the Vehicle Id for the equivalent Box Id
 SELECT @VehicleId = VehicleId FROM rvlfVehicleAssignment WHERE BoxId = @intBoxID
 
 IF EXISTS(SELECT vp.VehiclePlanId FROM rvlfVehiclePlanAssignment vp 
		   INNER JOIN rvlfVehicleMaintenanceService vm ON vm.VehiclePlanId = vp.VehiclePlanId
		   WHERE vp.VehicleId = @VehicleId AND vp.AssignedStatus = 1 AND 
		   (vm.ServiceType = 0 OR vm.ServiceType = 1) AND vm.Status = 0)
 BEGIN
	
	DECLARE @CurrentOdometerReading AS BIGINT = 0
	DECLARE @EngineHours AS BIGINT = 0
	
	-- If the message received is Sensor OFF with Duration i.e, Ignition OFF
	IF @vcBoxMsgInTypeName = 'Sensor Off with duration'
	BEGIN
		
		-- Get the current Odometer Reading from the Custom Property
		SET @CurrentOdometerReading = CAST(SUBSTRING(@vcCustomProp, CHARINDEX('Odometer',@vcCustomProp)+ 9, 
		(CHARINDEX('SENSOR_DURATION',@vcCustomProp) - (CHARINDEX('Odometer',@vcCustomProp) + 9) - 1)) AS INT)
		
		-- Get the current Engine Hours from the Custom Property
		SET @EngineHours = CAST(SUBSTRING(@vcCustomProp, CHARINDEX('SENSOR_DURATION',@vcCustomProp) + 16, 
		(CHARINDEX('; ;',@vcCustomProp) - (CHARINDEX('SENSOR_DURATION',@vcCustomProp))) - 16) AS INT)
		
		IF (@EngineHours <> 0 AND ((@EngineHours / 60) < 0.5))
		BEGIN
			SET @EngineHours = 0
		END
		ELSE IF (@EngineHours <> 0 AND ((@EngineHours / 60) > 0.5) AND ((@EngineHours / 60) < 1.0))
		BEGIN
			SET @EngineHours = 1
		END
		ELSE IF (@EngineHours <> 0 AND ((@EngineHours / 60) >= 1.0))
		BEGIN
			SET @EngineHours = ROUND((@EngineHours / 60), 0)
		END
	END
	ELSE IF (@vcBoxMsgInTypeName = 'Sensor' AND CAST(SUBSTRING (@vcCustomProp, CHARINDEX('=',@vcCustomProp,1)+1,CHARINDEX(';',@vcCustomProp)-1 -CHARINDEX('=',@vcCustomProp,1)) AS INT) = 3)
	BEGIN
	
		-- Get the current Odometer Reading from the Custom Property
		SET @CurrentOdometerReading = CAST(SUBSTRING(@vcCustomProp, CHARINDEX('Odometer',@vcCustomProp)+ 9, 
		(CHARINDEX('SensorInfo1',@vcCustomProp) - (CHARINDEX('Odometer',@vcCustomProp) + 9) - 1)) AS INT)
	
	END
	
	IF EXISTS(SELECT VehicleId FROM rvlfVehicleCurrentReadings WHERE VehicleId = @VehicleId)
	BEGIN 
		UPDATE rvlfVehicleCurrentReadings SET CurrentOdometerReading = @CurrentOdometerReading, 
		CurrentEngineHours = CurrentEngineHours + @EngineHours WHERE VehicleId = @VehicleId
	END
	ELSE
	BEGIN
		INSERT INTO rvlfVehicleCurrentReadings(VehicleId, CurrentOdometerReading, CurrentEngineHours) VALUES
		(@VehicleId, @CurrentOdometerReading, @EngineHours)
	END
		
 END
 
SET NOCOUNT OFF
END

-- exec [rvlf_sp_GetMaintenanceServiceNotifications] 999988, 'Sensor Off with duration', 'SENSOR_NUM=3;SENSOR_STATUS=OFF;Odometer=7;SENSOR_DURATION=3886; ;Fuel%=0;'

  




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMakDevices_MngEquip]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_GetMakDevices_MngEquip]
	@Sno int=null,                                        
	@EquipmentID varchar(max)=null,                                           
	@OrgId bigint=null,                                              
	@UserID int=null,                                          
	@bigFleetId bigint = NULL,                      
	@WarantyStart datetime=null,                      
	@WarantyEnd datetime=null,                  
	@CustomerID int=null                     
as                               
/******************************************************************************/                                                                              
-- Name  : rvlf_sp_GetMakDevices_MngEquip  null,null,6,398,177,null,null,null  
-- Description : Get MakDevices                                                                   
-- Author  : Gopal.R                                      
-- Company  : Angler Technologies                                      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                      
--Created Date -25-jun-2014                                       
/******************************************************************************/                                          
BEGIN                                
 DECLARE @HoursToBeAdded INT = 0                                                                    
 DECLARE @MinsToBeAdded INT = 0                                                        
 DECLARE @Distance varchar(20)                                                                    
 DECLARE @bigOrganizationID  bigint                                                                     
 DECLARE @DefaultDateFormat INT = 106                                                                    
 DECLARE @ConversionFactor numeric (10,2) = 1.0     

--declare @CheckUser int =null,@lastname nvarchar(100),@CheckUGid int 
--select @CheckUGid=UserGroupId from rvlfUserGroupAssignment where UserId=@UserID
--select @lastname=LastName from rvlfUser where UserId=@UserID
--if((@lastname like '%VXL%' or @lastname like '%trinetra%') or @CheckUGid=1 or @bigOrganizationID=6)
--begin
--	set @CheckUser=null
--end
--else
--begin
--	set @CheckUser=1
--end


 --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,@DefaultDateFormat=(case when  ISNULL(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end),                                                                    
	--	@bigOrganizationID = u.OrganizationId                                                                    
 --FROM rvlfUserPreferences up 
 --INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @UserID                                                                    
 --INNER JOIN rvlfUser u ON u.UserId = up.UserId                             
                                         
 SELECT Sno,MD.BoxId,md.VehicleID,MD.SubTypeId , t.VehicleTypeId as EquipmentTypeId,1 as SubTypeDesc ,t.VehicleTypeName,EquipmentName,                            
 CustomerName,EquipmentLocation,ContactNo,                            
 DateOfPurchase as DateOfPurchaseSort, Convert(varchar,CAST(dbo.rvlf_fn_DayLightSavings_Date(DateOfPurchase,@UserID,@HoursToBeAdded,@MinsToBeAdded,DateOfPurchase) AS DATE),@DefaultDateFormat ) as DateOfPurchase,                            
 WarrantyStDate as WarrantyStDateSort, Convert(varchar,CAST(dbo.rvlf_fn_DayLightSavings_Date(WarrantyStDate,@UserID,@HoursToBeAdded,@MinsToBeAdded,WarrantyStDate) AS DATE) ,@DefaultDateFormat) as WarrantyStDate,                            
 WarrantyEndDate as WarrantyEndDateSort, Convert(varchar,CAST(dbo.rvlf_fn_DayLightSavings_Date(WarrantyEndDate,@UserID,@HoursToBeAdded,@MinsToBeAdded,WarrantyEndDate) AS DATE),@DefaultDateFormat) as WarrantyEndDate,                            
 AMCStDate as AMCStDateSort, Convert(varchar,CAST(dbo.rvlf_fn_DayLightSavings_Date(AMCStDate,@UserID,@HoursToBeAdded,@MinsToBeAdded,AMCStDate) AS DATE),@DefaultDateFormat) as AMCStDate,                            
 AMCEndDate as AMCEndDateSort, Convert(varchar,CAST(dbo.rvlf_fn_DayLightSavings_Date(AMCEndDate,@UserID,@HoursToBeAdded,@MinsToBeAdded,AMCEndDate) AS DATE),@DefaultDateFormat) as AMCEndDate,                            
 AdditionalInfo,MD.OrganizationId,md.Email,CustomerId, V.Notify , V.Warning , V.Critical,
 ISNULL(dbo.rvlf_fn_GetNotificationsList(4, VA.VehicleID, 1,1,0),'') as EmailList,                                          
 ISNULL(dbo.rvlf_fn_GetNotificationsList(4, VA.VehicleID, 0,1,0),'') as SMSList,                                  
 REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(4, VA.VehicleID, 1,0,1),''),',',', ') as EmailUserNameList,                                     
 REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(4, VA.VehicleID, 0,0,1),''),',',', ') as SMSUserNameList,                                  
 ISNULL(dbo.rvlf_fn_GetNotificationsList(16, VA.VehicleID, 1,1,0),'') as AMCEmailList,                                  
 REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(16, VA.VehicleID, 1,0,1),''),',',', ') as AMCEmailUserNameList,                                 
 ISNULL(dbo.rvlf_fn_GetNotificationsList(16, VA.VehicleID, 0,1,0),'') as AMCSMSList,                                  
 REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(16, VA.VehicleID, 0,0,1),''),',',', ') as AMCSMSUserNameList,                      
 case when (AMCStDate IS not null and AMCEndDate Is not null) then 'Yes' else 'No' end as AMC,                      
 DATEDIFF(year,AMCStDate,AMCEndDate) as AMCPeriod,   --@WarantyStart as FromDate,@WarantyEnd as ToDate,             
 Convert(varchar,cast(@WarantyStart as datetime),106) as FromDate,              
 Convert(varchar,cast(@WarantyEnd as datetime),106) as ToDate, V.OpeningEngineHours,          
 Convert(varchar,cast(GETDATE() as datetime),106)+  ' ' + Convert(varchar,cast(GETDATE()  as Time),22) as PastGenDate,  
		case when WarrantyEndDate < @WarantyStart  then 'No' else 'Yes' end as WarrantyStatus ,MD.EquipmentSrNo,md.EquipmentLoca,EL.EquipmentLocaName,MD.EConsumptionType,MD.NoofShifts, 
		CASE WHEN MD.EConsumptionType =1 THEN 'Shift-wise' ELSE '24 Hours' END As Energyconsumption,
		 --CONVERT(VARCHAR(30), COnvert(varchar(30),ISNULL(CAST(CAST(cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0) AS FLOAT)/3600 AS DECIMAL(18,2)),0)))  + ' hrs' as CurrentValues     
ISNULL(cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours , 0),0) as CurrentValues,ISNULL(IsMainScr,'0') AS Main,ISNULL(MD.isAddparams,'0') As AddParam,NoAlarms,ElecTripAlert,ShutdownAlert
  FROM	rvlfMAKDevices MD                                          
 INNER	JOIN rvlfVehicle V on MD.VehicleId=V.VehicleId                
 LEFT	JOIN rvlfVehicleAssignment VA on MD.BoxId=VA.BoxId  and VA.IsDeleted=0                                           
 --LEFT	JOIN rvlfFleetVehicles fv ON VA.VehicleId=fv.VehicleId                                 
 --LEFT	OUTER JOIN rvlfMakSubProducts MSP on MSP.SubtypeId=MD.SubTypeId                                           
 LEFT	OUTER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId                                                      
 LEFT	OUTER JOIN rvlfEquipmentLocation EL on md.EquipmentLoca=EL.EquipmentLoca
 LEFT	JOIN rvlfBoxId bx ON bx.BoxId=VA.BoxId        
 LEFT JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = v.VehicleId                                        
 WHERE                                                           
  (--(@bigFleetID IS NULL OR @bigFleetID = '' OR (fv.FleetId IN (SELECT * FROM dbo.rvlf_fn_GetParentChild(@bigFleetID)))) AND                                                    
  ((@EquipmentID is Null) or (@EquipmentID = '0')  or (VA.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@EquipmentID,','))) or (@EquipmentID = '')) AND                                       
  --((@Sno is Null) or (MD.Sno = @Sno) or (@Sno = 0)) AND                                       
  ((@CustomerID is Null) or (@CustomerID = 0) or (MD.CustomerId = @CustomerID)) 
  --and ((@CheckUser is Null) or (md.CustomerName = @lastname)) 
  AND ((@OrgId is Null) or (MD.OrganizationId = @OrgId)) and MD.IsDelete=0 )
  --and((@WarantyStart is null or @WarantyEnd is null or cast(WarrantyEndDate as date) between cast(@WarantyStart as date) and cast(@WarantyEnd as date)))                  
 ORDER BY Sno DESC
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMakDevicesForSystemConfig]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_GetMakDevicesForSystemConfig]
	@Sno int=null,                                        
	@EquipmentID varchar(max)=null,                                           
	@OrgId bigint=null,                                              
	@UserID int=null,                                          
	@bigFleetId bigint = NULL,                      
	@WarantyStart datetime=null,                      
	@WarantyEnd datetime=null,                  
	@CustomerID int=null,
	@NewEdit int=null
as                               
/******************************************************************************/                                                                              
-- Name  : rvlf_sp_GetMakDevices_MngEquip  null,null,86,300,177,null,null,null  
-- Description : Get MakDevices                                                                   
-- Author  : Gopal.R                                      
-- Company  : Angler Technologies                                      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                      
--Created Date -25-jun-2014                                       
/******************************************************************************/                                          
BEGIN                                
 DECLARE @HoursToBeAdded INT = 0                                                                    
 DECLARE @MinsToBeAdded INT = 0                                                        
 DECLARE @Distance varchar(20)                                                                    
 DECLARE @bigOrganizationID  bigint                                                                     
 DECLARE @DefaultDateFormat INT = 106                                                                    
 DECLARE @ConversionFactor numeric (10,2) = 1.0     

--declare @CheckUser int =null,@lastname nvarchar(100),@CheckUGid int 
--select @CheckUGid=UserGroupId from rvlfUserGroupAssignment where UserId=@UserID
--select @lastname=LastName from rvlfUser where UserId=@UserID
--if((@lastname like '%VXL%' or @lastname like '%trinetra%') or @CheckUGid=1 or @bigOrganizationID=6)
--begin
--	set @CheckUser=null
--end
--else
--begin
--	set @CheckUser=1
--end

if(@NewEdit=0)
	begin
		 SELECT Sno,MD.BoxId,EquipmentName FROM	rvlfMAKDevices MD                                          
		 INNER	JOIN rvlfVehicle V on MD.VehicleId=V.VehicleId                
		 LEFT	JOIN rvlfVehicleAssignment VA on MD.BoxId=VA.BoxId  and VA.IsDeleted=0                                           
		 LEFT	OUTER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId                                                      
		 LEFT	OUTER JOIN rvlfEquipmentLocation EL on md.EquipmentLoca=EL.EquipmentLoca
		 LEFT	JOIN rvlfBoxId bx ON bx.BoxId=VA.BoxId                                             
		 WHERE                                                           
		  (
		  ((@EquipmentID is Null) or (@EquipmentID = '0')  or (VA.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@EquipmentID,','))) or (@EquipmentID = '')) AND                                       
		  ((@CustomerID is Null) or (@CustomerID = 0) or (MD.CustomerId = @CustomerID)) 
		  --and ((@CheckUser is Null) or (md.CustomerName = @lastname)) 
		  AND ((@OrgId is Null) or (MD.OrganizationId = @OrgId)) and MD.IsDelete=0) and MD.BoxId not in (Select boxID from rvlfSystemConfigMaster SCM where ((@CustomerID is Null) or (@CustomerID = 0) or (SCM.CustomerId = @CustomerID)) and OrganizationId=@OrgId and isDelete=0 )
		 ORDER BY EquipmentName
	 end
else
	begin
		 SELECT Sno,MD.BoxId,EquipmentName FROM	rvlfMAKDevices MD                                          
		 INNER	JOIN rvlfVehicle V on MD.VehicleId=V.VehicleId                
		 LEFT	JOIN rvlfVehicleAssignment VA on MD.BoxId=VA.BoxId  and VA.IsDeleted=0                                           
		 LEFT	OUTER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId                                                      
		 LEFT	OUTER JOIN rvlfEquipmentLocation EL on md.EquipmentLoca=EL.EquipmentLoca
		 LEFT	JOIN rvlfBoxId bx ON bx.BoxId=VA.BoxId                                             
		 WHERE                                                           
		  (
		  ((@EquipmentID is Null) or (@EquipmentID = '0')  or (VA.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@EquipmentID,','))) or (@EquipmentID = '')) AND                                       
		  ((@CustomerID is Null) or (@CustomerID = 0) or (MD.CustomerId = @CustomerID)) 
		  --and ((@CheckUser is Null) or (md.CustomerName = @lastname)) 
		  AND ((@OrgId is Null) or (MD.OrganizationId = @OrgId)) and MD.IsDelete=0) and MD.BoxId not in (Select boxID from rvlfSystemConfigMaster SCM where ((@CustomerID is Null) or (@CustomerID = 0) or (SCM.CustomerId = @CustomerID)) and OrganizationId=@OrgId and isDelete=0  and SysConfigID<>@NewEdit)
		 ORDER BY EquipmentName
	end
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetManualEntry]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetManualEntry]
	@bigQueryingUser bigint = 0,
	@bigOrganizationId bigint = NULL
AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetManualEntry 113, 7
--	Description	:	To Get the Manual Entry
--	Author		:	MuthuKumaraVadivel. V
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	06-May-2011	VM	Created Intial Version 
--              :   20-May-2011 LK  Changed the Date Format
--              :   16-Aug-2011 Ranjith Date format included
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	
	BEGIN
	
		DECLARE @ConversionFactor numeric (10,2) = 1.0
		DECLARE @DefaultDateFormat INT = 0
		
		SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,
		@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
	
		SELECT M.ManualEntryID, M.VehicleId, V.VehicleDescription AS VehicleName, 
		CONVERT(VARCHAR, M.FromDate, @DefaultDateFormat) AS FromDate,
		M.FromDate AS FromDateSort,
		CONVERT(VARCHAR, M.ToDate, @DefaultDateFormat) AS ToDate,
		M.ToDate AS ToDateSort,
		 M.EngineHours,
		CONVERT(INT, ROUND(M.Kilometers * @ConversionFactor, 0, 0)) AS Kilometers, M.Comments 
		FROM rvlfManualEntry M 
		INNER JOIN rvlfVehicle V ON M.VehicleId = V.VehicleId  
		WHERE V.OrganizationId = @bigOrganizationId		
			
    END
		
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMapItValuesForFullScreen]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- EXEC rvlf_sp_GetMapItValuesForFullScreen '999888,999980,999981',498
-- Author:		Vijay N
-- Create date: 4-Jan-2012
-- Description:	To get the mapit values for mapit.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetMapItValuesForFullScreen]
	-- Add the parameters for the stored procedure here	
	@bigBoxId VARCHAR(MAX),
	@bigQueryingUser BIGINT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    
    DECLARE @MapItValues NVARCHAR(MAX)=''
    
    SELECT @MapItValues += REPLACE((select mapitvalues from dbo.rvlf_Fn_GetMapItValues_New(FieldValue,@bigQueryingUser,'M', NULL)),'''','\''') 
    FROM rvlf_fn_ConvertArrayToTable(@bigBoxId,',')	
    
    SELECT @MapItValues AS MapItValues
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMapItValuesForFullScreenAdv]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================    
-- EXEC rvlf_sp_GetMapItValuesForFullScreenAdv '999888,999980,999981',498    
-- Author:  Ranjith N    
-- Create date: 22-Jan-2015
-- Description: To get the mapit values for mapit.    
-- =============================================    
CREATE PROCEDURE [dbo].[rvlf_sp_GetMapItValuesForFullScreenAdv]    
 -- Add the parameters for the stored procedure here     
 @bigBoxId VARCHAR(MAX),    
 @bigQueryingUser BIGINT    
AS    
BEGIN    
 -- SET NOCOUNT ON added to prevent extra result sets from    
 -- interfering with SELECT statements.    
 SET NOCOUNT ON;    
    -- Insert statements for procedure here    
        
    DECLARE @MapItValues NVARCHAR(MAX)=''    
        
    SELECT @MapItValues += REPLACE((select mapitvalues from dbo.rvlf_Fn_GetMapItValues(FieldValue,@bigQueryingUser,'M')),'''','\''')     
    FROM rvlf_fn_ConvertArrayToTable(@bigBoxId,',')     
        
    SELECT @MapItValues AS MapItValues    
END    
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMapValues]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetMapValues]      
 @bigQueryingUser bigint=NULL,      
 @vcBoxids varchar(MAX)=NULL      
AS              
/******************************************************************************/          
-- Name   : [rvlf_sp_GetMapValues] 420,'431,335,437,405,467,403,424,468,339,474,344,447,412,434,368,392,380,455,459,466,445,401,357,330,366,390,388,463,448,360,349,432,407,34,343,475,340,391,427,374,406,383,379,456,377,441,413,367,351,389,457,442,372,375'
-- -- Name   : [rvlf_sp_GetMapValues] 303,'166'
-- Description : To get mapit values for monitor          
-- Author   : V.Narayanasamy       
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--          : 16-Nov-2011 VN created      
--          : 29-Nov-2011 Sakthi get heading value depend on status and speed     
--          : 14-Dec-2011 Sakthi get the ignition status   
--          : 20-Dec-2011 Sakthi get the ignition status for sleep mode  
/*******************************************************************************/      
BEGIN      
 --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 @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 =12 THEN '0' ELSE CAST(CAST((B.LastSpeed * @ConversionFactor) as int) as varchar(30)) END ELSE '0' 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 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(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.PhoneNo,'-') 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 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       
    WHERE B.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))      
   ) AS TBL      
         
 -- 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       
       
 --get the vehicles which have not the cureent possition        
 SELECT @vcNotCurPosVeh=coalesce(@vcNotCurPosVeh,'')+(CAST(MAPVAL AS VARCHAR(MAX)))+'\n'       
  FROM (      
   SELECT (CAST(ROW_NUMBER() OVER(ORDER BY B.BOXID) AS VARCHAR)+'. '+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        
          
 SELECT @vcMapVal as Mapvalues,@vcLandmarkVal as Landmarkvalues,@vcLandmarkIds as LandmarkIds,@vcNotCurPosVeh as NotCurPosVeh      
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMapValuesMobile]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetMapValuesMobile]    
 @bigQueryingUser bigint=NULL,    
 @vcBoxids varchar(MAX)=NULL    
AS            
/******************************************************************************/        
-- Name   : [rvlf_sp_GetMapValuesMobile] 420,'431,335,437,405,467,403,424,468,339,474,344,447,412,434,368,392,380,455,459,466,445,401,357,330,366,390,388,463,448,360,349,432,407,34,343,475,340,391,427,374,406,383,379,456,377,441,413,367,351,389,457,442,372,375'
-- Description : To get mapit values for monitor        
-- Author   : V.Narayanasamy     
-- Company  : Angler Technologies        
/*******************************************************************************/    
BEGIN    
 --DECLARE THE VARIABLES FOR GET THE TIMEZONE DETAILS    
 DECLARE @SpeedUnit varchar(50),@ConversionFactor numeric (10,2) = 1.0 ,@vcMapVal VARCHAR(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 @vcMapVal=coalesce(@vcMapVal,'')+(CAST(MAPVAL AS VARCHAR(MAX)))+'~&~'     
  FROM (    
   SELECT( CAST(ISNULL(B.LastLatitude,'') AS VARCHAR)     
     + '~#~' + CAST(ISNULL(B.LastLongitude,'') AS VARCHAR)      
     + '~#~' + RV.VehicleDescription
     + '~#~' + REPLACE(ISNULL(B.LastStreetAddress,'Address is not resolved'),'''','\''')     
     + '~#~' + (dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId, h.MessageInID, h.OriginDateTime))
     + '~#~' + CAST((CASE WHEN LastSpeed = 0 THEN -1 ELSE B.Heading END) AS VARCHAR)    
     + '~#~' + 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 H.BoxMsgInTypeId = 3 THEN 0    
             WHEN H.BoxMsgInTypeId = 12 THEN 10  /*Sleep Mode*/  
             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 VARCHAR)  
     
    ) 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 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     
    WHERE B.BoxId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxIds,','))    
   ) AS TBL    
       
 -- 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     
     
 --get the vehicles which have not the cureent possition      
 SELECT @vcNotCurPosVeh=coalesce(@vcNotCurPosVeh,'')+(CAST(MAPVAL AS VARCHAR(MAX)))+'\n'     
  FROM (    
   SELECT (CAST(ROW_NUMBER() OVER(ORDER BY B.BOXID) AS VARCHAR)+'. '+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      
        
 SELECT @vcMapVal as Mapvalues,@vcLandmarkVal as Landmarkvalues,@vcLandmarkIds as LandmarkIds,@vcNotCurPosVeh as NotCurPosVeh    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMaxGeozoneAssignment]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetMaxGeozoneAssignment]       
/**************************************************************************      
Stored Procedure Name : rvlf_sp_GetMaxGeozoneAssignment      
Purpose      : Retrieves the max. no. of Geozones for the particular Box Id 
Created by   : Kumuthini      
Created date : 31-Aug-09      
Updated by   : Kumuthini     
Updated date : 01-Sep-09
****************************************************************************/      
      
@bigBoxId bigint  = Null

AS      
      
BEGIN       
  
	SELECT MaxGeozones FROM rvlfFirmware F
    INNER JOIN rvlfBoxSettings BS ON BS.FwId = F.FwId AND BS.BoxId = @bigBoxId

END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMDTReportDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
      
CREATE  PROCEDURE [dbo].[rvlf_sp_GetMDTReportDetails]            
 @bigFleetID bigint = NULL,            
 @intBoxID varchar(max) = NULL,              
 @dtStartDate DateTime = NULL,            
 @dtEndDate DateTime = NULL,            
 @tiType tinyint = 0,        
 @tiMsgDirection tinyint = 0,        
 @tiMsgStatus tinyint = 0,            
 @bigOrganizationID bigint = NULL,            
 @bigQueryingUser bigint = 0            
         
AS            
/******************************************************************************/            
-- Name  : rvlf_sp_GetMDTReportDetails 8, null, '02-Sep-12', '15-Sep-12', 0, 0, 0, 6, 140          
-- Description : To get the MDT Message Details and MDT User Login Details        
-- Author  : Kumuthini. L        
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--          : 17-Dec-2010 LK Created Intial Version               
--          : 10-Aug-2011 Ranjith Date Format included      
/******************************************************************************/            
BEGIN            
            
SET NOCOUNT ON            
      
 Declare @dtFDate datetime =@dtStartDate      
 Declare @dtEDate datetime =@dtEndDate      
              
 IF @bigFleetID IS NULL            
 BEGIN                
   SELECT @bigFleetID = FleetID FROM rvlfFleet WHERE OrganizationId = @bigOrganizationID AND IsDefault = 1                
 END         
         
 DECLARE @HoursToBeAdded INT = 0            
 DECLARE @MinsToBeAdded INT = 0            
 DECLARE @DefaultDateFormat INT = 0      
         
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
 @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 = @bigQueryingUser            
             
 SET @dtStartDate = DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))            
 SET @dtEndDate = DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))            
         
 IF @tiType = 1        
 BEGIN        
  SET @tiType = 98 -- MDT Login Details        
 END        
 ELSE IF @tiType = 2        
 BEGIN        
  SET @tiType = 77 -- MDT Message        
 END        
         
 DECLARE @MsgDirection AS Varchar(8) = ''        
 IF @tiMsgDirection = 1        
 BEGIN        
 SET @MsgDirection = 'Incoming'        
 END        
 ELSE IF @tiMsgDirection = 2        
 BEGIN        
 SET @MsgDirection = 'Outgoing'        
 END        
         
 DECLARE @Status AS Varchar(9) = ''        
 IF @tiMsgStatus = 1        
 BEGIN        
 SET @Status = 'Delivered'        
 END        
 ELSE IF @tiMsgStatus = 2        
 BEGIN        
 SET @Status = 'Failed'        
 END        
         
 DECLARE @tblMDT TABLE (BoxId Int, VehicleDescription Varchar(20), Vin Varchar(20), LicensePlate Varchar(20), OriginDateTime DateTime,        
 BoxMsgInTypeId BigInt, BoxCmdOutTypeId BigInt, [Message] Varchar(500), UserName Varchar(50), MessageType Varchar(25),        
 MessageDirection Varchar(10), Location Varchar(500), MessageStatus Varchar(10))        
         
 INSERT INTO @tblMDT (BoxId, VehicleDescription, Vin, LicensePlate, OriginDateTime, BoxMsgInTypeId, BoxCmdOutTypeId,         
    [Message], UserName, MessageType, MessageDirection, Location, MessageStatus)        
 SELECT * FROM         
  (SELECT ih.BoxId, v.VehicleDescription, v.Vin, v.LicensePlate,       
  OriginDateTime= dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,ih.OriginDateTime),      
  --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,ih.OriginDateTime)) AS OriginDateTime,         
  ih.BoxMsgInTypeId, 0 AS BoxCmdOutTypeId, dbo.rvlf_fn_GetMDTDetails(1, ih.CustomProp, ih.BoxMsgInTypeId, ih.BoxId) AS Message,          
  dbo.rvlf_fn_GetMDTDetails(2, ih.CustomProp, ih.BoxMsgInTypeId, ih.BoxId) AS UserName,        
  CASE WHEN BoxMsgInTypeId = 77 THEN dbo.rvlf_fn_GetMDTDetails(3, ih.CustomProp, ih.BoxMsgInTypeId, ih.BoxId) ELSE '-' END AS MessageType,         
  CASE WHEN BoxMsgInTypeId = 77 THEN 'Incoming' ELSE '-' END AS MessageDirection,         
  CASE WHEN BoxMsgInTypeId = 77 THEN ih.StreetAddress ELSE '-' END AS Location,  CASE WHEN BoxMsgInTypeId = 77 THEN 'Delivered' ELSE '-' END AS MessageStatus        
  FROM rvlfMsgInHst ih        
  INNER JOIN rvlfVehicleAssignment va ON va.BoxId = ih.BoxId        
  INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId        
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId        
  WHERE fv.FleetId = @bigFleetID AND ih.BoxMsgInTypeId IN (77, 98) AND ih.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate         
  AND (@intBoxID IS NULL OR @intBoxID='' OR ih.BoxId in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND BoxMsgInTypeId <> @tiType        
  UNION        
  SELECT oh.BoxId, v.VehicleDescription, v.Vin, v.LicensePlate,      
   OriginDateTime= dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,oh.SentDateTime),      
  --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,oh.SentDateTime)) AS OriginDateTime,         
  0 AS BoxMsgInTypeId, oh.BoxCmdOutTypeId,  dbo.rvlf_fn_GetMDTDetails(1, oh.CustomProp, oh.BoxCmdOutTypeId, oh.BoxId) AS Message,        
  u.UserName, dbo.rvlf_fn_GetMDTDetails(3, oh.CustomProp, oh.BoxCmdOutTypeId, oh.BoxId) AS MessageType, 'Outgoing' AS MessageDirection, '-' AS Location, CASE WHEN oh.Acknowledged = 0 THEN 'Failed' ELSE 'Delivered' END AS MessageStatus        
  FROM rvlfMsgOutHst oh        
  INNER JOIN rvlfVehicleAssignment va ON va.BoxId = oh.BoxId        
  INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId        
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId        
  INNER JOIN rvlfUser u ON oh.UserId = u.UserId        
  WHERE fv.FleetId = @bigFleetID AND oh.BoxCmdOutTypeId = 39 AND oh.SentDateTime BETWEEN @dtStartDate and @dtEndDate         
  AND (@intBoxID IS NULL OR @intBoxID='' OR oh.BoxId in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND (@tiType = 0 OR @tiType = 98 OR oh.BoxCmdOutTypeId = 0)) a        
 WHERE (@tiMsgDirection = 0 OR @tiType = 77 OR a.MessageDirection = @MsgDirection) AND (@tiMsgStatus = 0 OR @tiType = 77 OR a.MessageStatus = @Status)        
                  
 SELECT BoxId, VehicleDescription, Vin, LicensePlate, Convert(varchar,OriginDateTime,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(OriginDateTime as time),22) as OriginDateTime,OriginDateTime AS 'OriginDateTimeSort', BoxMsgInTypeId, BoxCmdOutTypeId,   
   
    [Message], UserName, MessageType, MessageDirection, Location, MessageStatus,        
 (SELECT COUNT(t2.BoxId) FROM @tblMDT t2 WHERE t1.BoxId = t2.BoxId AND (t2.BoxMsgInTypeId = 77 OR t2.BoxCmdOutTypeId = 39)) AS NoOfMsgs,        
 (SELECT COUNT(t2.BoxId) FROM @tblMDT t2 WHERE t1.BoxId = t2.BoxId AND t2.BoxMsgInTypeId = 77) AS NoOfIncomingMsgs,        
 (SELECT COUNT(t2.BoxId) FROM @tblMDT t2 WHERE t1.BoxId = t2.BoxId AND t2.BoxCmdOutTypeId = 39) AS NoOfOutgoingMsgs ,      
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,      
  PasGenerateddate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())      
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate         
  
   
 FROM @tblMDT t1        
              
 SET NOCOUNT OFF            
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMDTUsers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetMDTUsers]  
		@bigUserId bigint = Null,  
		@bigVehId BIGINT=null,		
		@bigOrganizationId bigint=null,
		@tiOpr tinyint = 0
AS  
/******************************************************************************/  
-- Name			: [rvlf_sp_GetMDTUsers]
-- Description	: To get the MDT user details
-- Author		: V.Narayanasamy  
-- Company		: Angler Technologies  
-- History		: <<Date(dd-MON-yyyy)>> Initial Reason  
--				: 18-Aug-2011 VN Created Intial Version   
/******************************************************************************/  
BEGIN  	 
	DECLARE @intBoxId AS INT = (SELECT BoxId FROM rvlfVehicleAssignment WHERE VehicleId = @bigVehId)  
	IF(@tiOpr=0)
		BEGIN		
			SELECT MU.UserId,MDTUserId,MDTUserName,MDTUserPassword,0 as Isselect,CASE WHEN MB.UserId IS NOT NULL THEN 0 ELSE 1 END AS IsAssigned    	
				FROM rvlfMDTUserTable MU
						LEFT OUTER JOIN rvlfMDTBoxMessageTable MB ON MB.UserId =MU.UserId   			
					WHERE (@bigUserId IS NULL OR @bigUserId='' OR MU.UserId =@bigUserId)									
						AND(@bigOrganizationId IS NULL OR @bigOrganizationId='' OR ORGANIZATIONID=@bigOrganizationId)						
		END
    IF(@tiOpr=1)
		BEGIN		
			DECLARE @tiTotUsers tinyint=(SELECT COUNT(UserId) FROM rvlfMDTBoxMessageTable WHERE BoxId=@intBoxId AND UserId IS NOT NULL AND CannedMsgId IS NULL)
			
			SELECT MU.UserId,MDTUserId,MDTUserName,MDTUserPassword,0 as Isselect,CASE WHEN @tiTotUsers>=10 THEN 0 ELSE 1 END AS IsExceedUsers,@tiTotUsers AS TotUsers   		
				FROM rvlfMDTUserTable MU			
					WHERE (@bigUserId IS NULL OR @bigUserId='' OR UserId =@bigUserId)				
						AND MU.UserId NOT IN(SELECT UserId FROM rvlfMDTBoxMessageTable WHERE BoxId=@intBoxId AND UserId IS NOT NULL AND CannedMsgId IS NULL)
						AND(@bigOrganizationId IS NULL OR @bigOrganizationId='' OR ORGANIZATIONID=@bigOrganizationId)
		END
	IF(@tiOpr=2)
		BEGIN						
			SELECT MU.UserId,MDTUserId,MDTUserName,MDTUserPassword,0 AS Isselect ,1 AS IsExceedUsers,0 AS TotUsers   	 		
				FROM rvlfMDTUserTable MU
					INNER JOIN rvlfMDTBoxMessageTable BT ON BT.USERID=MU.UserId 			
					WHERE (@bigUserId IS NULL OR @bigUserId='' OR MU.UserId =@bigUserId)	
						AND BT.BoxId=@intBoxId 	
						AND BT.CannedMsgId IS NULL		
						AND(@bigOrganizationId IS NULL OR @bigOrganizationId='' OR ORGANIZATIONID=@bigOrganizationId)
		END
END  


GO
/****** Object:  StoredProcedure [dbo].[RVLF_SP_GetMessageInTypes]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLF_SP_GetMessageInTypes]
	@bigCommandType bigint = null,
	@bigUserID AS bigint = null,
	@bigModuleID as bigint = 22,
	@bitIsNonAnglerAdmin AS bit = 0,
	@bigOrganizationID AS bigint = NULL
AS
/**************** **************************************************************/
--	Name		:	RVLF_SP_GetMessageInType] null,17,26,0,1
--	Description	:	To get the Message In Types
--	Author		:	S.Jeyanthi.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	19-Aug-2009	SJ	Created Intial Version --				
/******************************************************************************/
BEGIN

	IF @bitIsNonAnglerAdmin = 1
	
		SELECT *  FROM rvlfBoxMsgInType WHERE OperationTypeId IS NOT NULL order by BoxMsgInTypeDesc  asc 
	
	ELSE IF(@bitIsNonAnglerAdmin = 0)
	    BEGIN
			SELECT ct.*			 
				FROM rvlfBoxMsgInType ct
				INNER JOIN rvlfOperationType ot ON ot.OperationTypeId = ct.OperationTypeId
				INNER JOIN rvlfModule m ON ot.ModuleID = m.ModuleID			
				INNER JOIN rvlfUserGroupSecurity up ON up.OperationTypeId = ot.OperationTypeId AND up.UserGroupId = 
					(SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigUserID)
			WHERE ot.ModuleID = 26 AND  ct.OperationTypeId IS NOT NULL   order by BoxMsgInTypeDesc asc
		END	 
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetModelDetails_App]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetModelDetails_App]
@bigOrganizationID int,
@ModelId int = null,
@bigQueryingUser int = null
AS
/*********************************************************************************************
Procedure Name	: rvlf_sp_GetModelDetails_App 6,null,null
Description		: Get the model details
Created By		: Sakthi Gopinath S
Created Date	: 15-Mar-2013
*********************************************************************************************/
BEGIN
SET NOCOUNT ON

	DECLARE @HoursToBeAdded INT = 0        
	DECLARE @MinsToBeAdded INT = 0        
	DECLARE @ConversionFactor numeric (10,2) = 1.0        
	DECLARE @DistanceCaptionPrefix varchar(15)        
	DECLARE @SpeedCaptionPrefix varchar(15)      
	DECLARE @DefaultDateFormat INT = 0;
	DECLARE @bigFleetName varchar(30)      

	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,
	@DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)        
	FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz        
	ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser 


	SELECT M.ModelId,M.ModelCode,M.RptInterval,M.Pollingfreq,M.ChangingFreq,M.MobileNo,CAST(M.BattPercentage AS VARCHAR) AS BattPercentage,
	M.GPSStatus AS GPSValue,CASE WHEN M.FromDate IS NULL THEN '0' ELSE '1' END AS IsEnableDays,
	DATEPART(HOUR,M.FromTime) AS [FromHours],DATEPART(MINUTE,M.FromTime) AS [FromMinutes],
	DATEPART(HOUR,M.ToTime) AS [ToHours],DATEPART(MINUTE,M.ToTime) AS [ToMinutes],
	Convert(varchar,M.FromDate,@DefaultDateFormat) AS FromDate,
	Convert(varchar,M.ToDate,@DefaultDateFormat) AS ToDate,
	--CAST(CONVERT(DATE,M.FromDate) AS VARCHAR(12)) AS FromDate,
	--CAST(CONVERT(DATE,M.ToDate) AS VARCHAR(12)) AS ToDate,
	CONVERT(VARCHAR,M.FromTime,22) AS FromTime,
	CONVERT(VARCHAR,M.ToTime,22) AS ToTime,M.[Days],CASE WHEN M.GPSStatus=1 THEN 'Always ON' ELSE 'On-Demand' END AS GPSStatus,
	ISNULL(MA.BoxID,-1) AS BoxId,ISNULL(v.VehicleDescription,'Not assigned') AS VehicleDescription,
	CASE WHEN ISNULL(MA.BoxID,-1)=-1 THEN 'true' ELSE 'false' END AS IsAssigned,
	dbo.rvlf_fn_GetTimeFromSeconds(M.RptInterval) AS RptIntervalFormat,
	REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(4, va.VehicleId, 1,0,1),''),',',', ') AS Email,
	REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(4, va.VehicleId, 0,0,1),''),',',', ') AS SMS
	FROM dbo.rvlfModel_App M  LEFT OUTER JOIN rvlfModelBoxSettings_App MA ON MA.ModelId=M.ModelId
	LEFT OUTER JOIN dbo.rvlfVehicleAssignment va ON va.BoxId=MA.BoxID
	LEFT OUTER JOIN dbo.rvlfVehicle v ON v.VehicleId=va.VehicleId
	WHERE M.OrganizationID=@bigOrganizationID AND (@ModelId IS NULL OR @ModelId = '' OR M.ModelId=@ModelId)
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetModelPreferenceDetails_App]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetModelPreferenceDetails_App]
@UniqueModelCode VARCHAR(256)
AS
/*********************************************************************************************
Procedure Name	: rvlf_sp_GetModelPreferenceDetails_App '00000000-54b3-e7c7-0000-000046bffd97'
Description		: Get the model preference details
Created By		: Sakthi Gopinath S
Created Date	: 07-Mar-2013
*********************************************************************************************/
BEGIN
	SET NOCOUNT ON
		--GPS Status 
		-- 0 - On Demand
		-- 1 - Always ON
		SELECT ModelId,ModelCode,RptInterval,Pollingfreq,ChangingFreq,BattPercentage,
		CASE WHEN GPSStatus = 0 THEN 'On Demand' ELSE 'Always ON' END AS GPSStatus,
		CASE WHEN FromDate IS NULL THEN 'false' ELSE 'true' END AS IsDaysEnabled,
		CASE WHEN FromDate IS NULL THEN 'NA' ELSE REPLACE(CONVERT(VARCHAR,FromDate,104),'.','-') END AS FromDate,
		CASE WHEN FromDate IS NULL THEN 'NA' ELSE REPLACE(CONVERT(VARCHAR,ToDate,104),'.','-') END AS ToDate,
		CASE WHEN FromDate IS NULL THEN 'NA' ELSE SUBSTRING(CONVERT(VARCHAR,FromTime),1,8) END AS FromTime,
		CASE WHEN FromDate IS NULL THEN 'NA' ELSE SUBSTRING(CONVERT(VARCHAR,ToTime),1,8) END AS ToTime,
		CASE WHEN FromDate IS NULL THEN 'NA' ELSE [Days] END AS [Days]
		FROM dbo.rvlfModel_App WHERE ModelCode=@UniqueModelCode		
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetModelScheduledDetails_App]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetModelScheduledDetails_App]    
 @bigVehicleId bigint=null,    
 @dtFromdate datetime=null,    
 @dtTodate datetime=null,    
 @bigUserId bigint=null,    
 @intHoursToBeAdded INT = 0,    
 @intMinsToBeAdded INT = 0    
AS    
/*************************************************************************************/    
-- Name			: [rvlf_sp_GetModelScheduledDetails_App] 181,NULL,NULL,94,5,30    
-- Description	: To get the model or vehicle scheduled details    
-- Author		: Sakthi
-- Company		: Angler Technologies    
-- History		: <<Date(dd-MON-yyyy)>> Initial Reason    
/*************************************************************************************/    
BEGIN    
SET NOCOUNT ON
	declare @Lang varchar(50)           
	select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigUserId        
  
	SELECT DA.AssignmentDate,CONVERT(varchar(5),DA.FromTime,108) AS FromTime,ToTime = CONVERT(varchar(5),DA.GraceTime,108),VA.VehicleId,
	(case when @Lang='LanguageArNew' then isnull(v.VehicleDescription_Ar,v.VehicleDescription) else v.VehicleDescription end) AS VehName,
	L.LandmarkName,NULL AS TripId,0 AS IsAutomatic FROM rvlfModelSchedule_App DA  
	INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId =DA.VehicleId
	INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId  INNER JOIN rvlfLandmark L ON L.LandmarkID=DA.LandmarkId AND L.OrganizationId=V.OrganizationId
	WHERE ((@bigVehicleId IS NULL OR @bigVehicleId='') OR @bigVehicleId='' OR VA.VEHICLEID=@bigVehicleId)    
	AND (@dtFromdate IS NULL OR @dtFromdate='' OR @dtTodate IS NULL OR @dtTodate='' OR DA.AssignmentDate BETWEEN @dtFromdate AND @dtTodate)    
	ORDER BY DA.FromTime
SET NOCOUNT OFF
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetModPrivilege_Users]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE proc [dbo].[rvlf_sp_GetModPrivilege_Users]  
(                      
@bigOrganizationId bigint = Null,                    
@bigUserId bigint = Null  
)                      
as    
/******************************************************************************/       
-- Name  : rvlf_sp_GetModPrivilege_Users     
-- Description : get the users based in the module privileges  
-- Author  : Gopal.R                            
-- Company  : Angler Technologies                            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                            
-- Created Date -13-Jan-2015  
/******************************************************************************/   
begin  
select Usr.Email,Usr.DisplayName,Usr.UserId,Usr.OrganizationId from rvlfUser Usr inner join rvlfUserGroupAssignment ua on Usr.UserId=ua.UserId  
inner join rvlfUserGroupSecurity Usc on ua.UserGroupId=Usc.UserGroupId  
inner join rvlfOperationType ot on Usc.OperationTypeId=ot.OperationTypeId  
where ot.OperationTypeName ='Inventory Order Request Approve' and Usr.IsDelete=0 and Usr.IsActive=1  
and Usr.OrganizationId=@bigOrganizationId  
end  
  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetModulesOperations]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetModulesOperations]          
 @bigModuleId BIGINT = NULL,          
 @bigPackageId bigint = null          
AS          
          
/******************************************************************************/          
-- Name  : rvlf_sp_GetModulesOperations null,8          
-- Description : To get the Modules and Operations of the particular Module          
-- Author  : Kumuthini. L          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : 26-Nov-2009  Created Intial Version           
--    : 30-Nov-2009 MJJC Changed the logic of getting the moduleList,          
--           and to get the CSV list          
/******************************************************************************/          
BEGIN         
SET NOCOUNT ON           
          
 IF @bigPackageId IS NOT NULL and @bigPackageId  > 0          
 BEGIN          
           
  SELECT distinct m.ModuleID, p.PackageId, p.PackageName, p.PackageDesc,          
   m.ModuleName,m.ModuleDesc,        
        
   dbo.rvlf_fn_GetModulesOperations(po.PackageID,NULL,1)   as ModuleList          
  FROM rvlfModule m           
   INNER JOIN rvlfPackageOperations po ON po.ModuleID = m.ModuleID          
   INNER JOIN  rvlfPackage p ON po.PackageId = p.PackageId          
  WHERE p.PackageId = @bigPackageId AND m.ModuleID NOT IN          
  (SELECT ParentModuleId FROM rvlfModule WHERE ParentModuleId IS NOT NULL)     and m.ModuleDesc !='Temp'     
  UNION          
  SELECT ModuleID, null, null,null, ModuleName, ModuleDesc, dbo.rvlf_fn_GetModulesOperations(@bigPackageId,NULL,1) as ModuleList FROM rvlfModule WHERE ModuleID not in           
  ( SELECT ModuleID FROM rvlfPackageOperations WHERE PackageId = @bigPackageId) AND ModuleID NOT IN          
   (SELECT ParentModuleId FROM rvlfModule WHERE ParentModuleId IS NOT NULL)  and ModuleDesc !='Temp'           
  --Included by Jeyanthi for Ordering the module while edit          
  --Order By ModuleID           
  --End          
            
  SELECT        
 ModuleID =  CASE WHEN OperationTypeId  = 159  THEN  35     
 WHEN OperationTypeId  = 175  THEN  35     
 WHEN OperationTypeId  = 177  THEN  35    
 WHEN OperationTypeId  = 179  THEN  35     
 WHEN OperationTypeId  = 180  THEN  35     
 ELSE  m.ModuleID END, OperationTypeId , t.OperationTypeName , t.OperationDesc, m.ModuleName,m.ModuleDesc,           
    dbo.rvlf_fn_GetModulesOperations(@bigPackageId,NULL,0) as OperationsList          
  FROM rvlfOperationType t          
   INNER JOIN rvlfModule m ON t.ModuleID = m.ModuleID          
   WHERE t.OperationTypeId <> 144  ORDER BY t.OperationTypeName ASC          
             
 END          
 ELSE          
 BEGIN          
                  
        SELECT ModuleID, ModuleName, ModuleDesc, '' AS ModuleList FROM rvlfModule          
   WHERE ModuleID NOT IN (SELECT ParentModuleId FROM rvlfModule WHERE ParentModuleId IS NOT NULL)   and ModuleDesc !='Temp'       
          
          
      SELECT           
 ModuleID =  CASE WHEN OperationTypeId  = 159  THEN  35     
 WHEN OperationTypeId  = 175  THEN  35     
 WHEN OperationTypeId  = 177  THEN  35     
 WHEN OperationTypeId  = 179  THEN  35     
 WHEN OperationTypeId  = 180  THEN  35     
 ELSE ModuleID END,    
 OperationTypeId, OperationTypeName, OperationDesc, '' AS OperationsList FROM rvlfOperationType WHERE  OperationTypeId <> 144    ORDER BY OperationTypeName ASC   
      
 END          
          
SET NOCOUNT OFF          
END          
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMonthwiseFareDetailsRpt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
      
CREATE proc [dbo].[rvlf_sp_GetMonthwiseFareDetailsRpt]                    
--@bigFleetID bigint = null,                    
 @bigVendorID bigint = null,                              
 @intBoxID varchar(max) = null,                              
 @dtStartDate datetime = null,                              
 @dtEndDate datetime = null,                     
 @bigOrganizationID bigint = null,                              
 @bigQueryingUser bigint = 0                      
as                      
-- =============================================                                        
-- Name   : rvlf_sp_GetMonthwiseFareDetailsRpt   14,null,'2013-11-06 08:00:00.000 AM','2013-11-23 08:00:00.000 Pm',6,94     
-- Author  : Gopal.R                                        
-- Create date : 28-Oct-2013                                        
-- Description :  GetDaywiseFareDetailsRpt                                        
-- Company  : Angler Technologies                                        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                        
-- =============================================                      
begin                     
 Declare @VendordutyHrs int                    
 Declare @fxKmperMonth int                    
 Declare @dtFDate datetime =@dtStartDate                            
 Declare @dtEDate datetime =@dtEndDate                       
 DECLARE @HoursToBeAdded INT = 0                              
 DECLARE @MinsToBeAdded INT = 0                              
 DECLARE @ConversionFactor numeric (10,2) = 1.0                              
 DECLARE @DistanceCaptionPrefix varchar(15)                              
 DECLARE @SpeedCaptionPrefix varchar(15)                            
 DECLARE @DefaultDateFormat INT = 0;                            
 DECLARE @Hours varchar(max) = 0                      
 DECLARE @Minutes INT = 0                      
 DECLARE @Sign char =0                      
 DECLARE @ToDate Datetime = NULL                       
 DECLARE @FromDate Datetime = NULL    
 Declare @VendorContractFrom datetime      
 Declare @venodrContractTo datetime               
                      
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                      
-- @Hours= HOURS,@ToDate = ToDate,@FromDate = FromDate,                      
 --@Sign = SUBSTRING(Hours,1,1),@Minutes = SUBSTRING(Hours,5,2),                      
 @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,                  
 @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)                              
 FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz                              
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser                             
                       
 set @VendordutyHrs =(CASE WHEN (SELECT DutyHourType FROM rvlfVendors WHERE VendorId=@bigVendorID)=24 THEN 1440 ELSE 720 END )                    
 set @fxKmperMonth = (select FxKMPerMonth from rvlfVendors ve where ve.VendorId=@bigVendorID)                      
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                              
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                     
         
   --Declare Temp tables            
declare  @DayWiseDutyHrs table (boxid bigint,Startdate date,DutyHrsMin int,DutySeconds bigint,distanceKM bigint,ExtraHrsMint bigint,ExtraKm bigint)                      
declare @TripAddress table (TripID bigint,StartAddr varchar(250),EndAddr varchar(250))                    
declare @MonthlyFareDetails table (Boxid bigint,Tripdate datetime,Tripcount int,VendorID int,VendorName varchar(25),VehicleDescription varchar(50),LicensePlate varchar(60),vin varchar(20),            
OdometerStart decimal(8,2),OdometerEnd decimal(8,2),TotKm decimal(8,2),UwDistance varchar(10),FuelHike decimal(8,2),TollCharge decimal(8,2),FxCostPerMonth varchar(10),       
 Starttime datetime,closetime datetime,TripMintSec bigint,TripSeconds bigint,ExtraCostPerKm decimal(8,2),ExtraCostPerHr decimal(8,2))            
    
if(@bigVendorID is not null or @bigVendorID <> '')                  
begin      
select @VendorContractFrom=ContractFrom,@venodrContractTo=ContractTo from rvlfVendors where VendorId=@bigVendorID      
end      
      
set @VendorContractFrom =DATEADD(HOUR,(23),DATEADD(MINUTE,(58),@VendorContractFrom))                          
set @venodrContractTo =DATEADD(HOUR,(23),DATEADD(MINUTE,(58),@venodrContractTo))      
        
if(@dtStartDate between @VendorContractFrom and @venodrContractTo) --check start date and end date between contract period      
begin      
  if(@dtEndDate >= @VendorContractFrom and @dtEndDate > @venodrContractTo)      
  begin      
  set @dtEndDate =@venodrContractTo      
  end         
  --Geting some of details of distance, time of fare by day wise          
 insert into @DayWiseDutyHrs                      
 select a.BoxId,StrtDate, sum(mint) as HrsPerDay,SUM(seconds) as seconds,SUM(distanceKM) as distanceKM ,          
 case when (ven.DutyHourType *60)>SUM(mint) then 0 else (SUM(mint)- (ven.DutyHourType *60)) end as ExtraHrsMint,          
 case when (ven.FxKMPerMonth)>SUM(distanceKM) then 0 else SUM(distanceKM)-ven.FxKMPerMonth end as ExtraKm          
 from (select b.TripId,b.BoxId,cast(b.StartDate as date) as StrtDate,DATEDIFF(MINUTE,b.StartDate,b.EndDate) as mint,                    
 DATEDIFF(SECOND,b.StartDate,b.EndDate) as seconds,(b.OdometerEnd-OdometerStart) as distanceKM from rvlfTripDetails_AFC b where b.IsTripClosed=1) as a                      
 inner join rvlfTripFareDetails trpf on a.TripId=trpf.TripId                      
 inner join rvlfVehicleAssignment va on a.BoxId=va.BoxId                      
 inner join rvlfVehicle veh on va.VehicleId=veh.VehicleId                      
 inner join rvlfVendorVehicles vv on veh.VehicleId=vv.VehicleId and vv.VendorId=@bigVendorID                   
 inner join rvlfVendors ven on vv.VendorId=ven.VendorId        
 inner join rvlfTripDetails_AFC trp on trpf.TripId=trp.TripId    
 where  (@VendorContractFrom is null or @VendorContractFrom = '' or (trp.StartDate >= @VendorContractFrom and trp.StartDate<=@venodrContractTo))    
 and (DATEPART(month,StartDate) between DATEPART(month,@dtStartDate) and DATEPART(month,@dtEndDate) )    
 and (DATEPART(month, EndDate) between DATEPART(month,@dtStartDate) and DATEPART(month,@dtEndDate) )            
 group by StrtDate,a.BoxId ,ven.DutyHourType , ven.FxKMPerMonth      
                      
            
 -- getting Addres for every trip           
 insert into @TripAddress                    
 select TripId, case when trp.StartMessageInID IN (select MessageInId from rvlfMsgInHst) then                       
 (select StreetAddress from rvlfMsgInHst where MessageInID=trp.StartMessageInID) else 'N/A' end as StartAddr,                      
 case  when trp.EndMessageInID  IN (select MessageInId from rvlfMsgInHst) then                      
 (select StreetAddress from rvlfMsgInHst where MessageInID=trp.EndMessageInID) else 'N/A' end as EndDAddr                     
 from rvlfTripDetails_AFC trp                       
                       
 insert into @MonthlyFareDetails                       
 select trp.BoxId,cast(trp.StartDate as date) AS Tripdate,COUNT(trpf.TripId) as Tripcount ,ven.VendorId,ven.VendorName,veh.VehicleDescription,(veh.VehicleDescription + ' & ' + veh.LicensePlate) as LicensePlate,veh.vin,              
 min((trp.OdometerStart * @ConversionFactor)) as OdometerStart,max((trp.OdometerEnd * @ConversionFactor)) as OdometerEnd,              
 ((max(trp.OdometerEnd)-min(trp.OdometerStart)) * @ConversionFactor) as TotKm ,        
 isnull(cast(cast((sum(trpf.UwDistance) * @ConversionFactor) as int) as varchar(10)),'-')as UwDistance,             
 cast(avg(trpf.FuelHike)as decimal(8,2) )as FuelHike,sum(trpf.TollCharge) as TollCharge,                
 isnull(cast(cast(ven.FxCostPerMonth as decimal(8,2)) as varchar(10)),'-')as FxCostPerMonth,            
 min(trp.StartDate),Max(trp.EndDate),dwd.ExtraHrsMint as tripminutes, DATEDIFF(SECOND,min(trp.StartDate),max(trp.EndDate)) as TripSeconds, null,        
         
   --convert(varchar, trp.StartDate,106) as Tripdate,trp.StartDate,trp.EndDate,(dwd.distanceKM * @ConversionFactor) as distanceKM,              
 --isnull(cast(ven.ExCostPerHr as varchar(7)),'-')as ExCostPerHr, isnull(cast(ven.ExCostPerKm as varchar(7)),'-')as ExCostPerKm,              
 --dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SECOND,min(trp.StartDate),max(trp.EndDate))) as tripminutes,            
 --((case when @VendordutyHrs > dwd.DutyHrsMin and dwd.boxid=trp.BoxId then 0 else (dwd.DutyHrsMin - @VendordutyHrs)end)*60)                   
 --dwd.DutyHrsMin,dbo.rvlf_fn_GetTimeFromSeconds(DutySeconds) as DutyHrsSeconds,                    
 --PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())                     
 --,Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+                        
  --' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate ,                    
 --,sum(dbo.rvlf_fn_GetTimeFromSeconds((CASE WHEN @VendordutyHrs> dwd.DutyHrsMin then 0 else (dwd.DutyHrsMin - @VendordutyHrs) end)*60)) as totalExtraHrs,                    
 --,isnull(Tadr.StartAddr,'N/A') as StartAddr,isnull(Tadr.EndAddr,'N/A') as EndAddr,         (SUM(dwd.ExtraKm *(ven.ExCostPerKm))/10)  as ExtraCostPerKm,           
 --cast( sum( ((dwd.ExtraHrsMint)*60) *((Ven.ExCostPerHr/60)/60)) as decimal(8,2))  as ExtraCostPerHr                        
 (sum((dwd.ExtraHrsMint*60) * ((Ven.ExCostPerHr/60)/60))/10) as ExtraCostPerHr          
 from rvlfTripDetails_AFC trp                       
 inner join rvlfTripFareDetails trpf on trp.TripId=trpf.TripId                      
 inner join rvlfVehicleAssignment va on trp.BoxId=va.BoxId                      
 inner join rvlfVehicle veh on va.VehicleId=veh.VehicleId                      
 inner join rvlfVendorVehicles vv on veh.VehicleId=vv.VehicleId                      
 inner join rvlfVendors ven on vv.VendorId=ven.VendorId                      
 inner join @DayWiseDutyHrs dwd on dwd.Startdate = CAST(trp.StartDate as DATE) and dwd.boxid=trp.BoxId                     
 inner join @TripAddress Tadr on trp.TripId=Tadr.TripID                    
 where  (@dtStartDate is null or @dtStartDate = '' or trp.StartDate >= @dtStartDate ) and                   
 (@dtEndDate is null or @dtEndDate ='' or trp.StartDate <=@dtEndDate) and             
  --(@intBoxID is null or @intBoxID ='' or va.BoxId=@intBoxID) and                 
 (@intBoxID IS NULL or @intBoxID='' or va.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))and           
 (@bigVendorID is null or @bigVendorID ='' or ven.VendorId=@bigVendorID) and                   
 (@bigOrganizationID is null or @bigOrganizationID ='' or ven.OrganizationId=@bigOrganizationID)             
 and trp.IsTripClosed=1                  
 group by  trp.BoxId,cast(trp.StartDate as date),                     
 veh.VehicleDescription,veh.Vin,veh.LicensePlate,ven.VendorName,--trpf.FuelHike                  
 ven.FxCostPerMonth,dwd.ExtraHrsMint,          
 ven.VendorId              
 order by cast(trp.StartDate as date) desc       
 end                     
               
select convert(varchar,Tripdate, @DefaultDateFormat) as Tripdate ,Tripcount,b.VendorName ,VehicleDescription ,LicensePlate ,vin ,            
cast(OdometerStart as int) as OdometerStart ,cast(OdometerEnd as int) as OdometerEnd,cast(TotKm as int) as TotKm,UwDistance ,
case when FuelHike !=0 then isnull(cast(FuelHike as varchar),'-') else '-' end as FuelHikeperday ,      
(select case when avg(FuelHike) != '0' then isnull(cast(CAST(avg(FuelHike) as decimal(10,2)) as varchar(10)),'-') else '-' end from @MonthlyFareDetails a       
where a.VehicleDescription=b.VehicleDescription and a.VendorID=b.VendorID group by VehicleDescription )as FuelHike,
case when TollCharge !=0 then isnull(cast(TollCharge as varchar(10)),'-') else '-' end as TollChargeperday,
(select case when sum(TollCharge) != '0' then isnull(cast(sum(TollCharge) as varchar),'-') else '-' end from @MonthlyFareDetails a       
where a.VehicleDescription=b.VehicleDescription and a.VendorID=b.VendorID group by VehicleDescription )as TollCharge,

b.FxCostPerMonth ,            
Convert(varchar,dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,Starttime),@DefaultDateFormat)            
as Starttime           
,Convert(varchar,dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,closetime ),@DefaultDateFormat)           
as closetime            
,dbo.rvlf_fn_GetTimeFromSeconds(TripMintSec*60) as tripminutes,TripSeconds ,          
(select case when sum(ExtraCostPerKm) != '0' then isnull(cast(sum(ExtraCostPerKm) as varchar),'-') else '-' end from @MonthlyFareDetails a         
where a.VehicleDescription=b.VehicleDescription and a.VendorID=b.VendorID group by VehicleDescription ) as ExtraCostPerKm  ,         
(select case when sum(ExtraCostPerHr) != '0' then isnull(cast(sum(ExtraCostPerHr) as varchar),'-') else '-' end          
from @MonthlyFareDetails a where a.VehicleDescription=b.VehicleDescription and a.VendorID=b.VendorID group by VehicleDescription) as ExtraCostPerHr,     
           
(select dbo.rvlf_fn_GetTimeFromSeconds(sum(TripMintSec*60)) as tripminutes from @MonthlyFareDetails a where a.VehicleDescription=b.VehicleDescription and a.VendorID=b.VendorID group by VehicleDescription)          
 as TotTime         
,Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+          
' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate   ,
((case when b.FxCostPerMonth != '-' and b.FxCostPerMonth is not null then cast(b.FxCostPerMonth as decimal(10,2)) else 0 end) +
(select isnull(sum(ExtraCostPerKm),0) + isnull(sum(ExtraCostPerHr),0) + ISNULL(sum(TollCharge),0) from @MonthlyFareDetails a where a.VehicleDescription=b.VehicleDescription and a.VendorID=b.VendorID group by VehicleDescription ))
as TotAmount
       
from @MonthlyFareDetails b         
               
  -- select dbo.rvlf_fn_GetTimeFromSeconds(sum(TripSeconds)) as tripminutes,SUM(ExtraCostPerHr) as ExtraCostPerHr from @MonthlyFareDetails where (VendorID=@bigVendorID or @bigVendorID is null or @bigVendorID='')group by VehicleDescription            
end 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMsgInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[rvlf_sp_GetMsgInfo]      
(@boxID varchar(15) = null,@sentdate datetime = null,@type int,                              
    @bigQueryingUser bigint = 0, @uiMessageInID uniqueidentifier = null,@bigVehicleId bigint = null)                                
as                              
/******************************************************************************/                              
-- Name  : rvlf_sp_GetMsgInfo 16777472,'11-Aug-2014 12:50:47 PM',1, 300,'09474BF8-B3C6-E211-9A8E-00219B712B2E',null                              
-- Description : To get the message / command information based on the type                              
-- Author  : T. Sathish Kumar                              
-- Company  : Angler Technologies                              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                              

/******************************************************************************/                                
BEGIN                            
  ------- 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 @Units varchar(6)                            
 DECLARE @ConversionFactor numeric (10,2) = 1.0                            
 DECLARE @DefaultDateFormat INT = 0 
                                
                              
   SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                            
   --@ConversionFactor = CASE WHEN up.Distance = 0 THEN 1.0 ELSE 0.62 END ,                            
   @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,                            
   @Distance = CASE WHEN up.Distance = 0 THEN ' Miles' ELSE ' KM' END,                            
   @Units = 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 = @bigQueryingUser                               
                             
  --FIND THE USER AS A ANGLER ADMIN OR NOT                            
    DECLARE @bitIsAngAdmin bit =null         
    SELECT TOP 1 @bitIsAngAdmin=(CASE WHEN UserGroupId=1 THEN 1 ELSE 0 END) FROM rvlfUserGroupAssignment WHERE UserId=@bigQueryingUser                                
                             
 --------------------------------                            
 -------------------date conversion--included by Narayanasamy on 17-Nov-09---------------------------------        
 SET @sentdate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@sentdate))                            
 ----------------------------------------------------------------------------------------------------------                           
                           
  DECLARE @bitIsNotificationSent bit                            
 DECLARE @vcStreedAddress varchar(20) = NULL                         
 DECLARE @gprs varchar(10) = ''                  
DECLARE @roaming varchar(10) = ''                  
DECLARE @gps varchar(10) = ''                  
DECLARE @satellite varchar(10) = ''                  
SELECT                   
@gprs = CASE WHEN CHARINDEX('18;GPRS',IH.CustomProp,0) <> 0 THEN SUBSTRING(IH.CustomProp,CHARINDEX('GPRS_Code:',IH.CustomProp,0)+10,(CHARINDEX(';Roaming',IH.CustomProp,0)-(CHARINDEX('GPRS_Code:',IH.CustomProp,0)+10))) END,                  
@roaming = CASE WHEN CHARINDEX('18;GPRS',IH.CustomProp,0) <> 0 THEN SUBSTRING(IH.CustomProp,CHARINDEX('Roaming_Code:',IH.CustomProp,0)+13,(CHARINDEX(';GPSSatellite',IH.CustomProp,0)-(CHARINDEX('Roaming_Code:',IH.CustomProp,0)+13))) END,  
@satellite = CASE WHEN CHARINDEX('18;GPRS',IH.CustomProp,0) <> 0 THEN SUBSTRING(IH.CustomProp,CHARINDEX('GPSSatellite:',IH.CustomProp,0)+13,(CHARINDEX(';Gps_Code',IH.CustomProp,0)-(CHARINDEX('GPSSatellite:',IH.CustomProp,0)+13))) END,                  
@gps = CASE WHEN CHARINDEX('18;GPRS',IH.CustomProp,0) <> 0 THEN SUBSTRING(IH.CustomProp,CHARINDEX('Gps_Code:',IH.CustomProp,0)+9,LEN(IH.CustomProp)-(CHARINDEX('Gps_Code:',IH.CustomProp,0)+8)) END FROM rvlfMsgInHst IH                   
WHERE IH.MessageInID=@uiMessageInID                  
                      
 IF(@type =0)                            
 BEGIN                            
 SELECT DISTINCT A.*,'' AS FuelTempInfo,                            
    '' as BatteryStatus                       
  from (                            
  select ih.MessageInID,IH.BoxID,                          
  OriginDateTime= dbo.rvlf_fn_DayLightSavings(@sentdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,IH.OriginDateTime), 
      DateTimeReceived= dbo.rvlf_fn_DayLightSavings(@sentdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,IH.DateTimeReceived),
   IH.Latitude, IH.Longitude, ISNULL(IH.StreetAddress, 'Address is not resolved')  as StreetAddress,                             
   CASE WHEN IH.ValidGps = 0 then 'Valid' WHEN IH.ValidGps = 1 THEN 'Not Valid'                            
    ELSE 'No GPS information available' END as GPSStatus, IH.ValidGPS as ValidGPS,                            
   CASE WHEN IH.IsArmed = 0 THEN 'Yes' ELSE 'No' END as BoxArmed, 
   CASE WHEN IH.BoxMsgInTypeId = 28 THEN dbo.rvlf_fn_GetAlarmDetails(IH.CustomProp,                            
     IH.BoxMsgInTypeId,IH.BoxId, IH.MessageInID, IH.OriginDateTime)            
       WHEN IH.BoxMsgInTypeId = 21 THEN                            
     dbo.rvlf_fn_GetSensorMsgInformation(IH.CustomProp,IH.BoxId ) 
     WHEN IH.BoxMsgInTypeId IN(130,131,134,135) THEN                       
     dbo.rvlf_fn_GetAlarmDetails(IH.CustomProp,IH.BoxMsgInTypeId,IH.BoxId, IH.MessageInID, IH.OriginDateTime)  
    --Added by gopal for External Module command msg Sep-2013                
     WHEN IH.BoxMsgInTypeId = 56 THEN dbo.rvlf_fn_GetAlarmDetails(CustomProp,IH.BoxMsgInTypeId,IH.BoxId,IH.MessageInID,IH.OriginDateTime)                
    --                
    ELSE CustomProp END as CustomProp                
                    
     ,ih.NearestLandmark,PT.BoxProtocolTypeName,                            
   CASE WHEN SensorMask IS NOT NULL AND LEN(SensorMask)=8 THEN                            
   dbo.rvlf_fn_GetSensorMaskInformation(sensorMask,IH.BoxId) ELSE 'N/A' END as SensorInfo,                            
   CASE WHEN Speed=0 OR IH.ValidGps > 0 OR IH.BoxMsgInTypeId IN(9,14,15,16,17,24,51,90)  THEN '-'                             
    ELSE CAST(IH.Heading  as varchar(3)) END as Heading, cm.CommModeDesc,                            
    '- '   as Speed,                             
     IH.BoxMsgInTypeId   as MessageID,      
          
     IH.CommInfo1 , IH.CommInfo2,                            
   CASE                             
    WHEN IH.ValidGps > 0 OR IH.BoxMsgInTypeId IN(9,14,15,16,17,24,51,90) OR Speed=0 then '-'                            
    WHEN IH.Heading between 335 and 360 THEN 'N'                             
    WHEN IH.Heading between 0 and 25 THEN 'N'                             
    WHEN IH.Heading between 25 and 65 THEN 'NE'                             
    WHEN IH.Heading between 65 and 115 THEN 'E'                             
    WHEN IH.Heading between 115 and 155 THEN 'SE'                             
    WHEN IH.Heading between 155 and 210 THEN 'S'                             
    WHEN IH.Heading between 210 and 245 THEN 'SW'                     
    WHEN IH.Heading between 245 and 300 THEN 'W'          
    WHEN IH.Heading between 300 and 335 THEN 'NW' END as Direction,                            
    CASE WHEN IH.BoxMsgInTypeId = 28 OR IH.BoxMsgInTypeId = 73 OR IH.BoxMsgInTypeId = 94 OR IH.BoxMsgInTypeId = 98 or IH.BoxMsgInTypeId=56 
	THEN m.BoxMsgInTypeDesc                            
      WHEN IH.BoxMsgInTypeId in (4,7,13,24) then m.BoxMsgInTypeName 
           ELSE dbo.rvlf_fn_GetAlarmDetails_Optimzd( IH.customprop,IH.BoxMsgInTypeID, IH.BoxId, IH.MessageInID, IH.OriginDateTime,'LanguageEn' ) END  
		         as MessageDetails,        
            
     (case when @Lang='LanguageArNew' then isnull(v.VehicleDescription_Ar,v.VehicleDescription) else v.VehicleDescription end) as VehicleDescription, 
	 v.LicensePlate,                            
    @Distance as DistanceUnits, @ConversionFactor as ConversionFactor, @Units as Units, (case when @Lang='LanguageArNew' then isnull
	(v.VehicleDescription_Ar,v.VehicleDescription) else v.VehicleDescription end) as VehicleName,                            
   MD.CustomerName as DisplayName ,                       
    '' as MobileNo,                         
     ''   AS Generator,                            
         '' as  FuelDetails     ,
		 ('Interlock='+SUBSTRING(LastSensorMask,1,1)+';'+'Auto / Manual='+case when SUBSTRING(LastSensorMask,2,1)=1 then 'Auto' else 'Manual' end+';'
+'Centrifugal Fan 1- Trip='+ case when SUBSTRING(LastSensorMask,3,1)=1 then 'Not Tripped' else 'Tripped' end 
+';'+'Centrifugal Fan 2- Trip='+ case when SUBSTRING(LastSensorMask,4,1) =1 then 'Not Tripped' else 'Tripped' end 
+';'+'Secondary Filter- Trip='+case when SUBSTRING(LastSensorMask,5,1)=1 then 'Not Tripped' else 'Tripped' end 
+';'+'Secondary Filter- Status='+case when SUBSTRING(LastSensorMask,6,1)=1 then 'Running' else 'Stalled' end 
+';'+'Primary Filter 1- Trip='+case when SUBSTRING(LastSensorMask,7,1) =1 then 'Not Tripped' else 'Tripped' end
+';'+'Primary Filter 1- Status='+case when SUBSTRING(LastSensorMask,8,1)=1 then 'Running' else 'Stalled' end
+';'+'Primary Filter 2- Trip='+case when SUBSTRING(LastSensorMask,9,1) =1 then 'Not Tripped' else 'Tripped' end
 +';'+'Primary Filter 2- Status='+case when SUBSTRING(LastSensorMask,10,1)=1 then 'Running' else 'Stalled' end) as DigitalIP                       
                      
   from rvlfMsgInHst IH    
   inner join rvlfBoxId B on IH.BoxId=b.BoxId                         
   INNER JOIN rvlfVehicleAssignment va ON IH.BoxId = va.BoxId                            
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                            
   INNER JOIN rvlfBoxSettings s on IH.BoxId= s.BoxId                            
   INNER JOIN rvlfBoxMsgInType m ON IH.BoxMsgInTypeId = m.BoxMsgInTypeId                            
   INNER JOIN rvlfBoxProtocolType pt ON IH.BoxProtocolTypeId = pt.BoxProtocolTypeId                            
   LEFT OUTER JOIN rvlfLandmark fm ON IH.LandMarkID = fm.LandmarkID                             
   INNER JOIN rvlfCommMode cm ON s.CommModeId = cm.CommModeId                           
   --LEFT OUTER JOIN rvlfDriverAssignment da on da.BoxId = va.BoxId                        
   --LEFT OUTER JOIN rvlfDriverMaster dm on dm.DriverId = da.DriverId    
   inner join rvlfMAKDevices MD on MD.BoxId=IH.BoxId                   
  where                             
   (@uiMessageInID is NULL OR ih.MessageInID=@uiMessageInID)           
   AND (@bigVehicleId is null or  va.VehicleId = @bigVehicleId) and MD.IsDelete=0  
   ) A                            
 END                            
 ELSE                            
 BEGIN 
                          
 --SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END                          
 --  FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz                            
 --  ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser                           
                    
  select oh.BoxId,Convert(varchar,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,OH.SentDateTime)),@DefaultDateFormat)  as SentDateTime,  
  PT.BoxProtocolTypeName, U.DisplayName as UserName, MD.CustomerName as DisplayName,                           
   CASE WHEN Acknowledged = 1 THEN 'Acknowledged'                             
    WHEN Acknowledged = 0 THEN 'Expired'                             
    WHEN  Acknowledged = 2 THEN 'Success'                            
    WHEN  Acknowledged = 3 THEN 'Update Failed'                            
    WHEN  Acknowledged = 4 THEN 'CRC Incorrect'                            
    WHEN  Acknowledged = 5 THEN 'No Communication'                            
    WHEN  Acknowledged = 6 THEN 'Aborted'                            
    WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'                            
    ELSE 'Nothing' END AS Acknowledged,            
  BoxCmdOutTypeName as Message,BoxcmdTypeDesc as MessageDetails,                            
  case WHEN OH.BoxCmdOutTypeId IN( 2,14 ) THEN                             
   --Modified by Jeyanthi on 16-Aug-2010 for getting values                         
   --CAST (CAST (CAST ( OH.CustomProp AS int) / @ConversionFactor AS INT) AS Varchar(3)) + ' '+                            
   Cast(CAST (isnull(OH.CustomProp,0) / @ConversionFactor AS int) as nvarchar(10)) + ' ' +                             
   --End                            
   CASE WHEN OH.BoxCmdOutTypeId = 2 THEN @Distance ELSE REPLACE(@Distance, '/hr', '') END                            
  WHEN OH.BoxCmdOutTypeId = 19 THEN OH.CustomProp + ' feet'                            
   ELSE dbo.rvlf_fn_GetMessageOutParam(OH.CustomProp,OH.BoxCmdOutTypeId, OH.BoxId) END                            
   as CustomProp,     
    cm.CommModeDesc                             
  , OH.BoxCmdOutTypeId as MessageID,                     
  BoxcmdTypeDesc as MessageDetails, (case when @Lang='LanguageArNew' then isnull(v.VehicleDescription_Ar,v.VehicleDescription) else v.VehicleDescription end) as VehicleDescription, v.LicensePlate,                    
  (case when @Lang='LanguageArNew' then isnull(v.VehicleDescription_Ar,v.VehicleDescription) else v.VehicleDescription end) as VehicleName,                            
  @Distance as DistanceUnits, @ConversionFactor as ConversionFactor, @Units as Units                            
  from rvlfMsgOutHst OH
   INNER JOIN rvlfVehicleAssignment va On oh.boxID = va.BoxID                            
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                            
   INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId                            
   INNER JOIN rvlfBoxProtocolType PT on OH.BoxProtocolTypeID = PT.BoxProtocolTypeID                            
   LEFT OUTER JOIN rvlfMsgInHst IH ON OH.MessageInID = IH.MessageInID                            
   LEFT OUTER JOIN rvlfUser U on OH.UserId = U.UserId                             
   INNER JOIN rvlfServices s ON OH.ServiceId = s.ServiceID                            
   INNER JOIN rvlfCommMode cm ON s.CommModeId = cm.CommModeId    
   inner join rvlfMAKDevices MD on MD.BoxId=OH.BoxId                          
  where 
  OH.BoxId = @boxID and convert(varchar, SentDateTime,109) = convert(varchar,DATEADD(n,-@MinsToBeAdded,DATEADD(hh,-@HoursToBeAdded,@sentdate)),109) and MD.IsDelete=0  
 END                            
END                            
-- rvlf_sp_GetMsgInfo 2,'2009-10-10',0,3,'5FFBD946-9662-E111-B874-00219B712B2E', 10 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_Getmsginfo_App]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvlf_sp_Getmsginfo_App]
(
@MessageInID uniqueidentifier=null
)
as
begin
select top 10 MessageInID,BoxId,OriginDateTime,CustomProp,replace(replace(dbo.rvlf_fn_GetParamValueWithIndex(customprop,'AVC_Status_Word1=',';'),']',''),'[','')
 as [AVC_Status_Word1],replace(replace(dbo.rvlf_fn_GetParamValueWithIndex(customprop,'AVC_Status_Word2=',';'),']',''),'[','') as [AVC_Status_Word2]
 from rvlfMsgInHst where BoxMsgInTypeId=24 and MessageInID=@MessageInID order by OriginDateTime desc
 end

 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetMsgInfo_MAK]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetMsgInfo_MAK]  
(  
	@boxID bigint = null,  
	@sentdate datetime = null,  
	@type int,     
	@bigQueryingUser bigint = null,  
	@uiMessageInID uniqueidentifier = null,  
	@bigVehicleId bigint = null  
)            
as          
/******************************************************************************/          
-- Name  : rvlf_sp_GetMsgInfo 999980,'2016-11-22 05:16:56.000',0, 303,'CE2964C8-73B0-E611-80CF-0025900DCF95',null          
-- Description : To get the message / command information based on the type          
-- Author  : T. Sathish Kumar          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : 21-Jan-2010 MJJC Updated the metrics of the geofence          
--    : 25-Jan-2010 MJJC Updated the alarm getting alarm details          
--    : 02-Feb-2010 MJJC Changed message info to get the box msg desc for geozoneIDS.          
--    : 26-July-2010 VN  To get the speed with duration without speed          
--    : 16-Aug-2010 SJ changed Custom Prop values displayed as * instead of values          
--    : 19-Aug-2010 LK Changed the Vehicle Display Name to Vehicle Name      
--    : 04-Aug-2011 Ranjith Date format Included       
--    : 29-Apr-2013 Sakthi Message details framing for Mobile application  
/******************************************************************************/            
BEGIN        
  ------- Included by Kumuthini on 16-July-09 ---------------------        
         
 DECLARE @HoursToBeAdded INT = 0        
 DECLARE @MinsToBeAdded INT = 0        
 DECLARE @Distance varchar(20)        
 DECLARE @Units varchar(6)        
 DECLARE @ConversionFactor numeric (10,2) = 1.0        
 DECLARE @DefaultDateFormat INT = 0   
 declare @Lang varchar(50)                    
          
   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 ' Miles' ELSE ' KM' END,        
   @Units = CASE WHEN up.Distance = 0 THEN ' Miles' ELSE ' KM' END,  
   @DefaultDateFormat=(case when ISNULL(up.DefaultDateFormat,0)=0 then 106 else up.DefaultDateFormat end),  
   @Lang=isnull(Lang,'LanguageEn')       
   FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz        
   ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser        
         
   --Mobile application settings  
   DECLARE @val varchar(max)=''  
   SELECT @val = @val +(CASE value WHEN 1 THEN 'Sun' WHEN 2 THEN 'Mon' WHEN 3 THEN 'Tue' WHEN 4 THEN 'Wed' WHEN 5 THEN 'Thu' WHEN 6 THEN 'Fri' WHEN 7 THEN 'Sat' ELSE '' END)+','  
   FROM dbo.fn_Split(ISNULL((SELECT ap.[Days] FROM rvlfModel_App ap INNER JOIN rvlfModelBoxSettings_App ba ON ba.ModelId=ap.ModelId  
   INNER JOIN rvlfMsgInHst h ON h.BoxId=ba.BoxID WHERE h.MessageInID=@uiMessageInID),''),',')           
     
   DECLARE @ModelPreferenceDetails varchar(250)       
   DECLARE @BatteryPercentage varchar(75)     
   DECLARE @modelMobileNo varchar(15)  
   SELECT @ModelPreferenceDetails = 'Reporting Interval;'+ dbo.rvlf_fn_GetTimeFromSeconds(ap.RptInterval)+';Battery Alarm;'+CAST(ap.BattPercentage AS varchar)+' %;From date;'+  
   CONVERT(VARCHAR,ap.FromDate,107)+';To date;'+ CONVERT(VARCHAR,ap.ToDate,107)+';From time;'+CONVERT(varchar(15),ap.FromTime,100)+';To time;'+CONVERT(varchar(15),ap.ToTime,100)+';Days;'+@val,  
   @BatteryPercentage = 'Battery Alarm;'+CAST(ap.BattPercentage AS varchar)+' %',@modelMobileNo=ISNULL(ap.MobileNo,'-')  
   FROM rvlfModel_App ap INNER JOIN rvlfModelBoxSettings_App ba ON ba.ModelId=ap.ModelId  
   INNER JOIN rvlfMsgInHst h ON h.BoxId=ba.BoxID WHERE h.MessageInID=@uiMessageInID       
         
  --FIND THE USER AS A ANGLER ADMIN OR NOT        
    DECLARE @bitIsAngAdmin bit =null            
    SELECT TOP 1 @bitIsAngAdmin=(CASE WHEN UserGroupId=1 THEN 1 ELSE 0 END) FROM rvlfUserGroupAssignment WHERE UserId=@bigQueryingUser            
         
 --------------------------------         -------------------date conversion--included by Narayanasamy on 17-Nov-09---------------------------------        
 SET @sentdate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@sentdate))        
 ----------------------------------------------------------------------------------------------------------        
DECLARE @bitIsNotificationSent bit 
                  
DECLARE @gprs varchar(10) = ''            
DECLARE @roaming varchar(10) = ''            
DECLARE @gps varchar(10) = ''            
DECLARE @satellite varchar(10) = ''        
 DECLARE @vcStreedAddress varchar(20) = NULL   
 
	DECLARE @driverIdRF INT = NULL
	DECLARE @driverNameRF VARCHAR(MAX) = NULL
	SELECT TOP 1 @driverIdRF=A.DriverId,@driverNameRF=DM.DisplayName FROM
	(SELECT TOP 1 DriverId,ISNULL(PunchIn,FromTime) AS FromTime FROM rvlfDriverAssignment 
	WHERE (@sentdate BETWEEN FromTime AND ToTime) OR (@sentdate BETWEEN PunchIn AND PunchOut) ORDER BY FromTime DESC,PunchIn DESC 
	UNION ALL
	SELECT TOP 1 CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';') ='IN' OR @sentdate=OriginDateTime
	THEN 
	(SELECT DM.DriverId FROM rvlfIButtonMapping BP LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId=BP.DriverId
	WHERE BP.IButtonKey=dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';'))
	ELSE NULL END DriverId,h.OriginDateTime AS FromTime FROM rvlfMsgInHst h
	WHERE BoxId=@boxID AND BoxMsgInTypeId=100 AND OriginDateTime > DATEADD(HOUR,-12 ,@sentdate) ORDER BY OriginDateTime DESC) A 
	INNER JOIN rvlfDriverMaster DM ON DM.DriverId=A.DriverId
	ORDER BY A.FromTime DESC
 
      
 IF(@type =0)        
 BEGIN        
 SELECT TOP 1 A.*,CASE WHEN CustomProp  LIKE '%Battery Status=%' AND @bitIsAngAdmin=1 THEN 'Backup Battery Voltage : '+        
     CASE WHEN SUBSTRING(CustomProp,CHARINDEX('Battery Status=',CustomProp,1)+15,CHARINDEX(';',CustomProp,CHARINDEX('Battery Status=',CustomProp,1))-(CHARINDEX('Battery Status=',CustomProp,1)+15))='000' THEN 'Less than 7V'        
       WHEN SUBSTRING(CustomProp,CHARINDEX('Battery Status=',CustomProp,1)+15,CHARINDEX(';',CustomProp,CHARINDEX('Battery Status=',CustomProp,1))-(CHARINDEX('Battery Status=',CustomProp,1)+15))='001' THEN '7V'        
       WHEN SUBSTRING(CustomProp,CHARINDEX('Battery Status=',CustomProp,1)+15,CHARINDEX(';',CustomProp,CHARINDEX('Battery Status=',CustomProp,1))-(CHARINDEX('Battery Status=',CustomProp,1)+15))='010' THEN '7.2V'        
       WHEN SUBSTRING(CustomProp,CHARINDEX('Battery Status=',CustomProp,1)+15,CHARINDEX(';',CustomProp,CHARINDEX('Battery Status=',CustomProp,1))-(CHARINDEX('Battery Status=',CustomProp,1)+15))='011' THEN '7.4V'        
       WHEN SUBSTRING(CustomProp,CHARINDEX('Battery Status=',CustomProp,1)+15,CHARINDEX(';',CustomProp,CHARINDEX('Battery Status=',CustomProp,1))-(CHARINDEX('Battery Status=',CustomProp,1)+15))='100' THEN '7.6V'        
       WHEN SUBSTRING(CustomProp,CHARINDEX('Battery Status=',CustomProp,1)+15,CHARINDEX(';',CustomProp,CHARINDEX('Battery Status=',CustomProp,1))-(CHARINDEX('Battery Status=',CustomProp,1)+15))='101' THEN '7.8V'        
       WHEN SUBSTRING(CustomProp,CHARINDEX('Battery Status=',CustomProp,1)+15,CHARINDEX(';',CustomProp,CHARINDEX('Battery Status=',CustomProp,1))-(CHARINDEX('Battery Status=',CustomProp,1)+15))='110' THEN '8V'        
       ELSE 'Greater than 8.2V' END+';' ELSE '' END +        
    CASE WHEN CustomProp LIKE '%Charger Status=%' AND @bitIsAngAdmin=1  THEN         
     CASE WHEN SUBSTRING(CustomProp,CHARINDEX('Charger Status=',CustomProp,0)+15,(CHARINDEX(';',CustomProp,CHARINDEX('Charger Status=',CustomProp,0))-(CHARINDEX('Charger Status=',CustomProp,0)+15)))='0' THEN 'Backup Battery Charger : OFF'
      ELSE 'Backup Battery Charger : ON' END +';'         
    ELSE '' END +        
    CASE WHEN CustomProp LIKE '%Battery Running Status=%' AND @bitIsAngAdmin=1  THEN         
     CASE WHEN SUBSTRING(CustomProp,CHARINDEX('Battery Running Status=',CustomProp,0)+23,(CHARINDEX(';',CustomProp,CHARINDEX('Battery Running Status=',CustomProp,0))-(CHARINDEX('Battery Running Status=',CustomProp,0)+23)))='0' THEN   
     'Running Battery : Backup' ELSE 'Running Battery : Main' END+';'          
    ELSE '' END +         
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(CASE WHEN CHARINDEX('(', FuelDetails) <> 0         
                   THEN SUBSTRING(FuelDetails, CHARINDEX(' (', FuelDetails ),         
          LEN(FuelDetails)) ELSE '' END, '(', ''), ')', ''), ',', ';'), 'T1', 'Temperature Sensor-1 Value'), 'T2', 'Temperature Sensor-2 Value')        
     AS FuelTempInfo,        
    CASE WHEN CustomProp LIKE '%Voltage=%' AND @bitIsAngAdmin=1 THEN +'Voltage='+        
       SUBSTRING(CustomProp,CHARINDEX('Voltage=',CustomProp,1)+8,CHARINDEX(';',CustomProp,CHARINDEX('Voltage=',CustomProp,1))-(CHARINDEX('Voltage=',CustomProp,1)+8))+'mV'        
       ELSE '' END as BatteryStatus          
  from (        
  select MessageInID,IH.BoxID,Convert(varchar,DATEADD(n,@MinsToBeAdded, DATEADD(hh,@HoursToBeAdded,IH.OriginDateTime)),@DefaultDateFormat)+ ' ' + CONVERT(varchar,cast(DATEADD(n,@MinsToBeAdded, DATEADD(hh,@HoursToBeAdded,IH.OriginDateTime)) as Time),22)  
  AS OriginDateTime,         
   convert(varchar,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,IH.DateTimeReceived)),@DefaultDateFormat) + ' ' + CONVERT(varchar,cast(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,IH.DateTimeReceived))as time),22)  AS DateTimeReceived,      
  
   CASE WHEN IH.ValidGps = 0 then CAST(IH.Latitude AS VARCHAR) ELSE '-' END AS Latitude,   
   CASE WHEN IH.ValidGps = 0 then CAST(IH.Longitude AS VARCHAR) ELSE '-' END AS Longitude,  
   ISNULL(IH.StreetAddress, 'Address is not resolved')  as StreetAddress,         
   CASE WHEN IH.ValidGps = 0 then 'Valid' WHEN IH.ValidGps = 1 THEN 'Not Valid'        
    ELSE 'No GPS information available' END as GPSStatus, IH.ValidGPS as ValidGPS,        
   CASE WHEN IH.IsArmed = 0 THEN 'Yes' ELSE 'No' END as BoxArmed,        
   /*****************Changed by Jaya Chitra On 25-Aug-2009 ******************/        
   CASE WHEN IH.BoxMsgInTypeId = 28 THEN dbo.rvlf_fn_GetAlarmDetails_New(IH.CustomProp,IH.BoxMsgInTypeId,IH.BoxId, IH.MessageInID, IH.OriginDateTime,@Lang)         
    WHEN IH.BoxMsgInTypeId = 21 THEN dbo.rvlf_fn_GetSensorMsgInformation_New(IH.CustomProp,IH.BoxId,@Lang)        
    WHEN IH.BoxMsgInTypeId = 114 AND SUBSTRING(IH.customprop, CHARINDEX('GeozoneInOutWithDuration:', IH.customprop)+25,1) = '1' THEN       
     dbo.rvlf_fn_GetAlarmDetails_New(IH.CustomProp,IH.BoxMsgInTypeId,IH.BoxId, IH.MessageInID, IH.OriginDateTime,@Lang)    
    WHEN IH.BoxMsgInTypeId = 1 AND CHARINDEX('Param=Preference changed',IH.CustomProp,0) <> 0 THEN @ModelPreferenceDetails  
    WHEN IH.BoxMsgInTypeId = 4 AND CHARINDEX('IsAlarm=1',IH.CustomProp,0) <> 0 THEN  'Description;'+SUBSTRING(IH.CustomProp,CHARINDEX('AlarmMsg=',IH.CustomProp,0)+9,LEN(IH.CustomProp))+';'+@BatteryPercentage  
    WHEN IH.BoxMsgInTypeId = 4 AND CHARINDEX('IsAlarm=1',IH.CustomProp,0) <> 0 AND IH.CustomProp LIKE '%AlarmMsg=Battery%' THEN  'Description;'+SUBSTRING(IH.CustomProp,CHARINDEX('AlarmMsg=',IH.CustomProp,0)+9,LEN(IH.CustomProp))+';'+@BatteryPercentage  
    WHEN IH.BoxMsgInTypeId = 1 AND CHARINDEX('IsAlarm=0',IH.CustomProp,0) <> 0 THEN 'Odometer='+CAST(ISNULL(odometer,0) AS char(3)) --sakthi  
    --WHEN IH.BoxMsgInTypeId=55 THEN        
     -- '<table><tr><td>'+ REPLACE(REPLACE(REPLACE(IH.CustomProp,'=','<td>:</td><td>'),';','</td></tr><tr><td>' ), '$$', ':')+'</table>'        
	WHEN IH.BoxMsgInTypeId=114 AND CHARINDEX('18;GPRS',IH.CustomProp,0) <> 0 THEN            
		'GPRS Status;'+(CASE WHEN @gprs='1' THEN 'Low' ELSE 'Normal' END)+';'+            
		'Roaming Enabled;'+(CASE WHEN @roaming='1' THEN 'True' ELSE 'False' END)+';'+            
		'No. Of Satellite Used;'+@satellite+';'+            
		'GPS Status (PDOP);'+(CASE WHEN @gps='0' THEN 'Poor' WHEN @gps = '1' THEN 'Moderate' ELSE 'Good' END) 
    ELSE CustomProp END as CustomProp
    
     ,NearestLandmark,PT.BoxProtocolTypeName,        
   CASE WHEN SensorMask IS NOT NULL AND LEN(SensorMask)=8 THEN        
   dbo.rvlf_fn_GetSensorMsgInformation_New(sensorMask,IH.BoxId,@Lang) ELSE 'N/A' END as SensorInfo,        
   CASE WHEN Speed=0 OR IH.ValidGps > 0 OR IH.BoxMsgInTypeId IN(9,14,15,16,17,24,51,90)  THEN '-'         
    ELSE CAST(IH.Heading  as varchar(3)) END as Heading, cm.CommModeDesc,        
   CASE WHEN IH.BoxMsgInTypeId NOT IN(9,14,15,16,17,24,51,90) THEN         
    CAST(CAST(IH.Speed  * @ConversionFactor as int) as varchar(13))+ @Distance ELSE '- ' END as Speed,         
   CASE WHEN IH.BoxMsgInTypeId = 1 OR IH.BoxMsgInTypeId=4 AND CHARINDEX('MA_Model_No',IH.CustomProp,0) <> 0 THEN 114 
		WHEN IH.BoxMsgInTypeId =114 and  CHARINDEX('38;FuelTankLength',IH.CustomProp,0) <> 0 then 186
		ELSE IH.BoxMsgInTypeId END as MessageID,   
   IH.CommInfo1 , IH.CommInfo2,        
   CASE         
    WHEN IH.ValidGps > 0 OR IH.BoxMsgInTypeId IN(9,14,15,16,17,24,51,90) OR Speed=0 then '-'        
    WHEN IH.Heading between 335 and 360 THEN 'N'         
     WHEN IH.Heading between 0 and 25 THEN 'N'         
    WHEN IH.Heading between 25 and 65 THEN 'NE'         
    WHEN IH.Heading between 65 and 115 THEN 'E'         
    WHEN IH.Heading between 115 and 155 THEN 'SE'         
    WHEN IH.Heading between 155 and 210 THEN 'S'         
    WHEN IH.Heading between 210 and 245 THEN 'SW'         
    WHEN IH.Heading between 245 and 300 THEN 'W'         
    WHEN IH.Heading between 300 and 335 THEN 'NW' END as Direction,        
    CASE WHEN IH.BoxMsgInTypeId = 28 OR IH.BoxMsgInTypeId = 73 OR IH.BoxMsgInTypeId = 94 OR IH.BoxMsgInTypeId = 98 THEN m.BoxMsgInTypeDesc         
      WHEN IH.BoxMsgInTypeId=51 THEN 'Speed Violated for '        
     --+CAST(CAST(Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @Distance         
       +' (' +  dbo.rvlf_fn_GetDuration(IH.CustomProp,IH.BoxMsgInTypeId,IH.BoxID,1)+')'        
      WHEN IH.BoxMsgInTypeId=76 THEN REPLACE(dbo.rvlf_fn_GetAlarmDetails(IH.customprop,IH.BoxMsgInTypeID, IH.BoxId, IH.MessageInID, IH.OriginDateTime ),'Driver - ','')+' - '+(SELECT IButtonKeyName  FROM rvlfIButtonMapping WHERE   
      IButtonKey=CAST(SUBSTRING (       
      IH.customprop,CHARINDEX('Driver ID=',IH.customprop,1)+10,CHARINDEX(';',IH.customprop,        
        CHARINDEX('Driver ID=',IH.customprop,1)) - (CHARINDEX('Driver ID=',IH.customprop,1)+10)) as varchar))        
    WHEN IH.BoxMsgInTypeId=4 AND CHARINDEX('MA_Model_No',IH.CustomProp,0) <> 0 AND CHARINDEX('IsAlarm=1',IH.CustomProp,0) <> 0 THEN SUBSTRING(IH.CustomProp,CHARINDEX('AlarmMsg=',IH.CustomProp,0)+9,LEN(IH.CustomProp))  
    WHEN IH.BoxMsgInTypeId=1 AND CHARINDEX('MA_Model_No',IH.CustomProp,0) <> 0 AND CHARINDEX('Param=Preference changed',IH.CustomProp,0) <> 0 THEN 'Asset Settings Changed'     
    ELSE        
      CASE WHEN CHARINDEX(' (', dbo.rvlf_fn_GetAlarmDetails_New(IH.customprop,IH.BoxMsgInTypeID, IH.BoxId, IH.MessageInID, IH.OriginDateTime,@Lang )) <> 0         
           THEN REPLACE(dbo.rvlf_fn_GetAlarmDetails_New(IH.customprop,IH.BoxMsgInTypeID, IH.BoxId, IH.MessageInID, IH.OriginDateTime,@Lang ),        
                SUBSTRING(dbo.rvlf_fn_GetAlarmDetails_New(IH.customprop,IH.BoxMsgInTypeID, IH.BoxId, IH.MessageInID, IH.OriginDateTime ,@Lang),         
                CHARINDEX(' (', dbo.rvlf_fn_GetAlarmDetails_New(IH.customprop,IH.BoxMsgInTypeID, IH.BoxId, IH.MessageInID, IH.OriginDateTime ,@Lang)),         
                LEN(dbo.rvlf_fn_GetAlarmDetails_New(IH.customprop,IH.BoxMsgInTypeID, IH.BoxId, IH.MessageInID, IH.OriginDateTime ,@Lang))), '')        
           WHEN IH.BoxMsgInTypeID=97 THEN 'Harsh Thresholds'        
           WHEN IH.BoxMsgInTypeId = 114 and SUBSTRING(IH.customprop, CHARINDEX('ImgHeader:', IH.customprop)+10,1) = '1'  THEN 'Camera Image'         
           When IH.BoxMsgInTypeId = 114 and SUBSTRING(IH.customprop, CHARINDEX('CameraSettings:', IH.customprop)+15,1) = '1' Then 'Camera Settings'  
           When IH.BoxMsgInTypeId = 114 and SUBSTRING(IH.customprop, CHARINDEX('GeozoneInOutWithDuration:', IH.customprop)+25,1) = '1' Then 'Geozone In Out With Duration'  
           When IH.BoxMsgInTypeId = 114 and SUBSTRING(IH.CustomProp, CHARINDEX('IButtonCommand:', IH.CustomProp)+15,1) = '1' Then 'Send iButton Param'             
           when IH.BoxMsgInTypeId = 114 and CHARINDEX('18;GPRS',IH.CustomProp,0) <> 0  THEN 'Send Health Status'
		   when IH.BoxMsgInTypeId = 114 and CHARINDEX('38;FuelTankLength',IH.CustomProp,0) <> 0  THEN 'Send Ultrasonic Fuel Sensing Parameters'  
           ELSE dbo.rvlf_fn_GetAlarmDetails_New(IH.customprop,IH.BoxMsgInTypeID, IH.BoxId, IH.MessageInID, IH.OriginDateTime ,@Lang) END        
    END as MessageDetails, v.VehicleDescription, v.LicensePlate,        
    @Distance as DistanceUnits, @ConversionFactor as ConversionFactor, @Units as Units, v.VehicleDescription as VehicleName,      
    CASE WHEN ISNULL(@driverIdRF,0) =0 THEN dm.DisplayName ELSE @driverNameRF END AS DisplayName,  
    CASE WHEN (SELECT ISNULL(OrgId,0) FROM rvlfOrganizationServiceURL_App WHERE OrgId=v.OrganizationId) <> 0 THEN @modelMobileNo ELSE dm.mobileno END AS MobileNo,      
    CASE WHEN IH.BoxMsgInTypeId = 73 THEN dbo.rvlf_fn_GetAlarmDetails_New(IH.CustomProp, IH.BoxMsgInTypeId,IH.BoxId, IH.MessageInID, IH.OriginDateTime ,@Lang)         
    ELSE '' END AS Generator,        
    dbo.rvlf_fn_GetAlarmDetails_New(IH.customprop,IH.BoxMsgInTypeID, IH.BoxId, IH.MessageInID, IH.OriginDateTime,@Lang) FuelDetails        
   from rvlfMsgInHst IH         
   INNER JOIN rvlfVehicleAssignment va ON IH.BoxId = va.BoxId        
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId        
   INNER JOIN rvlfBoxSettings s on IH.BoxId= s.BoxId        
   INNER JOIN rvlfBoxMsgInType m ON IH.BoxMsgInTypeId = m.BoxMsgInTypeId        
   INNER JOIN rvlfBoxProtocolType pt ON IH.BoxProtocolTypeId = pt.BoxProtocolTypeId        
   LEFT OUTER JOIN rvlfLandmark fm ON IH.LandMarkID = fm.LandmarkID         
   INNER JOIN rvlfCommMode cm ON s.CommModeId = cm.CommModeId        
   LEFT OUTER JOIN rvlfDriverAssignment da on da.BoxId = va.BoxId AND 
   (@sentdate BETWEEN FromTime AND ToTime) OR (@sentdate BETWEEN PunchIn AND PunchOut)
   LEFT OUTER JOIN rvlfDriverMaster dm on dm.DriverId = da.DriverId     
  where         
   (@uiMessageInID is NULL OR MessageInID=@uiMessageInID)        
   AND (@bigVehicleId is null or  va.VehicleId = @bigVehicleId)        
   ) A        
 END        
 ELSE        
 BEGIN        
  select oh.BoxId,Convert(varchar,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,OH.SentDateTime)),@DefaultDateFormat)  as SentDateTime,PT.BoxProtocolTypeName, U.DisplayName as UserName,        
   CASE WHEN Acknowledged = 1 THEN 'Acknowledged'         
    WHEN Acknowledged = 0 THEN 'Expired'         
    WHEN  Acknowledged = 2 THEN 'Success'        
    WHEN  Acknowledged = 3 THEN 'Update Failed'        
    WHEN  Acknowledged = 4 THEN 'CRC Incorrect'        
    WHEN  Acknowledged = 5 THEN 'No Communication'        
    WHEN  Acknowledged = 6 THEN 'Aborted'        
    WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'        
    ELSE 'Nothing' END AS Acknowledged,        
  BoxCmdOutTypeName as Message,BoxcmdTypeDesc as MessageDetails,        
  case WHEN OH.BoxCmdOutTypeId IN( 2,14 ) THEN         
   --Modified by Jeyanthi on 16-Aug-2010 for getting values        
   --CAST (CAST (CAST ( OH.CustomProp AS int) / @ConversionFactor AS INT) AS Varchar(3)) + ' '+        
   Cast(CAST (isnull(OH.CustomProp,0) / @ConversionFactor AS int) as nvarchar(10)) + ' ' +         
   --End        
   CASE WHEN OH.BoxCmdOutTypeId = 2 THEN @Distance ELSE REPLACE(@Distance, '/hr', '') END        
  WHEN OH.BoxCmdOutTypeId = 19 THEN OH.CustomProp + ' feet'        
   ELSE dbo.rvlf_fn_GetMessageOutParam(OH.CustomProp,OH.BoxCmdOutTypeId, OH.BoxId) END        
   as CustomProp, cm.CommModeDesc         
  , OH.BoxCmdOutTypeId as MessageID, BoxcmdTypeDesc as MessageDetails, v.VehicleDescription, v.LicensePlate,v.VehicleDescription as VehicleName,        
  @Distance as DistanceUnits, @ConversionFactor as ConversionFactor, @Units as Units        
  from rvlfMsgOutHst OH         
   INNER JOIN rvlfVehicleAssignment va On oh.boxID = va.BoxID        
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId        
   INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId        
   INNER JOIN rvlfBoxProtocolType PT on OH.BoxProtocolTypeID = PT.BoxProtocolTypeID        
   LEFT OUTER JOIN rvlfMsgInHst IH ON OH.MessageInID = IH.MessageInID        
   LEFT OUTER JOIN rvlfUser U on OH.UserId = U.UserId         
   INNER JOIN rvlfServices s ON OH.ServiceId = s.ServiceID        
   INNER JOIN rvlfCommMode cm ON s.CommModeId = cm.CommModeId        
  where         
  OH.BoxId = @boxID and convert(varchar, SentDateTime,109) = convert(varchar, @sentdate,109)        
 END        
END        
-- rvlf_sp_GetMsgInfo 2,'2009-10-10',0,3,'CB14101B-ABBA-DE11-9B1D-000C2926DBC4', 10          
-- rvlf_sp_GetMsgInfo null,'2009-10-10',0,3,'CB14101B-ABBA-DE11-9B1D-000C2926DBC4', 10 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetNearingMaintenance]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetNearingMaintenance]        
 @bigOrganizationID bigint=null,        
 @dtStartDate DateTime=Null,        
 @dtEndDate DateTime=Null,        
 @bigFleetId bigint = null,        
 @bigVehicleId bigint = NULL,        
 @bigPlanId varchar(10) =Null,        
 @intServiceType int =Null,        
 @intNearingPercentage int =Null,        
 @intBoxID varchar(max)=Null,        
 @bigQueryingUser bigint = null        
AS       
  
/**************************************************************************************/        
-- Name        : rvlf_sp_GetNearingMaintenance 06,null,null,8,Null,Null,Null,null,null,18      
-- Description : To get the vehicles that were nearing to the maintenance        
-- Author      : Jeyanthi. S        
-- Company     : Angler Technologies        
-- History     : <<Date(dd-MON-yyyy)>> Initial Reason        
--             : 04-Oct-2010  Jeyanthi Created Intial Version         
--             : 09-Aug-2011 Ranjith Date format Included        
/**************************************************************************************/        
BEGIN        
SET NOCOUNT ON         
         
 SET @dtStartDate = NULL
 SET @dtEndDate = NULL
 Declare @dtFDate datetime =@dtStartDate      
 Declare @dtEDate datetime =@dtEndDate        
       
 DECLARE @Distance varchar(20)        
 DECLARE @ConversionFactor numeric (10,2) = 1.0        
 DECLARE @DefaultDateFormat INT = 0      
   DECLARE @HoursToBeAdded INT = 0        
 DECLARE @MinsToBeAdded INT = 0       
       
    SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,      
     @HoursToBeAdded = tz.HoursToBeAdded, @MinsToBeAdded = tz.MinToBeAdded ,        
     @Distance = 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 = @bigQueryingUser 
           
  If(@bigPlanId = '- Select -' OR @bigPlanId = 'All' OR @bigPlanId = '0')
  BEGIN
  Set @bigPlanID = null
  END 
		
 CREATE TABLE #tempLastReadings  
 (  
 VehicleId bigint,  
 DistanceTravelled bigint,  
 EngineHrs bigint  
 )   
 CREATE TABLE #tempDistance  
 (  
 BoxId int,  
 DistanceTravelled bigint  
 )   
 CREATE TABLE #tempEngineHrs  
 (  
 BoxId int,  
 EngineHrs bigint  
 )    
 CREATE TABLE #temp  
 (  
 ServiceDetailsId bigint,  
 VehiclePlanId bigint,  
 PlanDetailsId bigint,  
 VehicleId bigint,         
 PlanName varchar(100),  
 ServiceType tinyint,  
 Frequency tinyint,  
 ServicesPlanned varchar(2000),         
 ServiceCategoryId bigint,  
 DueOn varchar(35),  
 CurrentReadings bigint,  
 Nearing int,  
 IsRecurring bit,         
 ServicesDone varchar(2000),  
 ExpectedDueOn bigint,  
 CurrentValues Varchar(30),  
 PlannedCost numeric(18,2)  
 )        
 -- Get Vehicle Id by passing the Box Id        
  
       
 DECLARE @tblBoxes TABLE (BoxID int unique,VehiceID bigint)         
              
 INSERT INTO @tblBoxes (BoxID,VehiceID) SELECT va.BoxID,VA.VehicleId FROM rvlfVehicleAssignment va             
 INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId            
 WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' or BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID            
 ORDER BY BoxId   
   
    
 DECLARE @intBoxLooping int    
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes            
 WHILE @intBoxLooping IS NOT NULL  
BEGIN  
       SET @bigVehicleId  =(select VehiceID from @tblBoxes where BoxID = @intBoxLooping)  
         
 -- ****** Distance Travelled and Engine Hrs Calculation for last 2 weeks ******        
 DECLARE @dtLastStartDate DateTime = CONVERT(DATETIME,CONVERT(Date, DATEADD(DD, -14 , GETDATE())))        
 DECLARE @dtLastEndDate DateTime = CONVERT(DATETIME, CONVERT(Date, DATEADD(DD, -1 , GETDATE())))        
         
 -- Distance Travelled for Last 2 Weeks        
     DECLARE @tblUtilizationBoxes TABLE        
 (        
  SlNo int identity(1,1), BoxID int, VehicleDescription varchar(250), VehicleName varchar(50),        
  StartOdometer bigint,MaxOdometer bigint, SetOdometer bigint,EndOdometer bigint        
 )        
        
 INSERT INTO @tblUtilizationBoxes (BoxID, VehicleName, VehicleDescription )        
  SELECT @intBoxLooping, v.VehicleDescription as VehicleName, v.VehicleDescription         
  FROM rvlfVehicle v        
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId        
  INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId        
  WHERE v.OrganizationId = @bigOrganizationID AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId)        
  AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR v.VehicleId = @bigVehicleId)        
          
          
 DECLARE @dtOdometerSetDate DateTime=Null, @SetOdometer bigint=0        
 DECLARE @MaxOdometer bigint=0,@StartOdometer bigint=0,@EndOdometer bigint=0        
         
    DECLARE @intCounter int        
 SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes         
 --DECLARE @intBoxID int = 0        
 SET @intBoxID = 0        
 WHILE @intCounter IS NOT NULL        
  BEGIN        
           
   SET @dtOdometerSetDate=NULL;SET @SetOdometer=0; SET @MaxOdometer=0;SET @StartOdometer=0; SET @EndOdometer=0;        
           
   SELECT @intBoxID = BoxID FROM @tblUtilizationBoxes WHERE slno = @intCounter           
           
   SELECT TOP 1 @dtOdometerSetDate=SentDateTime, @SetOdometer=CustomProp FROM rvlfMsgOutHst              
      WHERE BoxCmdOutTypeId =14 and BoxId=@intBoxLooping and SentDateTime between         
      @dtLastStartDate and @dtLastEndDate order by SentDateTime desc        
            
           
   IF @dtOdometerSetDate IS NOT NULL        
    BEGIN        
     SELECT @MaxOdometer=(SELECT TOP 1 Max(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,        
       (CHARINDEX(';',CustomProp,        
       CHARINDEX('Odometer=',CustomProp,1))) -        
       (CHARINDEX('Odometer=',CustomProp,1)+9))) FROM rvlfMsgInHst         
      WHERE         
       BoxId = @intBoxLooping        
       AND OriginDateTime between @dtLastStartDate and @dtOdometerSetDate  and boxmsgintypeid <> 77       
       AND CustomProp LIKE '%Odometer%')              
              
    END        
           
   SET @StartOdometer=(SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,        
       (CHARINDEX(';',CustomProp,        
       CHARINDEX('Odometer=',CustomProp,1))) -        
       (CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst         
      WHERE         
       BoxId = @intBoxLooping        
       AND OriginDateTime between @dtLastStartDate and @dtLastEndDate   and boxmsgintypeid <> 77   AND Odometer > 0     
       AND CustomProp LIKE '%Odometer%'        
      ORDER BY OriginDateTime ASC)              
             
   SET @EndOdometer =(SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,        
       (CHARINDEX(';',CustomProp,        
       CHARINDEX('Odometer=',CustomProp,1))) -        
       (CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst         
      WHERE         
       BoxId = @intBoxLooping        
       AND OriginDateTime between @dtLastStartDate and @dtLastEndDate  and boxmsgintypeid <> 77  AND Odometer > 0       
       AND CustomProp LIKE '%Odometer%'        
      ORDER BY OriginDateTime DESC)        
           
              
           
   UPDATE @tblUtilizationBoxes SET StartOdometer=@StartOdometer,EndOdometer=@EndOdometer,        
    SetOdometer =@SetOdometer,MaxOdometer=@MaxOdometer  Where BoxID=@intBoxLooping          
           
   SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes WHERE SlNo < @intCounter        
  END        
          
            
         
  INSERT INTO #tempDistance(BoxId, DistanceTravelled)        
  SELECT BoxID, ISNULL(CASE WHEN SetOdometer = 0 THEN CEILING((EndOdometer - StartOdometer)* @ConversionFactor)         
  ELSE CEILING(((MaxOdometer - StartOdometer) + (EndOdometer - SetOdometer)) * @ConversionFactor) END, 0) AS DistanceTravelled       
   FROM @tblUtilizationBoxes         
  ORDER BY (EndOdometer - StartOdometer) DESC        
          
  -- Engine Hours for Last 2 Weeks        
         
        
          
    IF(@intServiceType =3)      
 BEGIN    
 INSERT INTO #tempEngineHrs(BoxId, EngineHrs)      
 SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,              
  CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -               
  ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'              
 FROM rvlfMsgInHst h               
 INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId              
 INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId     
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId              
 WHERE              
  v.OrganizationId = @bigOrganizationID  AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId)     
  AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR v.VehicleId = @bigVehicleId)            
  AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate  and  CustomProp like '%Sensor_NUM=2;%' AND CustomProp like '%SENSOR_DURATION=%'    
  AND h.BoxMsgInTypeId = 3              
 GROUP BY h.BoxId        
 END      
 ELSE      
 BEGIN     
 INSERT INTO #tempEngineHrs(BoxId, EngineHrs)            
 SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,              
  CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -               
  ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'              
 FROM rvlfMsgInHst h               
 INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId              
 INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId      
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId           
 WHERE              
  v.OrganizationId = @bigOrganizationID  AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId)            
  AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR v.VehicleId = @bigVehicleId)    
  AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate               
  AND h.BoxMsgInTypeId = 3              
 GROUP BY h.BoxId        
 END                  
  
  --INSERT INTO #tempEngineHrs(BoxId, EngineHrs)        
  --SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,        
  --    CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -         
  --    ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'        
  --FROM rvlfMsgInHst h         
  --INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId        
  --INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId        
  --INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId        
  --WHERE        
  -- v.OrganizationId = @bigOrganizationID AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId)        
  --    AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR v.VehicleId = @bigVehicleId)        
  -- AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate         
  -- AND h.BoxMsgInTypeId = 3        
  --GROUP BY h.BoxId        
       
       
        
           
  INSERT INTO #tempLastReadings(VehicleId, DistanceTravelled, EngineHrs)         
  SELECT va.VehicleId, d.DistanceTravelled, ISNULL(e.EngineHrs, 0) FROM #tempDistance d        
  LEFT OUTER JOIN #tempEngineHrs e ON e.BoxId = d.BoxId        
  INNER JOIN rvlfVehicleAssignment va ON d.BoxId = va.BoxId       
  
         
   
  
          
 -- ****** Get Nearing Maintenance ******       
        
   
         
 INSERT INTO #temp(ServiceDetailsId, VehiclePlanId, PlanDetailsId, VehicleId, PlanName, ServiceType, Frequency,         
 DueOn, CurrentReadings, Nearing, IsRecurring, ServicesDone, ExpectedDueOn, CurrentValues, PlannedCost)        
    SELECT vm.ServiceDetailsId, vm.VehiclePlanId, vm.PlanDetailsId, vp.VehicleId, mp.PlanName, vm.ServiceType, vm.Frequency,         
 CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 1 OR vm.ServiceType = 3 THEN CONVERT(VARCHAR(35), vm.DueOn) ELSE CONVERT(VARCHAR(10), vm.DueOnDate, 101) END AS DueOn,        
 CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3 THEN CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0))AS FLOAT)/(3600)AS Decimal(18,2))                 
 --CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3 THEN cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0)        
   WHEN vm.ServiceType = 1 THEN cr.CurrentOdometerReading         
   WHEN vm.ServiceType = 2 THEN (        
               CASE WHEN vm.Frequency = 0 THEN DATEDIFF(D, vm.StartDate, GETUTCDATE())         
                    WHEN vm.Frequency = 1 THEN DATEDIFF(M, vm.StartDate, GETUTCDATE())        
                    WHEN vm.Frequency = 2 THEN DATEDIFF(YEAR, vm.StartDate, GETUTCDATE()) END        
               )        
 END AS CurrentReadings, NearingPercentage AS Nearing, mp.RecurringService, dbo.rvlf_fn_GetMaintenanceServices(1, null, vm.ServiceDetailsId) AS ServicesDone,        
 (CASE WHEN vm.ServiceType = 2 THEN 0        
       WHEN vm.ServiceType = 0  OR vm.ServiceType = 3 THEN (CASE WHEN lr.EngineHrs = 0 THEN 0 ELSE ((14 * (vm.DueOn - (cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0)))) / lr.EngineHrs) END)        
       WHEN vm.ServiceType = 1 THEN (CASE WHEN lr.DistanceTravelled = 0 THEN 0 ELSE ((14 * (vm.DueOn - cr.CurrentOdometerReading)) / lr.DistanceTravelled) END)         
       ELSE '' END) AS ExpectedDueOn,        
CONVERT(VARCHAR(30), COnvert(varchar(30),ISNULL(CAST(CAST(cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0) AS FLOAT)/3600 AS DECIMAL(18,2)),0)))  + ' hrs; ' + CONVERT(VARCHAR(10), CONVERT(INT, ROUND((ISNULL(cr.CurrentOdometerReading, 0) * @ConversionFactor), 0, 0)))+ ' ' + @Distance AS CurrentValues,
 --CONVERT(VARCHAR(10), (cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0))) + ' hrs; ' + CONVERT(VARCHAR(10), CONVERT(INT, ROUND((ISNULL(cr.CurrentOdometerReading, 0) * @ConversionFactor), 0, 0))) + @Distance AS CurrentValues,        
 mp.TotalPlannedCost        
 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 rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId        
 INNER JOIN #tempLastReadings lr ON lr.VehicleId = v.VehicleId        
 WHERE mp.OrganizationId = @bigOrganizationID AND vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1         
 AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId)        
 AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR vp.VehicleId in(@bigVehicleId))        
 AND (@bigPlanId IS NULL OR @bigPlanId='' OR vp.PlanId = @bigPlanId)        
 AND (@intServiceType IS NULL OR @intServiceType='' OR vm.ServiceType = @intServiceType)        
 AND IsNearing = 1        
         
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping     
   END      
         
 CREATE TABLE #tempNearing(ServiceDetailsId bigint, VehiclePlanId bigint, PlanDetailsId bigint, Frequency tinyint, DistanceUnits varchar(8),        
 VehicleId bigint, VehicleName varchar(20), Vin varchar(20), LicensePlate varchar(20), PlanName varchar(100), ServiceType varchar(25),         
 ExpectedDueOnDate DateTime, ReadingsDue varchar(100), CurrentValues varchar(100), OverdueBy varchar(100), Nearing int,         
 ReScheduledOn DateTime, PlannedCost numeric(18,2))        
        
 INSERT INTO #tempNearing(ServiceDetailsId, VehiclePlanId, PlanDetailsId, Frequency, DistanceUnits, VehicleId, VehicleName, Vin, LicensePlate,        
  PlanName, ServiceType, ExpectedDueOnDate, ReadingsDue, CurrentValues, OverdueBy, Nearing, ReScheduledOn, PlannedCost)        
         
 SELECT Distinct t.ServiceDetailsId, t.VehiclePlanId, t.PlanDetailsId, t.Frequency, @Distance AS DistanceUnits, t.VehicleId,         
     v.VehicleDescription AS VehicleName, Vin, LicensePlate, t.PlanName,         
        CASE WHEN t.ServiceType = 0 THEN 'Engine Hours'      
   WHEN t.ServiceType = 1 THEN 'Odometer'       
    WHEN t.ServiceType = 2 THEN 'Time Based'       
    ELSE 'Concrete Mix Hours' END AS ServiceType,          
    (CASE WHEN t.ServiceType = 2 THEN t.DueOn         
              WHEN t.ServiceType = 0 OR t.ServiceType = 1 OR t.ServiceType = 3  THEN (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETDATE()) ELSE GETDATE() END) END)        
        ELSE '' END)            
        AS ExpectedDueOnDate,              
        CASE WHEN t.ServiceType = 0  OR t.ServiceType = 3 THEN CONVERT(Varchar(10), t.DueOn) + ' hrs' + (CASE WHEN vm.OdometerReadingOnDue IS NULL THEN '' ELSE '; ' + CONVERT(VARCHAR(35), CONVERT(INT, ROUND((vm.OdometerReadingOnDue * @ConversionFactor), 0
, 0))) + @Distance END      
)         
    WHEN t.ServiceType = 1 THEN (CASE WHEN vm.EngineHrsOnDue IS NULL THEN '' ELSE CONVERT(Varchar(10), vm.EngineHrsOnDue) + ' hrs; ' END) + CONVERT(VARCHAR(35), CONVERT(INT, ROUND((t.DueOn * @ConversionFactor), 0, 0))) + @Distance        
    ELSE (CASE WHEN vm.EngineHrsOnDue IS NULL THEN '' ELSE CONVERT(Varchar(10), vm.EngineHrsOnDue) + ' hrs' END) + (CASE WHEN vm.OdometerReadingOnDue IS NULL THEN '' ELSE (CASE WHEN vm.EngineHrsOnDue IS NULL THEN '' ELSE '; ' END) + CONVERT(VARCHAR(35),  
  
    
     
    CONVERT(INT, ROUND((vm.OdometerReadingOnDue * @ConversionFactor), 0, 0))) + @Distance END)         
     END AS ReadingsDue, t.CurrentValues,         
           (CASE WHEN t.ServiceType = 0 OR t.ServiceType = 3 THEN CONVERT(Varchar(10), t.CurrentReadings - t.DueOn) + ' hrs; '        
           WHEN t.ServiceType = 1 THEN CONVERT(Varchar(6),CONVERT(BIGINT, ((t.CurrentReadings - t.DueOn) * @ConversionFactor))) + @Distance + '; '         
           ELSE '' END) + (CASE WHEN t.ServiceType = 2 THEN CONVERT(VARCHAR(10), DATEDIFF(D, t.DueOn, GETUTCDATE())) + ' days'        
              WHEN t.ServiceType = 0 OR t.ServiceType = 1 THEN CONVERT(VARCHAR(10), DATEDIFF(D, (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETUTCDATE
    
      
()) ELSE GETUTCDATE() END) END), GETUTCDATE())) + ' days'        
           ELSE NULL END) AS OverdueBy, t.Nearing, vm.RescheduledOn AS ReScheduledOn, t.PlannedCost      
                 
 FROM #temp t        
 INNER JOIN rvlfVehicleMaintenanceService vm ON vm.ServiceDetailsId = t.ServiceDetailsId        
 INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId         
 INNER JOIN rvlfVehicle v ON v.VehicleId = t.VehicleId        
 INNER JOIN #tempLastReadings lr ON lr.VehicleId = v.VehicleId        
 WHERE (@intNearingPercentage IS NULL OR  @intNearingPercentage='' OR       
  (Nearing > (CASE WHEN @intNearingPercentage = 10 THEN 0 ELSE @intNearingPercentage END)        
   AND Nearing <= (CASE WHEN @intNearingPercentage = 10 THEN 20        
    WHEN @intNearingPercentage = 20 THEN 30        
    WHEN @intNearingPercentage = 30 THEN 40        
    WHEN @intNearingPercentage = 40 THEN 50        
    WHEN @intNearingPercentage = 50 THEN 60        
    WHEN @intNearingPercentage = 60 THEN 70        
    WHEN @intNearingPercentage = 70 THEN 80        
    WHEN @intNearingPercentage = 80 THEN 90         
    WHEN @intNearingPercentage = 90 THEN 100        
    WHEN @intNearingPercentage = 100 THEN 125        
    WHEN @intNearingPercentage = 125 THEN 150        
    ELSE 100000 END)))         
    ORDER BY t.Nearing DESC        
            
    ALTER TABLE #tempNearing ADD NoOfVehicles int, NoOfVehiclesNearing int, NoOfOverdueVehicles int, TotPlannedCost numeric(18,2)        
            
    UPDATE nm SET nm.NoOfVehicles = (SELECT COUNT(DISTINCT nm1.VehicleId) FROM #tempNearing nm1        
          WHERE (@dtStartDate IS NULL OR CONVERT(DATE, nm1.ExpectedDueOnDate) BETWEEN CONVERT(DATE, @dtStartDate) AND CONVERT(DATE, @dtEndDate))),        
        nm.NoOfVehiclesNearing = (SELECT COUNT(DISTINCT nm1.VehicleId) FROM #tempNearing nm1         
    WHERE (nm1.Nearing >= 0 AND nm1.Nearing <= 100)        
        AND (@dtStartDate IS NULL OR CONVERT(DATE, nm1.ExpectedDueOnDate) BETWEEN CONVERT(DATE, @dtStartDate) AND CONVERT(DATE, @dtEndDate))),        
  nm.NoOfOverdueVehicles = (SELECT COUNT(DISTINCT nm1.VehicleId) FROM #tempNearing nm1         
          WHERE nm1.Nearing > 100 AND (@dtStartDate IS NULL OR CONVERT(DATE, nm1.ExpectedDueOnDate) BETWEEN CONVERT(DATE, @dtStartDate) AND CONVERT(DATE, @dtEndDate))),        
  nm.TotPlannedCost = (SELECT SUM(nm1.PlannedCost) FROM #tempNearing nm1        
          WHERE (@dtStartDate IS NULL OR CONVERT(DATE, nm1.ExpectedDueOnDate) BETWEEN CONVERT(DATE, @dtStartDate) AND CONVERT(DATE, @dtEndDate)))                 
    FROM #tempNearing nm        
         
     IF @dtFDate IS NULL AND @dtEDate IS NULL       
    BEGIN      
  SELECT @dtFDate=MIN(ExpectedDueOnDate) FROM #tempNearing      
  SELECT @dtEDate=MAX(ExpectedDueOnDate) FROM #tempNearing      
    END      
          
    SELECT ServiceDetailsId, VehiclePlanId, PlanDetailsId, Frequency, DistanceUnits, VehicleId, VehicleName, Vin, LicensePlate,  NoOfVehicles, NoOfVehiclesNearing, NoOfOverdueVehicles, TotPlannedCost,      
  PlanName, ServiceType, Convert(varchar,ExpectedDueOnDate,@DefaultDateFormat) as ExpectedDueOnDate, ReadingsDue, CurrentValues, OverdueBy, Nearing, ReScheduledOn, PlannedCost,
  --Convert(varchar, @dtFDate,@DefaultDateFormat) 
  '-' as PasStartDate,
  --Convert(varchar,@dtEDate,@DefaultDateFormat) 
  '-' as PasEndDate,Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate  FROM #tempNearing WHERE (@dtStartDate IS NULL OR CONVERT(DATE, ExpectedDueOnDate) BETWEEN CONVERT(DATE, @dtStartDate) AND CONVERT(DATE, @dtEndDate))            
        
    DROP TABLE #tempNearing        
 DROP TABLE #temp        
    DROP TABLE #tempLastReadings    
    DROP TABLE #tempEngineHrs        
    DROP TABLE #tempDistance              
SET NOCOUNT OFF        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetNearingServiceDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetNearingServiceDetails]
	@bigServiceDetailsId bigint = NULL,
	@bigServiceCategoryID bigint
AS
/**************************************************************************************/
--	Name		:	rvlf_sp_GetNearingServiceDetails
--	Description	:	To get the pending service details 
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	24-Jun-2010		Created Intial Version 
/**************************************************************************************/
BEGIN
SET NOCOUNT ON 	
	
	DECLARE @BigVehiclePlanId AS BIGINT = 0
	DECLARE @dtLastExecutionOn AS DATETIME
	
	SET @BigVehiclePlanId = (SELECT VehiclePlanId FROM rvlfVehicleMaintenanceService WHERE ServiceDetailsId = @bigServiceDetailsId)
	SET @dtLastExecutionOn = (SELECT ExecutedOn FROM rvlfVehicleMaintenanceService WHERE ServiceDetailsId = 
							 (SELECT MAX(ServiceDetailsId) FROM rvlfVehicleMaintenanceService WHERE VehiclePlanId = @BigVehiclePlanId AND Status <> 0))
	
	SELECT ExecutedOn, ServiceCost, Comments, CASE WHEN @dtLastExecutionOn IS NOT NULL AND @dtLastExecutionOn > StartDate THEN @dtLastExecutionOn ELSE StartDate END AS StartDate
	FROM rvlfVehicleMaintenanceService 
	WHERE ServiceDetailsId = @bigServiceDetailsId

	IF @bigServiceCategoryID > 0 -- Here @bigServiceCategoryId refers Plan Id
	BEGIN

		SELECT ms.ServiceId, ms.ServiceName, ms.Description, ps.PlannedCost, sd.ServicedOn, sd.ServiceCost, (CASE WHEN sd.ServicedOn IS NOT NULL THEN 1 ELSE 0 END) AS IsDisable
		FROM rvlfMaintenanceService ms
		INNER JOIN rvlfMaintenancePlanServices ps ON ps.ServiceId = ms.ServiceId
		LEFT OUTER JOIN rvlfMaintenanceServiceDetails sd ON sd.ServiceId = ms.ServiceId AND sd.ServiceDetailsId = @bigServiceDetailsId
		WHERE ps.PlanId = @bigServiceCategoryId 
	
	END
	ELSE
	BEGIN
	
		-- If @bigServiceCategoryId is 0, then fetch the service & its cost from Adhoc Service Details
		SELECT ms.ServiceId, ms.ServiceName, ms.Description, 0 AS PlannedCost, NULL AS ServicedOn, ad.ServiceCost
		FROM rvlfMaintenanceService ms
		INNER JOIN rvlfAdhocServiceDetails ad ON ad.ServiceId = ms.ServiceId
		WHERE ad.AdhocServiceId = @bigServiceDetailsId
	
	END

SET NOCOUNT OFF
END	

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetNewsDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
CREATE Procedure [dbo].[rvlf_sp_GetNewsDetails]          
(          
  @bigOrganizationId bigint=null,          
  @bigNewsId bigint=null          
)          
AS          
/****************************************************************************************/          
-- Name    : rvlf_sp_GetNewsDetails 6,1          
-- Description   : To get the news details          
-- Author    : Jeyanthi.S          
-- Created Date  : 19-Oct-2010          
--  Modified Date :          
/***************************************************************************************/          
BEGIN          
 SET NOCOUNT ON           
           
 --SELECT * FROM rvlfNews          
 --WHERE --(@bigOrganizationId IS NULL OR OrganizationID=@bigOrganizationId) AND             
 --  (@bigNewsId IS NULL OR @bigNewsId = '' OR NewsId=@bigNewsId) AND          
 --  [Type] <> 'Tips'          
 --ORDER BY NewsId Desc           
         
 declare @NewLine char(2)          
  set @NewLine=char(13)+char(10)          
                     
 SELECT NewsId,NewsName,dbo.udf_StripHTML(REPLACE(REPLACE(REPLACE(dbo.udf_StripHTML(NewsDescription),'&quot;',''),'&nbsp;',''),'amp;','')) AS NewsDescription,[Type],                
 NavigateURL,PublishDate,ExpiryDate,OrganizationId,TipsShownDate,CreatedBy,CreatedDate,                
 ModifiedBy,ModifiedDate,ImageName,AuthorName,NewsDescription AS News,          
  REPLACE(REPLACE(REPLACE(NewsDescription,'&#39;','\'''),@NewLine,''),'"','') as  NewsDescription_Display,          
 @bigOrganizationId as OrganizationID ,isnull(IsNotificationSent,0) as IsNotificationSent,ReleasePDFLink,isnull(IsPushNotification,0) as IsPushNotification             
     
  FROM rvlfNews                  
 WHERE --(@bigOrganizationId IS NULL OR OrganizationID=@bigOrganizationId) AND                     
   (@bigNewsId IS NULL OR @bigNewsId = '' OR NewsId=@bigNewsId) AND                  
   [Type] <> 'Tips'                  
 ORDER BY NewsId Desc              
         
 SET NOCOUNT OFF          
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetNonPlannedMaintenance]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetNonPlannedMaintenance]    
@bigOrganizationID bigint  = NULL,
@bigFleetId bigint = NULL,    
@bigVehicleId bigint = NULL,    
@bigQueryingUser bigint = NULL,
@intBoxID varchar(max) = NULL
AS    
/**************************************************************************************/    
-- Name  : rvlf_sp_GetNonPlannedMaintenance 6,8,NULL,19,NULL    
-- Description : To get the vehicle which are not planned for maintenance    
-- Author  : Kumuthini. L    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--          : 10-Aug-2011 Ranjith Date format Included  
/**************************************************************************************/    
BEGIN    
SET NOCOUNT ON     
   DECLARE @DefaultDateFormat INT = 0  
 DECLARE @HoursToBeAdded INT = 0    
 DECLARE @MinsToBeAdded INT = 0   
   
    SELECT  @HoursToBeAdded = tz.HoursToBeAdded, @MinsToBeAdded = tz.MinToBeAdded ,  
     @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 = @bigQueryingUser   
      
      
      
 CREATE TABLE #Temp (ServiceDetailsId BIGINT)    
     
    INSERT INTO #Temp (ServiceDetailsId)    
 SELECT MAX(vm.ServiceDetailsId)    
 FROM rvlfVehicle v    
 INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehicleId = v.VehicleId     
 INNER JOIN rvlfVehicleMaintenanceService vm ON vm.VehiclePlanId = vp.VehiclePlanId    
 WHERE v.VehicleId NOT IN (SELECT DISTINCT vv.VehicleId FROM rvlfVehiclePlanAssignment vpp    
         INNER JOIN rvlfVehicle vv ON vv.VehicleId = vpp.VehicleId    
         INNER JOIN rvlfVehicleMaintenanceService vmm ON vmm.VehiclePlanId = vpp.VehiclePlanId    
         WHERE vmm.Status = 0 AND vv.OrganizationId = @bigOrganizationID)    
 AND v.OrganizationId = @bigOrganizationID    
 GROUP BY v.VehicleId    
     
 -- Select the Vehicles if any of the plan is not assigned 3 months after the completion of maintenance service     
 -- for the vehicle if the plan is non-recurring    
 SELECT v.VehicleDescription, v.LicensePlate, CONVERT(VARCHAR, vm.ExecutedOn, @DefaultDateFormat) AS LastServiceOn,     
 DATEDIFF(M, vm.ExecutedOn, GETUTCDATE()) AS Duration,    
    (SELECT ISNULL(SUM(ad.TotalServiceCost), 0) FROM rvlfAdhocServices ad     
  WHERE ad.VehicleId = v.VehicleId AND CONVERT(DATE, ad.ExecutionOn) >= CONVERT(DATE, vm.ExecutedOn))     
    AS UnPlannedCost,  
      PasGenerateddate =dbo.rvlf_fn_DayLightSavings(GETUTCDATE(),@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())  
   --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate     
 FROM rvlfVehicle v    
 INNER JOIN rvlfVehicleAssignment va ON va.VehicleId = v.VehicleId    
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId    
 INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehicleId = v.VehicleId     
 INNER JOIN rvlfVehicleMaintenanceService vm ON vm.VehiclePlanId = vp.VehiclePlanId    
 WHERE vm.ServiceDetailsId IN (SELECT ServiceDetailsId FROM #Temp) AND     
 DATEDIFF(M, vm.ExecutedOn, GETUTCDATE()) > 3 AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId)     
 AND (@intBoxID IS NULL OR @intBoxID='' OR va.BoxId in(select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))     
     
 UNION    
     
 -- Select the Vehicle which are not assigned for Maintenance from the Vehicle Purchase or Creation date    
 SELECT v.VehicleDescription, v.LicensePlate, '-' AS LastServiceOn,     
 CASE WHEN v.PurchasedDate IS NULL THEN DATEDIFF(M, v.CreatedDateTime, GETUTCDATE())     
   ELSE DATEDIFF(M, v.PurchasedDate, GETUTCDATE()) END AS Duration,    
    (SELECT ISNULL(SUM(ad.TotalServiceCost), 0) FROM rvlfAdhocServices ad WHERE ad.VehicleId = v.VehicleId) AS UnPlannedCost,  
    PasGenerateddate =dbo.rvlf_fn_DayLightSavings(GETUTCDATE(),@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())  
     --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate     
 FROM rvlfVehicle v    
 INNER JOIN rvlfVehicleAssignment va ON va.VehicleId = v.VehicleId    
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId    
 LEFT OUTER JOIN rvlfVehiclePlanAssignment vp ON vp.VehicleId = v.VehicleId     
 LEFT OUTER JOIN rvlfVehicleMaintenanceService vm ON vm.VehiclePlanId = vp.VehiclePlanId    
 WHERE v.OrganizationId = @bigOrganizationID AND vm.ServiceDetailsId IS NULL    
 AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId) AND (@intBoxID IS NULL OR @intBoxID='' OR va.BoxId in(select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))     
     
 DROP TABLE #Temp    
     
SET NOCOUNT OFF    
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetNonReportingDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetNonReportingDetails]
@bigFleetID bigint = NULL,
@intBoxID varchar(max) = null,
@dtStartDate datetime = null,
@dtEndDate datetime = null,
@bitTripStatus bit = 1,
@bigOrganizationID bigint = NULL,
@bigQueryingUser bigint = NULL,
@NoOfDays smallint = 1
AS
/************************************************************************************************            
Procedure Name	: rvlf_sp_GetNonReportingDetails 164,null,'2013-01-02 08:00:00.000',null,null,107,303,5
				: rvlf_sp_GetNonReportingDetails 181,null,'2013-02-01 00:00:00.000',null,null,107,499,2
Description		: To get the non-reporting device details
Author			: Sakthi Gopinath S           
Company			: Angler Technologies            
**************************************************************************************************/      
BEGIN
SET NOCOUNT ON
	DECLARE @Lang varchar(50)               
	SELECT @Lang=isnull(Lang,'LanguageEn') from dbo.rvlfUserPreferences where UserId = @bigQueryingUser            
                                  
	DECLARE @bigFleetName nvarchar(200)
	IF @bigFleetID IS NULL              
	BEGIN              
		SELECT @bigFleetID=FleetID FROM rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1              
	END  

	--Get the Fleet name
	SELECT @bigFleetName = FleetName FROM rvlfFleet WHERE FleetId = @bigFleetID

	DECLARE @HoursToBeAdded INT = 0              
	DECLARE @MinsToBeAdded INT = 0              
	DECLARE @ConversionFactor numeric (10,2) = 1.0              
	DECLARE @DistanceCaptionPrefix nvarchar(15)              
	DECLARE @SpeedCaptionPrefix nvarchar(15)            
	DECLARE @DisplayName nvarchar(30)      
	DECLARE @DefaultDateFormat INT = 0;

	SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@DisplayName = U.UserName,           
	@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,                
	@DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(Miles)' ELSE '(Km)' END,              
	@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(MPH)' ELSE '(KMPH)' 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 = @bigQueryingUser      
	INNER JOIN rvlfUser U on U.UserId = up.UserId  

	DECLARE @dtFDate datetime = DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,CAST(CAST(@dtStartDate AS DATE) AS DATETIME)))
	DECLARE @dtEDate datetime =@dtEndDate   

	SELECT DISTINCT @bigFleetID AS FleetId,@bigFleetName AS FleetName,v.VehicleId,
	CASE WHEN @Lang = 'LanguageArNew' THEN ISNULL(v.VehicleDescription,v.VehicleDescription) ELSE v.VehicleDescription END AS VehicleDescription,
	CONVERT(VARCHAR,b.LastValidDateTime,@DefaultDateFormat) + ' ' + CONVERT(VARCHAR,CAST(b.LastValidDateTime AS TIME),22) AS LastReportedDate,
	dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,b.Boxid,null,null) AS MessageDetails,
	CASE WHEN @Lang = 'LanguageArNew' THEN ISNULL(h.StreetAddress_AR,h.StreetAddress) ELSE h.StreetAddress END AS StreetAddress,
	CAST(DATEDIFF(DD, b.LastStatusDateTime, GETUTCDATE()) AS INT) AS NoOfDays,
	CASE WHEN @Lang = 'LanguageArNew' THEN N'غير المبلغ عنها لأيام '+CAST(@NoOfDays AS VARCHAR)+N' مشاركة'
	ELSE 'Not reported for last ' + CAST(@NoOfDays AS VARCHAR) + ' days' END AS Duration,
	CONVERT(VARCHAR,@dtFDate,@DefaultDateFormat) + ' 12:00:00 AM' AS PasStartDate,
	@DisplayName + ' - ' + CONVERT(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ 
	' '+ CONVERT(VARCHAR,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) AS TIME),22) AS PasGeneratedDate
	FROM rvlfBoxId b 
	INNER JOIN rvlfMsgInHst h ON b.MessageInId=h.MessageInID
	INNER JOIN rvlfVehicleAssignment va ON va.BoxId=h.BoxId
	INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId
	INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=v.VehicleId
	INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId
	WHERE (@bigFleetID IS NULL OR @bigFleetID = '' OR f.FleetId IN (@bigFleetID)) AND
	(@intBoxID IS NULL OR @intBoxID = '' OR @intBoxID='0' OR b.BoxId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND
	b.OrganizationId = @bigOrganizationID AND 
	((@dtFDate IS NULL  AND DATEDIFF(DD, b.LastStatusDateTime, GETUTCDATE()) > @NoOfDays) OR
	DATEDIFF(DD, b.LastStatusDateTime, @dtFDate) > @NoOfDays)
	--(b.LastStatusDateTime BETWEEN DATEADD(DD,(-1*@NoOfDays),@dtFDate) AND @dtFDate))
	
SET NOCOUNT OFF
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetNotificationCount_WithTemplate]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetNotificationCount_WithTemplate]      
@bigUserId INT = NULL,      
@bigOrganizationId INT = NULL      
AS      
/******************************************************************************/                                                        
-- Procedure Name : rvlf_sp_GetNotificationCount_WithTemplate 576,6      
-- Description  : Get Notification Lists      
-- Author   : Sakthi Gopinath S      
-- Company   : Trinetra Wireless (P) Ltd.      
-- History   : SS <25-Jun-2015> Initial Reason      
/******************************************************************************/                
BEGIN      
SET NOCOUNT ON      
	DECLARE @vcDetail VARCHAR(MAX) = ''      
	DECLARE @vcMsgInIds VARCHAR(MAX) = ''      
	DECLARE @vcNoNotifyDetails VARCHAR(MAX) = ''      
	DECLARE @nCount INT = 0      
	DECLARE @tbl table (Subjectsufix varchar(20),MessageInID uniqueidentifier,Readcount int,Notify int,Warning int,Critical int, Orderby tinyint)
 
	INSERT	INTO @tbl
	SELECT	nl.Subjectsufix,nl.MessageInID,  
			ISNULL((CASE WHEN nr.UserId > 1 THEN 0 ELSE NULL END) ,1) AS ReadCount,
			CASE WHEN nl.Subjectsufix='Notify' THEN 1 ELSE 0 END AS notify,
			CASE WHEN nl.Subjectsufix='Warning' THEN 1 ELSE 0 END AS Warning,
			CASE WHEN nl.Subjectsufix='Critical' THEN 1 ELSE 0 END AS Critical,
			CASE WHEN nl.Subjectsufix='Notify' THEN 2 WHEN nl.Subjectsufix='Warning' THEN 1 ELSE 0 END 
	FROM	dbo.rvlfNotificationLog nl 
	INNER	JOIN rvlfMsgInHst h ON h.MessageInID=nl.MessageInID AND nl.FleetID IS NULL    
	INNER	JOIN dbo.rvlfVehicle v ON v.VehicleId=nl.VehicleID     
	INNER	JOIN dbo.rvlfUserGroupAssignment ua ON nl.UserId=ua.UserId    
	INNER	JOIN dbo.rvlfUserGroupSecurity ugs ON ugs.UserGroupId=ua.UserGroupId    
	INNER	JOIN dbo.rvlfUser u ON u.UserId = nl.UserID    
	INNER	JOIN dbo.rvlfBoxMsgInType bm ON bm.OperationTypeID=ugs.OperationTypeId AND nl.BoxMsgInTypeName=bm.BoxMsgInTypeName  
	LEFT	OUTER JOIN dbo.rvlfNotificationRead nr ON nr.MessageInId=nl.MessageInID AND nr.UserId=nl.UserID  
	WHERE	u.UserId=@bigUserId AND nl.OrganizationID=@bigOrganizationId
	AND		DATEDIFF(HOUR,h.OriginDateTime,GETUTCDATE()) < 24


 ----#FFF url("../images/chart-bg.jpg") repeat-x scroll center bottom      
 --SELECT @vcNoNotifyDetails = '<div style=''padding:3px''><table class=''form-tbl'' style=''height:60px;background-color:white''>'+  '<tr><td style=''width:1%;color:#1B67B2;text-align:center;vertical-align:middle'' rowspan=''2''>'+      
 --'<span style=''font-family:Arial,Verdana,Helvetica,sans-serif;font-size:12px;line-height:1.5''>'+      
 --'<b>No new notification</b></span></td></tr></table></div>';       
 --SELECT @vcDetail = @vcDetail + '<div style=''padding:3px''>'+       
 --'<table class=''form-tbl'' style=''height:60px;border:1px solid #333333;background-color:' +      
 --(CASE WHEN NT.Subjectsufix='Critical' THEN '#FFEAEA;border-color:#AE6A5F''>'   
 --WHEN NT.Subjectsufix='Warning' THEN '#FDF6C4;border-color:#D3B56F''>'   
 --ELSE '#E1F5FA;border-color:#6B879F''>' END)+ '<tr>'+      
 --'<td style=''width:10%;text-align:center;vertical-align:middle'' rowspan=''2''><img style=''height:20px'' src='''+      
 --(CASE WHEN NT.Subjectsufix='Critical' THEN '..\images\icnNearingPercentage.png'' />'      
 --WHEN NT.Subjectsufix='Warning' THEN '..\images\icnNotifyOn.png'' />'      
 --ELSE '..\images\icn-notify.gif'' />' END)+ '</td>'+     
 --'<td colspan=''1'' style=''width:25%;text-align:left;''><span style=''font-family:Arial,Verdana,Helvetica,sans-serif;font-size:14px;font-weight:bold;color:#000000''>'+ NT.Subjectsufix+'!' +'</span></td>'+      
 --'<td Style=''width:5%;text-align:center;''><span style=''font-family:Arial,Verdana,Helvetica,sans-serif;font-size:14px;font-weight:bold;color:#000000''>:</td>  
 --<td Style=''width:60%;text-align:left;''><span style=''font-family:Arial,Verdana,Helvetica,sans-serif;font-size:14px;font-weight:bold;color:#000000''>45</td> </tr>'+    
----'<tr>'+      
 ----'<td style=''width:99%;text-align:left;color:#000000;padding-bottom:3px''><span style=''font-family:Arial,Verdana,Helvetica,sans-serif;font-size:12px;line-height:1.5''>      
 ----Vehicle <b>'''+NT.VehicleDescription+'''</b> notify a <b><u>'      
 ------<a title=''Click here view in map'' href=''http://here.com/map='+cast(NT.Latitude as varchar(15) )                
 ----   --+','+cast(NT.Longitude as varchar(15) )+',14/title=Vehicle:' + NT.VehicleDescription + '  Msg:' + NT.MessageDetails +'''>'      
 ----+NT.MessageDetails+      
 ------'</a>'      
 ----'</u></b> at '+CAST(NT.NLOriginDateTime AS VARCHAR)+      
 ----'</span></td></tr>'+      
 ----'<tr><td colspan=''2'' style=''width:100%;text-align:left;color:white''><span style=''font-family:Arial,Verdana,Helvetica,sans-serif;font-size:10px''>'+NT.TimeDetails+'</span></td></tr>'+      
 --'</table>'+      
 --'</div>',      
 ----'<div class=''form-box''>'+      
 ----'<h2> Vehicle : '+NT.VehicleDescription+' / License Plate : '+ISNULL(NT.LicensePlate,'-')+'</h2>'+      
 ----'<table class=''form-tbl''>'+      
 ----'<tr><td style=''width:100%;text-align:left''><span style=''font-size:12px''><b>Message : </b>'+NT.MessageDetails+'</span></td></tr>'+      ----'</tr><tr><td style=''width:100%;text-align:left''><span style=''font-size:10px''>'+NT.TimeDetails+'</span></td></tr>'+      

 ----'</table>'+      
 ----'</div>',      
 ----'<table style=''width:250px;text-align:left''><tr><td style=''width:100px;text-align:left''><font style=''font-size:14px;font-weight:bold''>'+NT.VehicleDescription+'</font><td>'+      
 ----'<td style=''width:150px;text-align:left''><font style=''font-size:12px''> - '+NT.MessageDetails+'</font></td></tr>'+      
 ----'<tr><td colspan=''2'' style=''text-align:left''><font style=''text-align:left;font-size:10px''>'+NT.TimeDetails+'</font></td></tr>'+      ----'</table><hr />',      
 --@nCount =   SUM(NT.ReadCount),      
 --@vcMsgInIds = @vcMsgInIds + CAST(NT.MessageInID AS VARCHAR(60)) + ','      
 --FROM (SELECT nl.MessageInID,nl.Subjectsufix,v.VehicleDescription,v.LicensePlate,h.OriginDateTime,nl.OriginDateTime AS NLOriginDateTime,      --nl.MessageDetails,nl.VehicleID,nl.FleetID,h.StreetAddress,h.Latitude,h.Longitude,      
 --CASE WHEN DATEDIFF(HOUR,h.OriginDateTime,GETUTCDATE()) >= 1 THEN CAST(DATEDIFF(HOUR,h.OriginDateTime,GETUTCDATE()) AS VARCHAR(2))+' hours ago'      
 --WHEN DATEDIFF(MINUTE,h.OriginDateTime,GETUTCDATE()) >= 1 THEN CAST(DATEDIFF(MINUTE,h.OriginDateTime,GETUTCDATE()) AS VARCHAR(2))+' mins ago'      
 --WHEN DATEDIFF(SECOND,h.OriginDateTime,GETUTCDATE()) >= 1 THEN CAST(DATEDIFF(SECOND,h.OriginDateTime,GETUTCDATE()) AS VARCHAR(2))+' secs ago' END       
 --AS [TimeDetails],ISNULL((CASE WHEN nr.UserId > 1 THEN 0 ELSE NULL END) ,1) AS ReadCount      
 --FROM dbo.rvlfNotificationLog nl INNER JOIN rvlfMsgInHst h ON h.MessageInID=nl.MessageInID AND nl.FleetID IS NULL      
 --INNER JOIN dbo.rvlfVehicle v ON v.VehicleId=nl.VehicleID 
 --INNER JOIN dbo.rvlfUserGroupAssignment ua ON nl.UserId=ua.UserId      
 --INNER JOIN dbo.rvlfUserGroupSecurity ugs ON ugs.UserGroupId=ua.UserGroupId      
 --INNER JOIN dbo.rvlfUser u ON u.UserId = nl.UserID      
 --INNER JOIN dbo.rvlfBoxMsgInType bm ON bm.OperationTypeID=ugs.OperationTypeId AND nl.BoxMsgInTypeName=bm.BoxMsgInTypeName    
 --LEFT OUTER JOIN dbo.rvlfNotificationRead nr ON nr.MessageInId=nl.MessageInID AND nr.UserId=nl.UserID    
 --WHERE u.UserId=923 AND nl.OrganizationID=183 AND DATEDIFF(HOUR,h.OriginDateTime,GETUTCDATE()) < 24    
 ----ORDER BY h.OriginDateTime DESC  
 --) NT GROUP BY NT.MessageInID, NT.VehicleDescription,NT.MessageDetails, NT.Subjectsufix    
 -- ,NT.TimeDetails,NT.LicensePlate,NT.OriginDateTime,NT.NLOriginDateTime,NT.StreetAddress,NT.Latitude,NT.Longitude    
 --ORDER BY NT.OriginDateTime DESC 
    
 SELECT @vcNoNotifyDetails = '<div style=''padding:3px''><table class=''form-tbl'' style=''height:60px;background-color:white''>' 
							+ '<tr><td style=''width:1%;color:#1B67B2;text-align:center;vertical-align:middle'' rowspan=''2''>'
							+ '<span style=''font-family:Arial,Verdana,Helvetica,sans-serif;font-size:12px;line-height:1.5''>'
							+ '<b>No new notification</b></span></td></tr></table></div>';    

 SELECT @vcDetail = @vcDetail + --'<a href=''AlertsPage.aspx'' style=''display: block;padding:0px''>
					'<div style=''padding:3px''>'
					+ '<table class=''form-tbl'' style=''height:45px;border:1px solid #333333;background-color:' 
					+ (CASE WHEN NT.Subjectsufix='Critical' THEN '#FFEAEA;border-color:#AE6A5F''>' 
							WHEN NT.Subjectsufix='Warning' THEN '#FDF6C4;border-color:#D3B56F''>' 
							ELSE '#E1F5FA;border-color:#6B879F''>' END) 
							+ '<tr><td style=''width:20%;text-align:center;vertical-align:middle'' ><img style=''height:20px'' src='''
					+ (CASE WHEN NT.Subjectsufix='Critical' THEN '..\images\icnNearingPercentage.png'' />'    
							WHEN NT.Subjectsufix='Warning' THEN '..\images\icnNotifyOn.png'' />'    
							ELSE '..\images\icn-notify.gif'' />' END)+ '</td>' 
								 + '<td style=''width:25%;text-align:left;vertical-align:middle''><span style=''font-family:Arial,Verdana,Helvetica,sans-serif;font-size:14px;font-weight:bold;color:#000000''>'
								 + NT.Subjectsufix + '</span></td>' 
								 + '<td Style=''width:5%;text-align:center;vertical-align:middle''><span style=''font-family:Arial,Verdana,Helvetica,sans-serif;font-size:14px;font-weight:bold;color:#000000''>:</td>
									<td Style=''width:25%;text-align:left;vertical-align:middle''><span style=''font-family:Arial,Verdana,Helvetica,sans-serif;font-size:14px;font-weight:bold;color:#000000''>'
					+ CAST((CASE WHEN NT.Subjectsufix='Critical' THEN SUM(Critical) 
							WHEN NT.Subjectsufix='Warning' THEN SUM(Warning) 
							ELSE SUM(notify) END) as varchar(MAX))+'</td></tr></table></div>',	--</a>',   
		@nCount = @nCount + SUM(NT.ReadCount),    
		@vcMsgInIds = STUFF((SELECT ', ' + CAST(MessageInID as varchar(100)) FROM @tbl b WHERE b.Readcount = 1 FOR XML PATH('')), 1, 2, '') --WHERE b.Subjectsufix = NT.Subjectsufix --coalesce(@vcMsgInIds +',','') + CAST(NT.MessageInID AS VARCHAR(60)) 
 FROM	@TBL NT 
 GROUP	BY NT.Subjectsufix,Orderby 
 ORDER	BY Orderby

 SELECT (CASE WHEN @nCount < 0 THEN @vcNoNotifyDetails 
			  WHEN @vcDetail IS NULL THEN @vcNoNotifyDetails 
			  WHEN LEN(@vcDetail) < 1 THEN @vcNoNotifyDetails 
			  ELSE @vcDetail END) AS Template, @nCount AS NotificationCount, @vcMsgInIds AS MsgInIds    
     
SET NOCOUNT OFF    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetNotificationList]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetNotificationList]          
AS          
/******************************************************************************/          
-- Name  : rvlf_sp_GetNotificationList          
-- Description : To get the notification list for email and SMS          
-- Author  : M. Jebamalai Jaya Chitra          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : 14-Nov-2009 MJJC Created initial version          
--    : 19-Aug-2010 LK   Removed the Vehicle Display Name          
--    : 22-Dec-2010 VN Restricted the SMS notification due to issue          
--    : 29-Dec-2010 TSK Removed "View in Map" SMS option for US Embassy          
--    : 27-Mar-2013 SS Organization expires check before sending the notification  
--    : 07-Dec-2016 to replace the map URL at 3 place by jayaram.     
/******************************************************************************/          
BEGIN          
          
 SELECT DISTINCT n.MessageInID,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,           
  n.CanSendEmail, n.IsMailSent, n.CanSendSMS, n.IsSMSSent,n.UserID,n.UserName as DisplayName,n.Email,n.MobileNo,n.OrganizationID,dbo.rvlf_fn_getsmssettings(NULL) as SMSsettings,       
  '' AS StreetAddress,'' as Speed,h.BoxId, n.BoxMsgInTypeName as BoxMsgInTypeDesc, n.VehicleID,n.VehicleDescription as VehicleName,n.VehicleDescription as EquipmentName,n.VehicleDescription,n.FleetID, n.FleetName,
  n.LicensePlate, n.Subjectsufix,n.Duration, n.MessageDetails,mt.MessageTemplate,aCM.ControllerName
  FROM rvlfNotificationLog n
		INNER JOIN rvlfMsgInHst h ON n.MessageInID = h.MessageInID
		INNER JOIN rvlfMAKDevices MD ON MD.BoxId = h.BoxId      
		INNER JOIN adrControllerMaster aCM ON aCM.ControllerPositionId = h.ControllerID and aCM.EquipmentId = h.BoxId AND (h.DCSIM IS NULL OR aCM.DCSIMId=h.DCSIM)
		INNER JOIN rvlfUserPreferences p On n.UserId = p.UserId
		INNER JOIN rvlfTimeZones t ON p.TimezoneId = t.TimeZoneID          
		INNER JOIN rvlfOrganization org ON org.OrganizationId = n.OrganizationId          
		INNER JOIN rvlfMsgInTemplates mt ON mt.BoxMsgInTemplateID =           
					   (CASE WHEN EXISTS (SELECT Top 1 mtm.BoxMsgInTemplateID FROM rvlfMsgInTemplates mtm WHERE mtm.BoxMsgInTypeId= h.BoxMsgInTypeID AND mtm.OrganizationID = n.OrganizationId) THEN          
							(SELECT Top 1 mtm.BoxMsgInTemplateID FROM rvlfMsgInTemplates mtm WHERE mtm.BoxMsgInTypeId=h.BoxMsgInTypeID AND mtm.OrganizationID = n.OrganizationId)          
						   WHEN EXISTS(SELECT Top 1 mtm.BoxMsgInTemplateID  FROM rvlfMsgInTemplates mtm WHERE mtm.BoxMsgInTypeId=0 AND mtm.OrganizationID = n.OrganizationId) THEN          
							(SELECT Top 1 mtm.BoxMsgInTemplateID FROM rvlfMsgInTemplates mtm WHERE mtm.BoxMsgInTypeId=0 AND mtm.OrganizationID = n.OrganizationId)
						 ELSE (SELECT Top 1 mtm.BoxMsgInTemplateID FROM rvlfMsgInTemplates mtm WHERE mtm.BoxMsgInTypeId=0 AND mtm.OrganizationID = 0)          
						END)
   WHERE CAST(n.OriginDateTime AS DATE) = CAST(GETUTCDATE() AS DATE) AND org.ExpiresOn > GETUTCDATE() AND n.CanSendEmail = 1 AND (n.IsMailSent = 0 OR n.IsMailSent IS NULL) 
		AND (NoOfEmailTries IS NULL OR NoOfEmailTries < org.TotalNoofEmailTries) and org.OrganizationId in (86,6)         
             
  SELECT DISTINCT n.MessageInID,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,
		n.CanSendEmail,n.IsMailSent, n.CanSendSMS, n.IsSMSSent,n.UserID,n.UserName as DisplayName,n.Email, n.MobileNo, n.OrganizationID, n.OrganizationID as OrdId,dbo.rvlf_fn_getsmssettings(null)as SMSsettings,
		'' AS StreetAddress,'' as Speed,h.BoxId, n.BoxMsgInTypeName as BoxMsgInTypeDesc, n.VehicleID,n.VehicleDescription as EquipmentName, n.VehicleDescription,n.FleetID, n.FleetName, n.LicensePlate,n.Subjectsufix,
		n.Duration,(n.Subjectsufix+'-' +n.MessageDetails) AS MessageDetails,mt.SMSTemplate as MessageTemplate, 
		'ESP Name: ' + n.VehicleDescription +'\n Controller Name: '+ aCM.ControllerName +'\n'+ 'Datetime: '+ CAST(DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) AS varchar(20)) + '\n Status: '+ n.Duration as Messagecontent
  FROM rvlfNotificationLog n          
       INNER JOIN rvlfMsgInHst h ON n.MessageInID = h.MessageInID          
       INNER JOIN rvlfUserPreferences p On n.UserId = p.UserId        
       INNER JOIN rvlfTimeZones t ON p.TimezoneId = t.TimeZoneID          
       INNER JOIN rvlfOrganization org ON org.OrganizationId = n.OrganizationId
	   INNER JOIN adrControllerMaster aCM ON aCM.ControllerPositionId = h.ControllerID and aCM.EquipmentId = h.BoxId AND (h.DCSIM IS NULL OR aCM.DCSIMId=h.DCSIM)
       INNER JOIN rvlfMsgInSMSTemplates mt ON mt.BoxMsgInTypeID = (CASE WHEN EXISTS(SELECT m.BoxMsgInTypeId FROM rvlfMsgInSMSTemplates m WHERE m.BoxMsgInTypeID = h.BoxMsgInTypeId) THEN h.BoxMsgInTypeID ELSE 0 END)
   WHERE CAST(n.OriginDateTime AS DATE) = CAST(GETUTCDATE() AS DATE) AND org.ExpiresOn > GETUTCDATE() AND n.CanSendSMS = 1 AND (n.IsSMSSent = 0  OR n.IsSMSSent IS NULL)
		AND (NoOfSMSTries IS NULL OR NoOfSMSTries < org.TotalNoofSMSTries) 
		and org.OrganizationId in (86,6)
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetNotificationNews]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
CREATE Procedure [dbo].[rvlf_sp_GetNotificationNews]          
-- Add the parameters for the stored procedure here  
(
@bigOrganizationID bigint = null,
 @intUserID        int = null  
 )
AS          
/****************************************************************************************/          
-- Name    : rvlf_sp_GetNotificationNews 18         
-- Description   : To get the news details          
-- Author    : ranjith N       
-- Created Date  : 16-Apr-2014          
/***************************************************************************************/          
BEGIN          
 SET NOCOUNT ON  
                     
 (SELECT top 10 row_number() over (order by NewsId Desc) as AutoNocolumn,NewsId,NewsName,NewsDescription,  
    CONVERT(varchar(20),PublishDate,106) as PublishDate      
 FROM rvlfNews                  
 WHERE (@bigOrganizationId IS NULL OR OrganizationID=@bigOrganizationId)  or OrganizationID = 1 AND                      
   [Type] <> 'Tips'  and isnull(IsPushNotification,0)  = 1   and getutcdate() <=  expirydate     
  
union all  
  
select row_number() over (order by UserFeedbackId Desc) as AutoNocolumn,UserFeedbackId as NewsId,  
  'Feedback' as NewsName, 'Your Feedback has been reviewed and replied by one of our Administrators.   
         Kindly log into your account in Trinetra portal to view the reply for your Feedback.' as NewsDescription, --FeedbackText as NewsDescription,  
  CONVERT(varchar(20),FeedbackDate,106) as PublishDate       
from rvlfUserFeedback where UserId  = @intUserID and Status = 1)  
  
ORDER BY NewsId Desc         
       
 SET NOCOUNT OFF          
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetNotifications]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetNotifications] 
/******************************************************
Stored Procedure Name	: rvlf_sp_GetNotifications
Purpose					: Retrieve all mail notifications
Created by				: Uma
Created date			: 14-Jul-09
Updated by				: 
Updated date			: 
*******************************************************/

@NotificationId		int		= Null

AS

BEGIN	
	
	SELECT * from rvlfNotifications
	WHERE 
	((@NotificationId is Null) or (NotificationID=@NotificationId) or (@NotificationId = 0))
	ORDER BY NotificationName ASC

END
-- rvlf_sp_GetNotifications Null


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetNotificationType]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 create proc [dbo].[rvlf_sp_GetNotificationType]
 as
 begin
 select * from rvlfNotificationListTypes
 end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOdometerReading]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetOdometerReading]        
        
@Vid varchar(12) = NULL,        
@Mode BIGINT =NULL        
        
AS        
/******************************************************************************/        
-- Name  : [rvlf_sp_GetOdometerReading]40,2        
-- Description : To get the fuel details        
--    :          
-- Author  : Kapil.        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--    : 07-May-2014 Created Intial Version         
/******************************************************************************/        
          
DECLARE @FV bigint        
DECLARE @FC bigint        
DECLARE @MAXODO varchar        
        
BEGIN        
         
if(@Mode =1)        
         
 BEGIN        
         
  set @FV=(select MAX(Odometer) from rvlfFuelVehicle where VehicleId=@Vid AND  IsDelete =0)           
        
  select max(odo) as Odometer from (SELECT @FC as ODO union SELECT @FV as ODO)U           
         
  select VehicleDescription,VehicleId from rvlfVehicle where VehicleId = @Vid 
                  
  END      
  ELSE      
  BEGIN   
   --Set @FC=(select MAX(Odometer) from rvlfFuelContainer where RefgId=@Vid AND IsDelete =0)          
          
   --select max(odo) as Odometer from (SELECT @FC as ODO union SELECT @FV as ODO)U         
   select MAX(Odometer) as Odometer from rvlfFuelContainer where RefgId=@Vid AND IsDelete =0  
   select VehicleDescription,v.VehicleId from rvlfVehicle V    
   inner join rvlfRefrigeratorAssignmt RA on  V.VehicleId=RA.VehicleId    
   where RA.RefgId = @Vid         
          
 END        
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOfficeDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetOfficeDetails]  
 @bigLocationId bigint=null  
   
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_GetOfficeDetails]1,1  
-- Description : To get the office details  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 17-Feb-2010 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
  
 --SELECT LocationId,LocationName  FROM rvlfOfficeLocation WHERE @bigLocationId IS NULL OR LocationId=@bigLocationId   
 SELECT OrganizationId as AddressId,Address as AddressName  FROM rvlfOrganization WHERE @bigLocationId IS NULL OR @bigLocationId='' OR OrganizationId=@bigLocationId  
   
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrganization]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetOrganization]    
 @bigOrganizationID bigint = null,    
 @vcOrganizationName varchar(200)= null,    
 @vcOrganizationDisplayName varchar(20) = null,    
 @vcOrganizationCode varchar(5) = null,    
 @vcVATNumber varchar(20) = null,    
 @vcAddress varchar(200) = null,    
 @vcCityName varchar(75) = null,    
 @vcStateName varchar(75) = null,     
 @bigCountryID bigint = null,     
 @vcPhoneNo varchar(20) = null,    
 @vcMobileNo varchar(15) = null,    
 @vcWebsiteURL varchar(150) = null,    
 @vcOrganizationEmailID varchar(200) = null,    
 @vcDescription varchar(250) = null,    
 @vcLogoName varchar(150) = null,    
 @siMapGroupId smallint = null,    
 @vcContactPerson varchar(100) = null,    
 @vcDesignation varchar(100) = null,    
 @vcContactEmailID varchar(200) = null,    
 @vcContactPhoneno varchar(20) = null,    
 @dtExpiresOn datetime = null,    
 @bigProcessedBy bigint = null, -- Holds CreatedBy if new else ModifiedBy    
 @dtProcessedOn datetime = null, -- Holds CreatedDate if new else ModifiedDate,
 @bigQueryingUser bigint=NULL    
AS    
/******************************************************************************/    
-- Name  : rvlf_sp_GetOrganization 6    
-- Description : To gets the details of the organization    
-- Author  : M. Jebamalai Jaya Chitra.    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 11-Nov-2009 MJJC Created Intial Version     
-- Updated by : V.Narayanasamy on 25-Nov-2009 for getting organization setting details    
--            : 3-Dec-2009 for getting Date as null format.   
--            : 18-Sep-2010 for getting Logo Option Details. 
--            : 05-Aug-2011 Ranjith Date format included
/******************************************************************************/    
BEGIN    
 SET NOCOUNT ON     
 
  DECLARE @ConversionFactor decimal(18,2) = 1.0  

     
  SELECT @ConversionFactor = CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 END
  FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz  
  ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser 
 
  SELECT     
   g.OrganizationId, g.OrganizationName, g.OrganizationDisplayName, g.OrganizationCode,    
   g.VATNumber, g.Address, g.CityName, g.StateName, g.CountryID, g.PhoneNo,g.MobileNo,    
   g.WebsiteURL, g.OrganizationEmailID, g.Description, g.LogoName, g.MapGroupId,    
   g.ContactPerson, g.Designation, g.ContactEmailID, g.ContactPhoneno,(SELECT COUNT(VehicleId) FROM rvlfVehicle WHERE @bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId =@bigOrganizationID )AS NoOfVehicles,  
   g.ExpiresOn as ExpiresOn,g.TotalNoofEmailTries,g.TotalNoofSMSTries,g.NoOfFleet,    
   g.NoOfVehicles,g.NoOfUsers,g.LockIP,g.IPLockDuration,g.EnforcePasswordPolicy,g.CngOnFirstLogin,    
   g.PwdMinCharacters,g.LockUser,g.IPTries,g.LockUserTries,c.CountryName,g.OrgDistance Distance    
  FROM rvlfOrganization g  INNER JOIN rvlfCountry c ON g.CountryId = c.CountryId    
    WHERE    
   (@vcOrganizationName IS NULL OR @vcOrganizationName='' OR g.OrganizationName = @vcOrganizationName)     
   AND (@vcOrganizationCode IS NULL OR @vcOrganizationCode='' OR g.OrganizationCode = @vcOrganizationCode)    
   AND (@vcOrganizationDisplayName IS NULL OR @vcOrganizationDisplayName='' OR g.OrganizationDisplayName = @vcOrganizationDisplayName)    
   AND (@vcVATNumber IS NULL OR @vcVATNumber='' OR g.VATNumber = @vcVATNumber)    
   AND (@vcAddress IS NULL OR @vcAddress='' OR g.[Address] = @vcAddress)    
   AND (@vcCityName IS NULL OR @vcCityName='' OR g.CityName = @vcCityName)    
   AND (@vcStateName IS NULL OR @vcStateName='' OR g.StateName = @vcStateName)    
   AND (@bigCountryID IS NULL OR @bigCountryID='' OR g.CountryId = @bigCountryID)    
   AND (@vcPhoneNo IS NULL OR @vcPhoneNo='' OR g.PhoneNo = @vcPhoneNo)    
   AND (@vcMobileNo IS NULL OR @vcMobileNo='' OR g.MobileNo = @vcMobileNo)    
   AND (@vcWebsiteURL IS NULL OR @vcWebsiteURL='' OR g.WebsiteURL = @vcWebsiteURL)    
   AND (@vcOrganizationEmailID IS NULL OR @vcOrganizationEmailID='' OR g.OrganizationEmailID = @vcOrganizationEmailID)    
   AND (@vcDescription IS NULL OR @vcDescription='' OR g.[Description] = @vcDescription)    
   AND (@vcLogoName IS NULL OR @vcLogoName='' OR g.LogoName = @vcLogoName)    
   AND (@siMapGroupId IS NULL OR @siMapGroupId='' OR g.MapGroupId = @siMapGroupId)    
   AND (@vcContactPerson IS NULL OR @vcContactPerson='' OR g.ContactPerson = @vcContactPerson)    
   AND (@vcDesignation IS NULL OR @vcDesignation='' OR g.Designation = @vcDesignation)    
   AND (@vcContactEmailID IS NULL OR @vcContactEmailID='' OR g.ContactEmailID = @vcContactEmailID)    
   AND (@vcContactPhoneno IS NULL OR @vcContactPhoneno='' OR g.ContactPhoneNo = @vcContactPhoneno)    
   AND (@dtExpiresOn IS NULL OR @dtExpiresOn='' OR g.ExpiresOn = @dtExpiresOn)    
   AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR g.OrganizationId= @bigOrganizationID)    
       
       
  SELECT PM.PartnerId FROM rvlfOrganization G    
    LEFT OUTER JOIN rvlfPartnerMaster PM ON PM.OrganizationId=G.OrganizationId       
   WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR G.OrganizationId=@bigOrganizationID )   
     
  SELECT L.LogoOptionID FROM rvlfOrganizationLogoOption O   
    LEFT OUTER JOIN rvlfLogoOption L On L.LogoOptionID = O.LogoOptionID       
   WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR O.OrganizationId=@bigOrganizationID )   
     
   -- Added For Getting Package Datails (V.Muthukumaravadivel)  
     
   SELECT PackageId,CONVERT(VARCHAR(50),PurchasedOn,103) AS PurchasedOn ,CONVERT(VARCHAR(50),ExpiresOn,103) AS ExpiresOn FROM  rvlfOrganizationPackage   
   WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationID=@bigOrganizationID AND IsActive='True')   
       
 SET NOCOUNT OFF    
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrganizationContactDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetOrganizationContactDetails]

@bigOrganizationId bigint = null

AS
/******************************************************************************/
--	Name		:	[rvlf_sp_GetOrganizationContactDetails]
--	Description	:	To get the CUSTOMER details
--				:   Pass the values to @bigEmployeeID 
--	Author		:	Kapil.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	22-Aug-2013	Kapil Created Intial Version 
/******************************************************************************/
BEGIN

 --select ContactEmailID,ContactPerson from rvlfOrganization where LockUser =0 --and OrganizationId = @bigOrganizationId
  
 SELECT OrganizationId,
  -- ROW_NUMBER()OVER(Partition By OrganizationId Order By ContactName) as OrgRowID, 
    ContactName as ContactPerson, 
    EmailId as Email,
    'Top Management' as UserGroup,
    0 as  UserGroupId,  
    OrganizationDisplayName
     
FROM 
( 
SELECT rvlfOrganization.OrganizationId,OrganizationDisplayName,ContactPerson as ContactPerson1, ContactEmailID as ContactEmailID1, ContactPerson2, ContactEmailID2,ContactPerson3, ContactEmailID3,ContactPerson4, ContactEmailID4,ContactPerson5, ContactEmailID5 ,ContactPerson6, ContactEmailID6  --, Supplier3, City1, City2, City3 
FROM rvlfOrganization inner join rvlfOrganizationPackage OP on rvlfOrganization.OrganizationId = OP.OrganizationID  where LockUser =0  AND OP.IsActive =1 AND OP.ExpiresOn > CONVERT(DATE,GETUTCDATE())-- and Op.OrganizationId NOT in(1,6) 

) Main

UNPIVOT 
( 
ContactName FOR contact IN (ContactPerson1, ContactPerson2,ContactPerson3,ContactPerson4,ContactPerson5,ContactPerson6) 
) Sup

UNPIVOT 
( 
EmailId For email IN (ContactEmailID1, ContactEmailID2, ContactEmailID3,ContactEmailID4,ContactEmailID5,ContactEmailID6) 
) Ct


WHERE RIGHT(contact,1) =  RIGHT(email,1)

--and EmailId not like '%Pra%'

--and EmailId not like '%internal%'

--and EmailId not like '%jaya%' 

and Ct.ContactName <>''
and EmailId <>'' 

union all

SELECT OrganizationId,   
  -- ROW_NUMBER()OVER(Partition By OrganizationId Order By ContactName) as OrgRowID, 
    ContactName as ContactPerson, 
    EmailId as Email,
   UserGroupName,
   UserGroupId,
   OrganizationDisplayName
     
FROM 
(     
 select U.UserName as ContactPerson1,U.Email as ContactEmailID1,UserGroupName,UG.UserGroupId,OrganizationDisplayName,O.OrganizationId 
 from rvlfOrganization o 
 right join rvlfUser U on o.OrganizationId = U.OrganizationId 
 INNER JOIN rvlfUserGroupAssignment UA on U.UserId = UA.UserId 
 INNER JOIN rvlfUserGroup UG on UA.UserGroupId = UG.UserGroupId
 inner join rvlfOrganizationPackage OP on o.OrganizationId = OP.OrganizationID
 where U.IsActive =1 and U.IsDelete =0 and o.LockUser=0 and U.UserName<>'hidden' and UG.UserGroupName like '%Security Admin%'
 AND OP.IsActive =1 AND OP.ExpiresOn > CONVERT(DATE,GETUTCDATE()) --and  o.OrganizationId not in(1,6)-- and u.UserId in (18,12,52,94,140)
) Main

UNPIVOT 
( 
ContactName FOR contact IN (ContactPerson1) 
) Sup


UNPIVOT 
( 
EmailId For email IN (ContactEmailID1) 
) Ct

WHERE RIGHT(contact,1) =  RIGHT(email,1)

--and EmailId not like '%Pra%'

--and EmailId not like '%internal%'

--and EmailId not like '%jaya%' 

and Ct.ContactName <>''
and EmailId <>'' 
--and UserGroupName like '%Security Admin%' 

order by OrganizationDisplayName 

END





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrganizationList]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetOrganizationList]
AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetOrganizationList
--	Description	:	To get the OTA commands from the messages out.
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	05-Sep-2009	MJJC	Created Intial Version 
--				:	21-Dec-2009	VN	for getting values order by organization name
/******************************************************************************/
BEGIN
	SELECT * FROM rvlfOrganization WHERE OrganizationId IN (1,6,86,132)
	ORDER BY OrganizationDisplayName 
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrganizationModules]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetOrganizationModules]  
 @bigOrganizationID bigint,  
 @bigUserGroupID bigint = null,  
 @bitIsAnglerAdmin bit = 0  
AS  
  
/******************************************************************************/  
-- Name  : rvlf_sp_GetOrganizationModules 86,149,0  
-- Description : To get the Modules and Operations of the particular Module  
-- Author  : M. Jebamalai Jaya Chitra  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 01-Dec-2009 MJJC Created Intial Version   
--	  : 29-JUL-2011 Get module id if parent module id is not null
/******************************************************************************/  
BEGIN  
SET NOCOUNT ON   
 DECLARE @vcClassNamesOfModules varchar(max)  
 IF @bitIsAnglerAdmin = 0  
  BEGIN  
   SELECT * FROM rvlfModule WHERE ModuleID IN   
   (SELECT distinct CASE WHEN M.ParentModuleId IS NOT NULL THEN M.ParentModuleId ELSE M.ModuleID END AS MODULEID FROM rvlfUserGroupSecurity UG
	INNER JOIN rvlfModule M ON M.ModuleID=UG.ModuleId  WHERE UserGroupId=@bigUserGroupID )  
   --(SELECT distinct ModuleID FROM rvlfPackageOperations WHERE PackageId =  
   --(SELECT PackageId FROM rvlfOrganizationPackage WHERE OrganizationID = @bigOrganizationID AND IsActive = 1))  
   AND ParentModuleId IS Null and PagePath IS NOT NULL Order By DisplayOrder ASC  
     
   SELECT @vcClassNamesOfModules = ISNULL(@vcClassNamesOfModules + ',','') + ClassName  
    FROM rvlfModule WHERE ModuleID IN   
     (SELECT distinct ModuleID FROM rvlfUserGroupSecurity WHERE UserGroupId = @bigUserGroupID)  
      AND ParentModuleId IS Null and PagePath IS NOT NULL Order By DisplayOrder ASC  
  END  
 ELSE  
  BEGIN  
   SELECT * FROM rvlfModule WHERE ParentModuleId IS Null and PagePath IS NOT NULL Order By DisplayOrder ASC  
  
   SELECT @vcClassNamesOfModules = ISNULL(@vcClassNamesOfModules + ',','') + ClassName  
    FROM rvlfModule WHERE ParentModuleId IS Null and PagePath IS NOT NULL Order By DisplayOrder ASC  
  END  
 SELECT @vcClassNamesOfModules  
SET NOCOUNT OFF  
END  
select * from rvlfModule  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrganizationModules_test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetOrganizationModules_test]  
 @bigOrganizationID bigint,  
 @bigUserGroupID bigint = null,  
 @bitIsAnglerAdmin bit = 0  
AS  
  
/******************************************************************************/  
-- Name  : rvlf_sp_GetOrganizationModules_test 183,314,0  
-- Description : To get the Modules and Operations of the particular Module  
-- Author  : M. Jebamalai Jaya Chitra  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 01-Dec-2009 MJJC Created Intial Version   
--	  : 29-JUL-2011 Get module id if parent module id is not null
/******************************************************************************/  
BEGIN  
SET NOCOUNT ON   
 DECLARE @vcClassNamesOfModules varchar(max)  
 IF @bitIsAnglerAdmin = 0  
  BEGIN  
   SELECT * FROM rvlfModule WHERE ModuleID IN   
   (SELECT distinct CASE WHEN M.ParentModuleId IS NOT NULL THEN M.ParentModuleId ELSE M.ModuleID END AS MODULEID FROM rvlfUserGroupSecurity UG
	INNER JOIN rvlfModule M ON M.ModuleID=UG.ModuleId  WHERE UserGroupId=@bigUserGroupID )
   --(SELECT distinct ModuleID FROM rvlfPackageOperations WHERE PackageId =  
   --(SELECT PackageId FROM rvlfOrganizationPackage WHERE OrganizationID = @bigOrganizationID AND IsActive = 1))  
   AND ParentModuleId IS Null and PagePath IS NOT NULL  OR ModuleID IN (53) Order By DisplayOrder ASC  
     
   SELECT @vcClassNamesOfModules = ISNULL(@vcClassNamesOfModules + ',','') + ClassName  
    FROM rvlfModule WHERE ModuleID IN   
     (SELECT distinct ModuleID FROM rvlfUserGroupSecurity WHERE UserGroupId = @bigUserGroupID)  
      AND ParentModuleId IS Null and PagePath IS NOT NULL Order By DisplayOrder ASC  
  END  
 ELSE  
  BEGIN  
   SELECT * FROM rvlfModule WHERE ParentModuleId IS Null and PagePath IS NOT NULL Order By DisplayOrder ASC  
  
   SELECT @vcClassNamesOfModules = ISNULL(@vcClassNamesOfModules + ',','') + ClassName  
    FROM rvlfModule WHERE ParentModuleId IS Null and PagePath IS NOT NULL Order By DisplayOrder ASC  
  END  
 SELECT @vcClassNamesOfModules  
SET NOCOUNT OFF  
END  
select * from rvlfModule 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrganizationMSGDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetOrganizationMSGDetails]  
 @dtStartDate  DateTime=null,  
 @dtEndDate   DateTime=Null,   
 @bigOrganizationID  bigint = null,  
 @bigFleetID   bigint = Null,  
 @bigVehicleID  bigint = Null,  
 @intBoxMsgInTypeId int  = null,  
 @intBoxCmdOutTypeID int  = Null,   
 @MobileNo   nvarchar(15)=Null,  
 @bigQueryingUser bigint = 0,  
 @IsMessageIn  bit=0,  
 @IsMessageOut  bit=0,  
 @IsEmail   bit=0,  
 @IsSMS    bit=0   
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_GetOrganizationMSGDetails]'2009-07-01 00:00:00','2010-07-31 00:00:00',0,0,0,0,0,null,17  
-- Description : To get the organization overall msg sent,recived details.  
-- Author  : S.Jeyanthi  
-- Company  : Angler Technologies.  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 10-Jun-2010 VN Created Intial Version   
--    : 29-Jul-2010 SJ Included Email and SMS Messages  
/******************************************************************************/  
BEGIN  
 --IF @bigFleetID IS NULL  
 -- BEGIN  
 --  SELECT @bigFleetID=FleetID from rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1  
 -- END  
 DECLARE @HoursToBeAdded INT = 0  
 DECLARE @MinsToBeAdded INT = 0  
   
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded     
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz  
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser  
   
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))  
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))   
  
 DECLARE @tblCommand TABLE(OrganizationID bigInt,MessageIn bigint,MessageOut bigInt,AcknowledgedMsg bigInt,UnAcknowledgedMsg bigInt,Aborted bigInt,Email bigint,SMS bigint)  
  
IF(@IsMessageIn = 0 AND @IsMessageOut =0 AND @IsEmail =0 AND @IsSMS=0)  
 BEGIN  
  INSERT INTO @tblCommand (OrganizationID,MessageOut,AcknowledgedMsg,UnAcknowledgedMsg,Aborted)   
  SELECT OrganizationID,(CASE WHEN MessageOut>0 THEN MessageOut ELSE 0 END )AS MessageOut,   
      (CASE WHEN AcknowledgedMsg>0 THEN AcknowledgedMsg ELSE 0 END)AS AcknowledgedMsg,   
      (CASE WHEN UnAcknowledgedMsg>0 THEN UnAcknowledgedMsg ELSE 0 END)AS UnAcknowledgedMsg,  
    (ISNULL(MessageOut,0) - (ISNULL(AcknowledgedMsg,0) + ISNULL(UnAcknowledgedMsg,0))) 'Aborted'       
    FROM(      
    SELECT V.OrganizationId,COUNT(mo.BoxId)as MessageOut,  
        SUM(CASE WHEN mo.Acknowledged=1 THEN 1 END)AS AcknowledgedMsg,  
        SUM(CASE WHEN mo.Acknowledged=0 THEN 1 END)AS UnAcknowledgedMsg  
      FROM rvlfVehicle  v      
       INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId   
       INNER JOIN rvlfBoxSETtings bs ON bs.BoxId=va.BoxId         
       LEFT OUTER JOIN rvlfMsgOutHst mo ON MO.BoxId=bs.BoxId   
         
      WHERE ((@bigOrganizationID IS NULL) OR  (@bigOrganizationID =0) OR (v.OrganizationId=@bigOrganizationID))  
      AND ((@intBoxCmdOutTypeID is null) or (@intBoxCmdOutTypeID =0) Or (mo.BoxCmdOutTypeID=@intBoxCmdOutTypeID))  
      AND ((@bigVehicleID is null) or (@bigVehicleID =0) Or (V.VehicleId=@bigVehicleID))  
      AND (SentDateTime between  @dtStartDate and @dtEndDate)        
      GROUP BY V.OrganizationId    
    )as a   
     
  UPDATE t  SET MessageIn=B.Msg  FROM @tblCommand t  
  INNER JOIN (SELECT B.OrganizationID,Count(H.BoxId) as Msg FROM rvlfMsgInHst H   
    INNER JOIN rvlfBoxId B on B.BoxId =H.BoxId   
    INNER Join rvlfBoxMsgInType BM on BM.BoxMsgInTypeId =H.BoxMsgInTypeId   
    INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = H.BoxID           
    INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID   
    WHERE ((@bigOrganizationID IS NULL) OR (@bigOrganizationID =0) OR (B.OrganizationId=@bigOrganizationID))   
    AND ((@intBoxMsgInTypeID is null) or (@intBoxMsgInTypeID =0) Or (H.BoxMsgInTypeId=@intBoxMsgInTypeID))  
    AND ((@bigVehicleID is null) or (@bigVehicleID =0) Or (V.VehicleId=@bigVehicleID))  
    AND (OriginDateTime between @dtStartDate and @dtEndDate)   
    GROUP By B.OrganizationID) B on B.OrganizationId=t.OrganizationID  
  
   UPDATE t  SET Email=N.Email  FROM @tblCommand t  
   INNER JOIN (SELECT N.OrganizationID,Count(IsMailSent) Email FROM rvlfNotificationLog N   
    Where ((@bigOrganizationID is Null) OR  (@bigOrganizationID =0) OR (N.OrganizationId =@bigOrganizationID))  
    AND ((@bigFleetID Is Null) OR (@bigFleetID =0) OR (FleetID =@bigFleetID))  
    AND ((@bigVehicleID is Null) Or (@bigVehicleID =0) OR (VehicleID =@bigVehicleID))  
    AND (EmailProcessedDate between @dtStartDate and @dtEndDate)  
    GROUP By N.OrganizationID) N on N.OrganizationId=t.OrganizationID  
  
   UPDATE t  SET SMS=NS.SMS  FROM @tblCommand t  
   INNER JOIN (SELECT N.OrganizationID,Count(IsSmsSent) SMS FROM rvlfNotificationLog N   
    Where ((@bigOrganizationID is Null) OR  (@bigOrganizationID =0) OR (N.OrganizationId =@bigOrganizationID))  
    AND ((@bigFleetID Is Null) OR (@bigFleetID =0) OR (FleetID =@bigFleetID))  
    AND ((@bigVehicleID is Null) Or (@bigVehicleID =0) OR (VehicleID =@bigVehicleID))  
    AND (SMSProcessedDate  between @dtStartDate and @dtEndDate)   
    AND ((@MobileNo is Null) Or (@MobileNo ='') OR (MobileNo =@MobileNo))  
    GROUP By N.OrganizationID) NS on NS.OrganizationId=t.OrganizationID  
    
   SELECT t.OrganizationID,O.OrganizationName,MessageIn,MessageOut,AcknowledgedMsg,UnAcknowledgedMsg,Aborted,  
   Email,SMS,ROW_NUMBER() Over(Order By t.OrganizationId) RowID   
   FROM @tblCommand t   
   JOIN rvlfOrganization O on O.OrganizationId=t.OrganizationID  
 END  
  
ELSE  
 BEGIN  
 IF (@IsMessageIn=1)  
  BEGIN     
   SELECT '' UserName, BoxMsgInTypeDesc as MessageName,Count(H.BoxId) as MessageCount    
   FROM rvlfMsgInHst H   
   INNER JOIN rvlfBoxId B on B.BoxId =H.BoxId   
   INNER Join rvlfBoxMsgInType BM on BM.BoxMsgInTypeId =H.BoxMsgInTypeId   
   INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = H.BoxID           
   INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID     
   Where    
   ((@bigOrganizationID IS NULL) OR  (@bigOrganizationID =0) OR (B.OrganizationId=@bigOrganizationID))   
   AND ((@intBoxMsgInTypeID is null) or (@intBoxMsgInTypeID =0) Or (H.BoxMsgInTypeId=@intBoxMsgInTypeID))  
   AND ((@bigVehicleID is null) or (@bigVehicleID =0) Or (V.VehicleId=@bigVehicleID))  
   AND (OriginDateTime between @dtStartDate and @dtEndDate)   
   Group By BoxMsgInTypeDesc    
  END  
  
 IF (@IsMessageOut=1)  
  BEGIN  
   SELECT '' UserName, BoxCmdOutTypeName as MessageName,Count(mo.BoxId)as MessageCount   
      FROM rvlfVehicle  v      
       INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId   
       INNER JOIN rvlfBoxSettings bs ON bs.BoxId=va.BoxId         
       LEFT OUTER JOIN rvlfMsgOutHst mo ON MO.BoxId=bs.BoxId    
       Inner JOIN rvlfUser U ON U.UserId=mo.UserId   
       Inner Join rvlfBoxCmdOutType C on C.BoxCmdOutTypeId =mo.BoxCmdOutTypeId        
      WHERE ((@bigOrganizationID IS NULL) OR  (@bigOrganizationID =0) OR (v.OrganizationId=@bigOrganizationID))  
      AND ((@intBoxCmdOutTypeID is null) or (@intBoxCmdOutTypeID =0) Or (mo.BoxCmdOutTypeID=@intBoxCmdOutTypeID))  
      AND ((@bigVehicleID is null) or (@bigVehicleID =0) Or (V.VehicleId=@bigVehicleID))  
      AND (SentDateTime between  @dtStartDate and @dtEndDate)  
      Group By BoxCmdOutTypeName    
  END  
  
 IF (@IsEmail=1)  
  BEGIN  
   SELECT N.UserName,N.Email as MessageName, Count(MessageInID) as MessageCount  
   FROM rvlfNotificationLog N  
   INNER JOIN rvlfUser U on U.UserId=N.UserID   
   Where ((@bigOrganizationID is Null) OR  (@bigOrganizationID =0) OR (N.OrganizationId =@bigOrganizationID))  
   AND ((@bigFleetID Is Null) OR (@bigFleetID =0) OR (FleetID =@bigFleetID))  
   AND ((@bigVehicleID is Null) Or (@bigVehicleID =0) OR (VehicleID =@bigVehicleID))  
   AND (SMSProcessedDate  between @dtStartDate and @dtEndDate)   
   AND ((@MobileNo is Null) Or (@MobileNo ='') OR (N.MobileNo =@MobileNo))  
   Group By N.UserName,N.Email  
  END  
   
 IF (@IsSMS=1)  
  BEGIN  
   SELECT U.UserName,N.MobileNo as MessageName,Count(MessageInID) as MessageCount  
   FROM rvlfNotificationLog N   
   INNER JOIN rvlfUser U on U.UserId=N.UserID    
   Where ((@bigOrganizationID is Null) OR  (@bigOrganizationID =0) OR (N.OrganizationId =@bigOrganizationID))  
   AND ((@bigFleetID Is Null) OR (@bigFleetID =0) OR (FleetID =@bigFleetID))  
   AND ((@bigVehicleID is Null) Or (@bigVehicleID =0) OR (VehicleID =@bigVehicleID))  
   AND (SMSProcessedDate  between @dtStartDate and @dtEndDate)   
   AND ((@MobileNo is Null) Or (@MobileNo ='') OR (N.MobileNo =@MobileNo))  
   Group By U.UserName,N.MobileNo  
  END  
 END    
  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrganizationNew]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
      
      
CREATE  PROCEDURE [dbo].[rvlf_sp_GetOrganizationNew]          
 @bigOrganizationID bigint = null,          
 @vcOrganizationName varchar(200)= null,          
 @vcOrganizationDisplayName varchar(20) = null,          
 @vcOrganizationCode varchar(5) = null,          
 @vcVATNumber varchar(20) = null,          
 @vcAddress varchar(200) = null,          
 @vcCityName varchar(75) = null,          
 @vcStateName varchar(75) = null,           
 @bigCountryID bigint = null,           
 @vcPhoneNo varchar(20) = null,          
 @vcMobileNo varchar(15) = null,          
 @vcWebsiteURL varchar(150) = null,          
 @vcOrganizationEmailID varchar(200) = null,          
 @vcDescription varchar(250) = null,          
 @vcLogoName varchar(150) = null,          
 @siMapGroupId smallint = null,          
 @vcContactPerson varchar(100) = null,          
 @vcDesignation varchar(100) = null,          
 @vcContactEmailID varchar(200) = null,          
 @vcContactPhoneno varchar(20) = null,          
 @dtExpiresOn datetime = null,          
 @bigProcessedBy bigint = null, -- Holds CreatedBy if new else ModifiedBy          
 @dtProcessedOn datetime = null, -- Holds CreatedDate if new else ModifiedDate,      
 @bigQueryingUser bigint=NULL          
AS          
/******************************************************************************/          
-- Name  : rvlf_sp_GetOrganization 1          
-- Description : To gets the details of the organization          
-- Author  : M. Jebamalai Jaya Chitra.          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : 11-Nov-2009 MJJC Created Intial Version           
-- Updated by : V.Narayanasamy on 25-Nov-2009 for getting organization setting details          
--            : 3-Dec-2009 for getting Date as null format.         
--            : 18-Sep-2010 for getting Logo Option Details.       
--            : 05-Aug-2011 Ranjith Date format included      
/******************************************************************************/          
BEGIN          
 SET NOCOUNT ON           
       
  DECLARE @ConversionFactor decimal(18,2) = 1.0        
  DECLARE @DefaultDateFormat INT = 0      
           
  SELECT @ConversionFactor = CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 END,@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       
       
  SELECT           
   g.OrganizationId, g.OrganizationName, g.OrganizationDisplayName, g.OrganizationCode,          
   g.VATNumber, g.Address, g.CityName, g.StateName, g.CountryID, g.PhoneNo,g.MobileNo,          
   g.WebsiteURL, g.OrganizationEmailID, g.Description, g.LogoName, g.MapGroupId,             
   g.ContactPerson,g.ContactPerson2,g.ContactPerson3,g.ContactPerson4,g.ContactPerson5,g.ContactPerson6,  
   g.Designation, g.ContactEmailID,g.ContactEmailID2,g.ContactEmailID3,g.ContactEmailID4,g.ContactEmailID5,g.ContactEmailID6,              
   g.ContactPerson, g.Designation, g.ContactEmailID, g.ContactPhoneno,(SELECT COUNT(VehicleId) FROM rvlfVehicle WHERE @bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId =@bigOrganizationID )AS NoOfVehicles,        
   ISNULL(convert(varchar,g.ExpiresOn,@DefaultDateFormat), null) as ExpiresOn,      
   g.ExpiresOn as ExpiresOnSort,      
   g.TotalNoofEmailTries,g.TotalNoofSMSTries,g.NoOfFleet,          
   g.NoOfVehicles,g.NoOfUsers,g.LockIP,g.IPLockDuration,g.EnforcePasswordPolicy,g.CngOnFirstLogin,          
   g.PwdMinCharacters,g.LockUser,g.IPTries,g.LockUserTries,c.CountryName,g.OrgDistance Distance,g.OrgMapProvider,    
   (case when @bigOrganizationID = 119 then '../images/ZulkomLogo.png'  
		 when @bigOrganizationID = 179 then '../images/Niat_Emblem.jpg' 
		 when @bigOrganizationID = 86 then '../images/ador-logo.png' 
		 else ''   end) as PartnerImageURL,  
   g.CurrencyTypeId,isnull(g.OrgLang,2) as OrgLang,ISNULL(g.SMSQryCount,0)as SMSQryCount,isnull(OrgLangSettings,1) as LangSettings ,  
     ISNULL(g.NoOfLandmarks,0) as NoOfLandmarks,ISNULL(g.NoOfGeozones,0) as NoOfGeozones,ISNULL(g.NoOfUSerGroups,0) as  NoOfUSerGroups,
     g.EnableApp,g.AppExpDays,g.AppReminder1,g.AppInsDate       
   --'../images/ZulkomLogo.png'     
   --(case when @bigOrganizationID = 119 then '../images/ZulkomLogo.png' else '' end)     
   -- as PartnerImageURL --'../images/ZulkomLogo.png'      
  FROM rvlfOrganization g  INNER JOIN rvlfCountry c ON g.CountryId = c.CountryId          
    WHERE          
   (@vcOrganizationName IS NULL OR @vcOrganizationName='' OR g.OrganizationName = @vcOrganizationName)           
   AND (@vcOrganizationCode IS NULL OR @vcOrganizationCode='' OR g.OrganizationCode = @vcOrganizationCode)          
   AND (@vcOrganizationDisplayName IS NULL OR @vcOrganizationDisplayName='' OR g.OrganizationDisplayName = @vcOrganizationDisplayName)          
   AND (@vcVATNumber IS NULL OR @vcVATNumber='' OR g.VATNumber = @vcVATNumber)          
   AND (@vcAddress IS NULL OR @vcAddress='' OR g.[Address] = @vcAddress)          
   AND (@vcCityName IS NULL OR @vcCityName='' OR g.CityName = @vcCityName)          
   AND (@vcStateName IS NULL OR @vcStateName='' OR g.StateName = @vcStateName)          
   AND (@bigCountryID IS NULL OR @bigCountryID='' OR g.CountryId = @bigCountryID)          
   AND (@vcPhoneNo IS NULL OR @vcPhoneNo='' OR g.PhoneNo = @vcPhoneNo)          
   AND (@vcMobileNo IS NULL OR @vcMobileNo='' OR g.MobileNo = @vcMobileNo)          
   AND (@vcWebsiteURL IS NULL OR @vcWebsiteURL='' OR g.WebsiteURL = @vcWebsiteURL)          
   AND (@vcOrganizationEmailID IS NULL OR @vcOrganizationEmailID='' OR g.OrganizationEmailID = @vcOrganizationEmailID)          
   AND (@vcDescription IS NULL OR @vcDescription='' OR g.[Description] = @vcDescription)          
   AND (@vcLogoName IS NULL OR @vcLogoName='' OR g.LogoName = @vcLogoName)          
   AND (@siMapGroupId IS NULL OR @siMapGroupId='' OR g.MapGroupId = @siMapGroupId)          
   AND (@vcContactPerson IS NULL OR @vcContactPerson='' OR g.ContactPerson = @vcContactPerson)          
   AND (@vcDesignation IS NULL OR @vcDesignation='' OR g.Designation = @vcDesignation)          
   AND (@vcContactEmailID IS NULL OR @vcContactEmailID='' OR g.ContactEmailID = @vcContactEmailID)          
   AND (@vcContactPhoneno IS NULL OR @vcContactPhoneno='' OR g.ContactPhoneNo = @vcContactPhoneno)          
   AND (@dtExpiresOn IS NULL OR @dtExpiresOn='' OR g.ExpiresOn = @dtExpiresOn)          
   AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR g.OrganizationId= @bigOrganizationID)          
             
             
  SELECT PM.PartnerId FROM rvlfOrganization G          
    LEFT OUTER JOIN rvlfPartnerMaster PM ON PM.OrganizationId=G.OrganizationId             
   WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR G.OrganizationId=@bigOrganizationID )         
           
  SELECT L.LogoOptionID FROM rvlfOrganizationLogoOption O         
    LEFT OUTER JOIN rvlfLogoOption L On L.LogoOptionID = O.LogoOptionID             
   WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR O.OrganizationId=@bigOrganizationID )         
           
   -- Added For Getting Package Datails (V.Muthukumaravadivel)        
           
   SELECT PackageId,CONVERT(VARCHAR(50),PurchasedOn,103) AS PurchasedOn ,CONVERT(VARCHAR,ExpiresOn,@DefaultDateFormat) AS ExpiresOn FROM  rvlfOrganizationPackage         
   WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationID=@bigOrganizationID AND IsActive='True')         
             
 SET NOCOUNT OFF          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrganizationRights]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetOrganizationRights]  
 @bigModuleId bigint=null,  
 @bigOrganizationId bigint=null  
  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_GetOrganizationRights] 1,1  
-- Description : To get organization rights.  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 05-Dec-2009 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
 SELECT op.PackageId,po.ModuleID    
  FROM rvlfOrganizationPackage op  
   INNER JOIN rvlfPackageOperations po ON po.PackageId=op.PackageId  
  WHERE(@bigOrganizationId IS NULL OR @bigOrganizationId='' OR op.OrganizationID=@bigOrganizationId )  
   AND (@bigModuleId IS NULL OR @bigModuleId='' OR po.ModuleID=@bigModuleId) and op.IsActive = 1  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrganizationSolution]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetOrganizationSolution]
	@bigOrgId BIGINT
AS
/**************************************************************************************/
--	Name		:	rvlf_sp_GetOrganizationSolution
--	Description	:	To get the solution name for the organization
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	21-Feb-2010	MJJC	Joined to get the solution Details
/**************************************************************************************/
BEGIN
SET NOCOUNT ON 
			
	SELECT g.SolutionId, g.OrganizationId, s.SolutionId,s.ResourceFileName FROM rvlfOrganizationSolution g 
		INNER JOIN rvlfTrinetraSolutions s ON g.SolutionId = s.SolutionId
	WHERE g.OrganizationId = @bigOrgId

    SELECT isnull(OrgMapProvider,0) as OrgMapProvider  FROM rvlfOrganization WHERE OrganizationId = @bigOrgId    
    
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrgnizationalData]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[rvlf_sp_GetOrgnizationalData]
	@bigOrganizationID bigint = null
AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetOrgnizationalData 3
--	Description	:	To get the organizational information such as 
--					division, departments, shifts
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	27-Oct-2009	MJJC	Created Intial Version 
--	Updated by	:	V.Narayanasamy on 6-Nov-09 for getting employee details
/******************************************************************************/
BEGIN
	SELECT OrgDivisionID,OrgDivisionName FROM rvlfOrgDivision ORDER BY OrgDivisionName 
	SELECT DepartmentID,DepartmentName  FROM rvlfOrgDepartment ORDER BY DepartmentName 
	SELECT ShiftID,ShiftName  FROM rvlfOrgShifts ORDER BY ShiftName 
	SELECT distinct e.EmployeeID,e.DisplayName   
		FROM rvlfEmployee e 
			INNER JOIN rvlfUserGroup uG ON uG.UserGroupId=e.USERGROUP 
		WHERE (UserGroupId=2 OR UserGroupId=3) AND orgid=@bigOrganizationID AND IsDeleted=0 AND Available=1 ORDER BY e.DisplayName 
	SELECT UserGroupId,UserGroupName as UserGroupDesc FROM rvlfUserGroup ORDER BY UserGroupName  	
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrgStatistics_Distance]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvlf_sp_GetOrgStatistics_Distance]
(
	@bigOrganizationID bigint,
    @bigFleetID bigint = null,
	@dtStartDate datetime,
	@dtEndDate datetime,
	@bigQueryingUser bigint,
	@bigTopNos bigint
	
)   
AS 
/******************************************************************************/
--	Name		:	rvlf_sp_GetOrgStatistics_Distance 43,64,'2010-12-06 00:00:00','2010-12-06 23:00:00',62,15
--	Description	:	To get the organization statistics.
--	Author		:	S. Jeyanthi
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
/******************************************************************************/

Begin    

	DECLARE @HoursToBeAdded INT = 0
	DECLARE @MinsToBeAdded INT = 0
	DECLARE @ConversionFactor numeric (10,2) = 1.0
	DECLARE @CaptionPrefix varchar(10)
	DECLARE @intCounter int
	
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,
		   @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,
		   @CaptionPrefix = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'kms' END
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser    		   
	
	
    IF @bigFleetID IS NULL
		SELECT @bigFleetID = FleetID FROM rvlfFleet where OrganizationId = @bigOrganizationID and  IsDefault=1
		
    /***************** Distance Travelled *****************/
		DECLARE @tblUtilizationBoxes TABLE
	(
		SlNo int identity(1,1), BoxID int, VehicleDescription varchar(250), VehicleName varchar(50),
		StartOdometer bigint,MaxOdometer bigint, SetOdometer bigint,EndOdometer bigint
	)

	INSERT INTO @tblUtilizationBoxes (BoxID, VehicleName, VehicleDescription )
		SELECT distinct h.BoxId ,
			v.VehicleDescription as VehicleName,
			v.VehicleDescription 
			FROM rvlfMsgInHst h 
			INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
			INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
			INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId and fv.FleetId= @bigFleetID
		WHERE
			v.OrganizationId = @bigOrganizationID 
			AND h.OriginDateTime between @dtStartDate and @dtEndDate 
			
			

	DECLARE @dtOdometerSetDate DateTime=Null, @SetOdometer bigint=0
	DECLARE @MaxOdometer bigint=0,@StartOdometer bigint=0,@EndOdometer bigint=0
	
	
	--DECLARE @intCounter int
	SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes 
	DECLARE @intBoxID int=0
	WHILE @intCounter IS NOT NULL
		BEGIN
			
			SET @dtOdometerSetDate=NULL;SET @SetOdometer=0; SET @MaxOdometer=0;SET @StartOdometer=0; SET @EndOdometer=0;
			
			SELECT @intBoxID = BoxID FROM @tblUtilizationBoxes WHERE slno = @intCounter			
			
			SELECT TOP 1 @dtOdometerSetDate=SentDateTime, @SetOdometer=CustomProp FROM rvlfMsgOutHst						
						WHERE BoxCmdOutTypeId =14 and BoxId=@intBoxID and SentDateTime between 
						@dtStartDate and @dtEndDate order by SentDateTime desc
				
			
			IF @dtOdometerSetDate IS NOT NULL
				BEGIN
					SELECT @MaxOdometer=(SELECT TOP 1 Max(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,
							(CHARINDEX(';',CustomProp,
							CHARINDEX('Odometer=',CustomProp,1))) -
							(CHARINDEX('Odometer=',CustomProp,1)+9))) FROM rvlfMsgInHst 
						WHERE 
							BoxId = @intBoxID
							AND OriginDateTime between @dtStartDate and @dtOdometerSetDate 
							AND CustomProp LIKE '%Odometer%')						
						
				END
			
			SET @StartOdometer=(SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,
							(CHARINDEX(';',CustomProp,
							CHARINDEX('Odometer=',CustomProp,1))) -
							(CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst 
						WHERE 
							BoxId = @intBoxID
							AND OriginDateTime between @dtStartDate and @dtEndDate 
							AND CustomProp LIKE '%Odometer%'
						ORDER BY OriginDateTime ASC)						
					
			SET @EndOdometer =(SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,
							(CHARINDEX(';',CustomProp,
							CHARINDEX('Odometer=',CustomProp,1))) -
							(CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst 
						WHERE 
							BoxId = @intBoxID
							AND OriginDateTime between @dtStartDate and @dtEndDate 
							AND CustomProp LIKE '%Odometer%'
						ORDER BY OriginDateTime DESC)
			
						
			
			UPDATE @tblUtilizationBoxes SET StartOdometer=@StartOdometer,EndOdometer=@EndOdometer,
			 SetOdometer =@SetOdometer,MaxOdometer=@MaxOdometer  Where BoxID=@intBoxID		
			
			SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes WHERE SlNo < @intCounter
		END
	
	Select * from @tblUtilizationBoxes
	SELECT TOP (@bigTopNos)  BoxID, VehicleDescription, VehicleName, 
		CASE WHEN SetOdometer =0 THEN CEILING((EndOdometer - StartOdometer)*@ConversionFactor) 
		ELSE CEILING(((MaxOdometer - StartOdometer) + (EndOdometer - SetOdometer)) *@ConversionFactor) END as DistanceTravelled,
		@CaptionPrefix as CaptionPrefix
		 FROM @tblUtilizationBoxes	
		WHERE (EndOdometer - StartOdometer) >0 
		ORDER BY (EndOdometer - StartOdometer) DESC
End
	


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrgStatistics_IdlingPercentage]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvlf_sp_GetOrgStatistics_IdlingPercentage]  
(  
 @bigOrganizationID bigint,  
    @bigFleetID bigint = null,  
 @dtStartDate datetime,  
 @dtEndDate datetime,  
 @bigQueryingUser bigint,  
 @bigTopNos bigint  
)     
AS   
/******************************************************************************/  
-- Name  : rvlf_sp_GetOrgStatistics  
-- Description : To get the organization statistics.  
-- Author  : M. Jebamalai Jaya Chitra  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 30-Dec-2009 MJJC Altered the running and idling logic  
--    : 21-Feb-2010 MJJC Included default fleet checking  
--    : 23-Jun-2010 MJJC Included the Running time calculation only for the closed trips  
--    : 26-Jun-2010 MJJC Changed the running time calculation by taking only the sensor off packets  
--    :   26-Jun-2010 JS  Modified Running vs Idling Calculation the running time calculation by taking only the sensor off packets  
/******************************************************************************/  
Begin      
  
 DECLARE @HoursToBeAdded INT = 0  
 DECLARE @MinsToBeAdded INT = 0  
 DECLARE @ConversionFactor numeric (10,2) = 1.0  
 DECLARE @CaptionPrefix varchar(10)  
  
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,  
     @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,  
     @CaptionPrefix = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'kms' END  
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz  
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser  
           
    -- print 'capiton'  
    -- print @CaptionPrefix  
    --print @bigQueryingUser  
    --print @CaptionPrefix  
      
    IF @bigFleetID IS NULL  
  SELECT @bigFleetID = FleetID FROM rvlfFleet where OrganizationId = @bigOrganizationID and  IsDefault=1  
      
/***************** Organization Statistics ***************/  
 SELECT COUNT(*) as 'No of Vehicles' from rvlfVehicle where OrganizationId = @bigOrganizationID  
  
 SELECT SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0 THEN 1 ELSE 0 END) as Moving,  
  SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN 1 ELSE 0 END) as Idling,  
  SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =0 THEN 1 ELSE 0 END) as Parked FROM rvlfBoxId b  
  INNER JOIN rvlfVehicleAssignment va ON b.BoxId = va.BoxId   
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
  WHERE v.OrganizationId = @bigOrganizationID  
  
--/********************* Alarms ********************/  
 SELECT top (@bigTopNos)   
   SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) as CriticalAlarms,  
    a.BoxID,v.VehicleDescription,  
   --v.DisplayName  as VehicleName  
   v.VehicleDescription  as VehicleName  
  FROM rvlfAlarm a  
   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  WHERE   
   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND  
   (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) AND   
   ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
     a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)  
  GROUP BY a.BoxId, v.VehicleDescription,v.VehicleDescription--v.DisplayName   
  HAVING  
     SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) >0  
  ORDER BY   
  CriticalAlarms DESC  
      
--/********************* Running vs Idling ********************/  
  
  DECLARE @tblIdlingInfo table  
  (  
   BoxID int,  
   VehicleDescription varchar(50),  
   VehicleName varchar(50),  
   IdlingTime int,  
   RunningTime int  
  )  
  
  INSERT INTO @tblIdlingInfo (BoxID, VehicleDescription, VehicleName)  
   SELECT distinct h.BoxId , v.VehicleDescription,v.VehicleDescription--v.DisplayName   
   FROM rvlfMsgInHst h  
     INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId  
     INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
     INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
    WHERE h.OriginDateTime between @dtStartDate and @dtEndDate  
     AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)   
     AND (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID)      
    
  DECLARE @intCounter int  
    
  --Idling Time-------  
  DECLARE @bigIdlingDuration bigint = 0    
  DECLARE @firstIdlingOffDateTime datetime --firstignitionoff  
  DECLARE @firstIdlingOffDuration int =0  
  DECLARE @lastIdlingOnDateTime Datetime   
  DECLARE @lastIdlingOffDuration int =0  
  --End  
    
  --Running Time-------  
  DECLARE @bigTripDuration bigint = 0  
  DECLARE @firstIgnitionOffDateTime datetime --firstignitionoff  
  DECLARE @firstIgnitionOffDuration int =0   
  DECLARE @lastIgnitionOnDateTime Datetime  
  DECLARE @lastIgnitionOffDuration int =0  
      
  --End  
    
  SET nocount on  
  SELECT @intCounter = MAX(BoxID) FROM @tblIdlingInfo  
  WHILE @intCounter IS NOT NULL  
   BEGIN  
    SET @bigIdlingDuration = 0 ; SET @firstIdlingOffDateTime = null; SET @firstIdlingOffDuration = 0;  
    SET @lastIdlingOnDateTime = NULL;SET @lastIdlingOffDuration=0;  
      
    SET @bigTripDuration = 0 ; SET @firstIgnitionOffDateTime = null; SET @firstIgnitionOffDuration = 0;  
    SET @lastIgnitionOnDateTime = NULL; SET @lastIgnitionOffDuration=0;   
    --End  
      
    /************ Idling Duration ****************/  
    -- Gets the idling packet duration withing the querying period and sums it.      
    SET @bigIdlingDuration = (SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)  
     as int)), 0) FROM rvlfmsginhst where BoxId = @intCounter   
     and OriginDateTime between @dtStartDate and @dtEndDate AND BoxMsgInTypeId = 9)  
      
    --Included By Jeyanthi on 28-Jul-10  
    SET @firstIdlingOffDateTime = (SELECT TOP 1 OriginDateTime from rvlfMsgInHst where BoxId= @intCounter and BoxMsgInTypeId = 9   
      and OriginDateTime between @dtStartDate and @dtEndDate  
      order by OriginDateTime asc)    
        
    SET @lastIdlingOnDateTime =(SELECT Top 1 OriginDateTime from rvlfMsgInHst where BoxId= @intCounter and BoxMsgInTypeId = 8  
      and OriginDateTime between @dtStartDate and @dtEndDate  
      order by OriginDateTime Desc)          
      
    SET @firstIdlingOffDuration =(SELECT TOP 1 CAST(dbo.rvlf_fn_GetDuration(CustomProp,   
      BoxMsgInTypeID, BoxID, 0)as int)  
     FROM rvlfmsginhst where BoxId = @intCounter and OriginDateTime between   
      @dtStartDate and @dtEndDate  
     AND BoxMsgInTypeId = 9 order by Origindatetime)  
       
    SET @lastIdlingOffDuration= (SELECT TOP 1 CAST(dbo.rvlf_fn_GetDuration(CustomProp,   
      BoxMsgInTypeID, BoxID, 0)as int)  
     FROM rvlfmsginhst where BoxId = @intCounter and OriginDateTime between   
      @dtStartDate and @dtEndDate  
     AND BoxMsgInTypeId = 9 order by Origindatetime Desc)      
      
    IF @firstIdlingoffDuration > DATEDIFF(N,@dtStartDate,@firstIdlingOffDateTime)  
     BEGIN        
      SET @bigIdlingDuration = @bigIdlingDuration - (@firstIdlingoffDuration-DATEDIFF(N,@dtStartDate,@firstIdlingOffDateTime))  
     END      
     
    If @lastIdlingOffDuration =0  
     BEGIN        
      SET @bigIdlingDuration = @bigIdlingDuration + DATEDIFF(N,@lastIdlingOnDateTime,@dtEndDate)  
     END   
       
    UPDATE @tblIdlingInfo SET IdlingTime = @bigIdlingDuration WHERE BoxID = @intCounter  
      
    SET @bigIdlingDuration = 0  
   /*********************************************/  
     
   /************Running Time*********************/  
         
    SET @bigTripDuration = (SELECT ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,  
      CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -   
      ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0)  
      FROM rvlfMsgInHst Where BoxMsgInTypeId=3 and OriginDateTime between @dtStartDate  and @dtEndDate  
      AND BoxId = @intCounter  
      GROUP BY BoxId)   
        
    SET @firstIgnitionOffDateTime = (SELECT TOP 1 OriginDateTime from rvlfMsgInHst where BoxId= @intCounter and BoxMsgInTypeId = 3   
      and OriginDateTime between @dtStartDate and @dtEndDate  
      order by OriginDateTime asc)  
        
       
    SET @lastIgnitionOnDateTime = (SELECT TOP 1 OriginDateTime from rvlfMsgInHst where BoxId= @intCounter and BoxMsgInTypeId = 2  
      and OriginDateTime between @dtStartDate and @dtEndDate  
      order by OriginDateTime Desc)  
        
    --SELECT top 1 @firstIgnitionOffDuration = CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,  
    --  CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -   
    --  ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)  
    --  FROM rvlfMsgInHst Where BoxMsgInTypeId=3 order by Origindatetime ASC  
      
    SET @firstIgnitionOffDuration =(SELECT TOP 1 CAST(dbo.rvlf_fn_GetDuration(CustomProp,   
      BoxMsgInTypeID, BoxID, 0)as int)  
     FROM rvlfmsginhst where BoxId = @intCounter and OriginDateTime between   
      @dtStartDate and @dtEndDate  
     AND BoxMsgInTypeId = 3 order by Origindatetime Asc)   
         
    --Select Top 1 @lastIgnitionOffDuration = CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,  
    --  CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -   
    --  ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)  
    --  FROM rvlfMsgInHst Where BoxMsgInTypeId=3 order by Origindatetime Desc  
        
    SET @lastIgnitionOffDuration =(SELECT TOP 1  CAST(dbo.rvlf_fn_GetDuration(CustomProp,   
      BoxMsgInTypeID, BoxID, 0)as int)  
     FROM rvlfmsginhst where BoxId = @intCounter and OriginDateTime between   
      @dtStartDate and @dtEndDate  
     AND BoxMsgInTypeId = 2 order by Origindatetime Desc)         
      
      
    IF @firstIgnitionOffDuration > DATEDIFF(N,@dtStartDate,@firstIgnitionOffDateTime)  
     BEGIN  
      SET @bigTripDuration = @bigTripDuration - (@firstignitionoffDuration-DATEDIFF(N,@dtStartDate,@firstIgnitionOffDateTime))     
     END       
       
    If @lastIgnitionOffDuration = 0  
     BEGIN  
      SET @bigTripDuration = @bigTripDuration + DATEDIFF(N,@lastIgnitionOnDateTime,@dtEndDate)   
           
     END       
         
    UPDATE @tblIdlingInfo SET RunningTime = (@bigTripDuration) WHERE BoxID = @intCounter  
    SELECT @intCounter = MAX(BoxID) FROM @tblIdlingInfo WHERE BoxID < @intCounter  
     
   END  
     
   --Select * from @tblIdlingInfo  
   Declare @QueryingTime int=DateDiff(N,@dtstartDate,@dtendDate)  
     
   SELECT top(@bigtopnos) BoxID as BoxId, CEILING(IdlingTime / 60.00) AS IdlingTime,  
    RunningTime  AS RunningTime,  
    dbo.rvlf_fn_GetTimeFromSeconds(IdlingTime ) as IdlingTimeFormatted,  
    dbo.rvlf_fn_GetTimeFromSeconds(RunningTime * 60) as RunningTimeFormatted,  
    VehicleDescription, VehicleName,      
    --(case when RunningTime > 0 Then 100 Else 0 End) as RunningPercentage,   
    --(case when RunningTime > 0 then Ceiling((IdlingTime /(RunningTime * 60.00)) * 100 ) Else 0 End) AS IdlingPercentage      
    (case when RunningTime > 0 then (RunningTime * 100 /@QueryingTime) Else 0 End) AS RunningPercentage,  
    --(case when IdlingTime > 0 then ((IdlingTime/60) * 100 /@QueryingTime) Else 0 End) AS IdlingPercentage,  
    Ceiling((case when IdlingTime > 0 and RunningTime > 0 then ((IdlingTime) * 100 /(RunningTime * 60)) Else 0 End)) AS IdlingPercentage,  
    @QueryingTime QueryingTime, 100 as QueryingTimePercentage  
   FROM @tblIdlingInfo t  
   WHERE IdlingTime > 0 OR RunningTime > 0  
    ORDER BY RunningTime desc --t.IdlingTime Desc--  
       
   
 /**************** Speed Alerts *************/  
 SELECT top (@bigTopNos)   
   SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END) as SpeedAlerts,  
    a.BoxID,v.VehicleDescription,  
   --v.DisplayName  as VehicleName  
   v.VehicleDescription VehicleName  
  FROM rvlfMsgInHst  a  
   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  WHERE   
   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND  
   (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID)   
   AND   
   ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
     a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
  GROUP BY a.BoxId, v.VehicleDescription,v.DisplayName  
  HAVING SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END)>0  
  ORDER BY   
  --CASE WHEN   
  SpeedAlerts DESC  
    
 /***************** Distance Travelled *****************/  
  DECLARE @tblUtilizationBoxes TABLE  
 (  
  SlNo int identity(1,1), BoxID int, VehicleDescription varchar(250), VehicleName varchar(50),  
  StartOdometer bigint, EndOdometer bigint  
 )  
  
 INSERT INTO @tblUtilizationBoxes (BoxID, VehicleName, VehicleDescription )  
  SELECT distinct h.BoxId ,  
   --v.DisplayName as VehicleName ,   
   v.VehicleDescription as VehicleName,  
   v.VehicleDescription   
   FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId and fv.FleetId= @bigFleetID  
  WHERE  
   v.OrganizationId = @bigOrganizationID   
   AND h.OriginDateTime between @dtStartDate and @dtEndDate   
     
 --DECLARE @intCounter int  
 SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes   
 DECLARE @intBoxID int   
 WHILE @intCounter IS NOT NULL  
  BEGIN  
  print 'counter'  
  print @intCounter  
    
   SELECT @intBoxID = BoxID FROM @tblUtilizationBoxes WHERE slno = @intCounter  
   print 'Boxid'  
  print @intBoxID  
   UPDATE @tblUtilizationBoxes SET EndOdometer =  
    (SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,  
     (CHARINDEX(';',CustomProp,  
     CHARINDEX('Odometer=',CustomProp,1))) -  
     (CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst   
    WHERE   
     BoxId = @intBoxID  
     AND OriginDateTime between @dtStartDate and @dtEndDate   
     AND CustomProp LIKE '%Odometer%'  
    ORDER BY OriginDateTime ASC) WHERE BoxID = @intBoxID  
      
   UPDATE @tblUtilizationBoxes SET StartOdometer =  
    (SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,  
     (CHARINDEX(';',CustomProp,  
     CHARINDEX('Odometer=',CustomProp,1))) -  
     (CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst   
    WHERE   
     BoxId = @intBoxID  
     AND OriginDateTime between @dtStartDate and @dtEndDate   
     AND CustomProp LIKE '%Odometer%'  
    ORDER BY OriginDateTime DESC)  
    WHERE BoxID=@intBoxID  
   SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes WHERE SlNo < @intCounter  
  END  
  print @CaptionPrefix  
 SELECT TOP (@bigTopNos ) BoxID, VehicleDescription, VehicleName,   
  CEILING((StartOdometer - EndOdometer)*@ConversionFactor) as DistanceTravelled,  
  @CaptionPrefix as CaptionPrefix  
   FROM @tblUtilizationBoxes   
  WHERE (StartOdometer - EndOdometer) >0   
  ORDER BY (StartOdometer - EndOdometer ) DESC  
End  
 ------exec rvlf_sp_GetOrgStatistics @bigOrganizationID=N'2',@bigTopNos=N'20',@bigFleetID=N'2',@dtStartDate='2009-12-28 06:33:20',@dtEndDate='2009-12-30 06:33:20',@bigQueryingUser=N'1'  
   
 ----select sum(DATEDIFF(N, StartDate, EndDate)) from rvlfTripDetails where BoxId = 21 and StartDate between DATEADD(day, -1, SysUTCDATETIME()) and  SysUTCDATETIME()  
 ----select sum(IdlingDuration) /60 from rvlfTripDetails where BoxId = 21 and StartDate between DATEADD(day, -1, SysUTCDATETIME()) and  SysUTCDATETIME()  
 ----select TripId, DATEDIFF(N, StartDate, EndDate) from rvlfTripDetails where BoxId = 21 and StartDate between DATEADD(day, -1, SysUTCDATETIME()) and  SysUTCDATETIME() order by TripId desc  
 ----2473 179  
   
 ----Update rvlfTripDetails set IsTripClosed = 1 where TripId = 2473  
  
  
  
  
  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrgStatistics_new]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [dbo].[rvlf_sp_GetOrgStatistics_new]  
(  
 @bigOrganizationID bigint,  
 @bigFleetID bigint = null,  
 @dtStartDate datetime,  
 @dtEndDate datetime,  
 @bigQueryingUser bigint,  
 @bigTopNos bigint
 --,@bigUserID bigint
)     
AS   
/******************************************************************************/  
-- Name  : rvlf_sp_GetOrgStatistics_new 40,39,'2011-05-08 09:49:37 AM','2011-05-09 09:50:15 AM',19,3,null
-- Description : To get the organization statistics.  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 12-May-2011 VN Altered the running and idling logic  
--  Updated by  :  Ranjith - getting rowno of each chart for datatable filteration  
--  Updated date:  27-Jun-11  
/******************************************************************************/  
  
  
BEGIN      

 declare @Lang varchar(50)   
 select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser
 
  
 DECLARE @HoursToBeAdded INT = 0  
 DECLARE @MinsToBeAdded INT = 0  
 DECLARE @ConversionFactor numeric (10,2) = 1.0  
 DECLARE @CaptionPrefix varchar(10)  
 DECLARE @DefaultDateFormat INT = 0 
   

  
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,
     @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,  
     @CaptionPrefix = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'kms' END,
     @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           
    
    IF @bigFleetID IS NULL  
  SELECT @bigFleetID = FleetID FROM rvlfFleet where OrganizationId = @bigOrganizationID and  IsDefault=1  
      
/***************** Organization Statistics ******************************************************************/ 

--SELECT f.FleetId,COUNT(v.VehicleId) as 'No of Vehicles' from rvlfVehicle v INNER JOIN rvlfFleetVehicles fv
-- ON fv.VehicleId=v.VehicleId INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId
-- WHERE v.OrganizationId = @bigOrganizationID GROUP BY f.FleetId

 --select count(distinct(fv.VehicleId)) as 'No of Vehicles' from rvlfFleetUsers FU  inner join rvlfFleetVehicles fv
 --on fv.FleetId = FU.FleetId inner join rvlfFleet f on f.FleetId = fv.FleetId 
 --where FU.UserId= @bigUserID and f.OrganizationId = @bigOrganizationID
      
 --SELECT f.FleetId,SUM(CASE WHEN SUBSTRING(B.LastSensorMask,6,1) =1 and b.LastSpeed > 0 THEN 1 ELSE 0 END) as Moving,      
 -- SUM(CASE WHEN SUBSTRING(b.LastSensorMask,6,1) =1 and b.LastSpeed = 0 THEN 1 ELSE 0 END) as Idling,      
 -- SUM(CASE WHEN SUBSTRING(b.LastSensorMask,6,1) =0 THEN 1 ELSE 0 END) as Parked       
 --FROM rvlfBoxId b INNER JOIN rvlfVehicleAssignment va ON va.BoxId = b.BoxId  
 --INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId INNER JOIN rvlfFleetVehicles fv
 --ON fv.VehicleId=v.VehicleId INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId
 --WHERE B.OrganizationId = @bigOrganizationID
 -- GROUP BY f.FleetId
  declare @IsAngAdmin int 
 select @IsAngAdmin =(case when UserGroupId = 1 then 1  else 0 end) from rvlfUserGroupAssignment where UserId= @bigQueryingUser
 
 if(@IsAngAdmin=1)
 begin
  
  select count(distinct(fv.VehicleId)) as 'No of Vehicles' from rvlfFleetUsers FU  inner join rvlfFleetVehicles fv  
 on fv.FleetId = FU.FleetId inner join rvlfFleet f on f.FleetId = fv.FleetId   
 inner join rvlfVehicleAssignment VA on VA.VehicleId = FV.VehicleId  
 where f.OrganizationId =@bigOrganizationID  
   
;WITH cteVehicleStatus AS  
  
(SELECT DISTINCT(b.BoxId),b.LastSensorMask,b.LastSpeed  
FROM rvlfBoxId b INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId  
INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = va.VehicleId  
INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId INNER JOIN rvlfFleetUsers fu ON fu.FleetId=f.FleetId  
INNER JOIN rvlfUser u ON u.UserId = fu.UserId where u.OrganizationId= @bigOrganizationID)   
SELECT isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0 THEN 1 ELSE 0 END),0) as Moving,   
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN 1 ELSE 0 END),0) as Idling,   
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =0 THEN 1 ELSE 0 END),0) as Parked  FROM  
  
cteVehicleStatus  
 end
 else
 begin
  select count(distinct(fv.VehicleId)) as 'No of Vehicles' from rvlfFleetUsers FU  inner join rvlfFleetVehicles fv  
 on fv.FleetId = FU.FleetId inner join rvlfFleet f on f.FleetId = fv.FleetId   
 inner join rvlfVehicleAssignment VA on VA.VehicleId = FV.VehicleId  
 where FU.UserId= @bigQueryingUser and f.OrganizationId =@bigOrganizationID  
   
;WITH cteVehicleStatus AS  
  
(SELECT DISTINCT(b.BoxId),b.LastSensorMask,b.LastSpeed  
FROM rvlfBoxId b INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId  
INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = va.VehicleId  
INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId INNER JOIN rvlfFleetUsers fu ON fu.FleetId=f.FleetId  
INNER JOIN rvlfUser u ON u.UserId = fu.UserId WHERE u.OrganizationId = @bigOrganizationID and u.UserId=@bigQueryingUser)   
SELECT isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0 THEN 1 ELSE 0 END),0) as Moving,   
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN 1 ELSE 0 END),0) as Idling,   
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =0 THEN 1 ELSE 0 END),0) as Parked  FROM  
  
cteVehicleStatus  
 end 


  --select  
  --SUM(CASE WHEN SUBSTRING(B.LastSensorMask,6,1) =1 and b.LastSpeed > 0 THEN 1 ELSE 0 END) as Moving,      
  --SUM(CASE WHEN SUBSTRING(b.LastSensorMask,6,1) =1 and b.LastSpeed = 0 THEN 1 ELSE 0 END) as Idling,      
  -- SUM(CASE WHEN SUBSTRING(b.LastSensorMask,6,1) =0 THEN 1 ELSE 0 END) as Parked     
  --from  rvlfFleetUsers fu inner join rvlfFleetVehicles fv on  fv.FleetId=fu.FleetId
  --inner join rvlfVehicleAssignment va on va.VehicleId = fv.VehicleId
  --inner join rvlfBoxId b on b.BoxId = va.BoxId
  --where fu.UserId = @bigUserID and b.OrganizationId = @bigOrganizationID group by va.BoxId
   
 --SELECT COUNT(VehicleId) as 'No of Vehicles' from rvlfVehicle where OrganizationId = @bigOrganizationID  
  
 --SELECT SUM(CASE WHEN SUBSTRING(B.LastSensorMask,6,1) =1 and b.LastSpeed > 0 THEN 1 ELSE 0 END) as Moving,  
 -- SUM(CASE WHEN SUBSTRING(b.LastSensorMask,6,1) =1 and b.LastSpeed = 0 THEN 1 ELSE 0 END) as Idling,  
 -- SUM(CASE WHEN SUBSTRING(b.LastSensorMask,6,1) =0 THEN 1 ELSE 0 END) as Parked   
 --FROM rvlfBoxId b   
 -- WHERE B.OrganizationId = @bigOrganizationID  
  
/********************* Alarms *******************************************************************************/  
  
 --SELECT TOP (@bigTopNos) SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) as CriticalAlarms,  
 --   a.BoxID,v.VehicleDescription,     
 --  v.VehicleDescription  as VehicleName  
 -- FROM rvlfAlarm a  
 --  INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
 --  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
 --  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
 -- WHERE   
 --  (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID) AND  
 --  (@bigFleetID IS NULL OR fv.FleetId = @bigFleetID) AND   
 --  ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
 --    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)       
 -- GROUP BY a.BoxId, v.VehicleDescription,v.VehicleDescription,OrganizationId  
 -- HAVING  
 --    SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) >0  
 -- ORDER BY   
 --  CASE WHEN OrganizationId=55 THEN a.BoxId END ASC,CriticalAlarms DESC  
 select Alarms.CriticalAlarms,Alarms.BoxId,Alarms.VehicleDescription,Alarms.VehicleName, row_number() over(order by Alarms.CriticalAlarms DESC) as AlarmsRowno, 
 PasGenerateddate =dbo.rvlf_fn_DayLightSavings(GETUTCDATE(),@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate    
 from  
  (SELECT TOP (@bigTopNos) SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) as CriticalAlarms,  
    a.BoxID,v.VehicleDescription,     
  v.VehicleDescription as VehicleName
  
  FROM rvlfAlarm a  
   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  WHERE   
   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND  
   (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) AND   
   ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
     a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)       
  GROUP BY a.BoxId, v.VehicleDescription,v.VehicleDescription,OrganizationId 
  HAVING  
     SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) >0  
  ORDER BY   
   CASE WHEN OrganizationId=55 THEN a.BoxId END ASC,CriticalAlarms DESC)as Alarms    
    
  --/********************* Running vs Idling ********************/  
  
  DECLARE @tblIdlingInfo table  
  (  
   BoxID int,  
   VehicleDescription nvarchar(50),  
   VehicleName nvarchar(50),  
   IdlingTime int,  
   RunningTime int,  
   Distance int  
  )  
  DECLARE @tblmsg table  
  (     
   BoxmsgtypeId tinyint,  
   Orgindatetime datetime,  
   CustomProp varchar(600)  
  )  
  INSERT INTO @tblIdlingInfo (BoxID, VehicleDescription, VehicleName)              
    SELECT va.BoxId , v.VehicleDescription  AS VEH,v.VehicleDescription as VehicleDescription  
          FROM rvlfVehicleAssignment va   
           INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
           INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
          WHERE(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)   
           AND (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID)                       
    
  DECLARE @IntBoxLoop INT =(SELECT MIN(BoxID) FROM @tblIdlingInfo)  
    
  WHILE @IntBoxLoop IS NOT NULL  
   BEGIN  
    DECLARE @dtIsIgnitionoff DATETIME =NULL,@dtIsIdlingEnd DATETIME =NULL,@dtOdometerSetDate DATETIME=NULL,@SetOdometer BIGINT=0,  
     @MaxOdometer BIGINT=0,@StartOdometer BIGINT=0,@EndOdometer BIGINT=0;  
      
    --CHECK IF ANY SET ODOMETER COMMAND FOR THE BOXID  
    SELECT TOP 1 @dtOdometerSetDate=SentDateTime, @SetOdometer=CustomProp   
     FROM rvlfMsgOutHst        
      WHERE BoxCmdOutTypeId =14 AND BoxId=@IntBoxLoop   
       AND SentDateTime BETWEEN @dtStartDate AND @dtEndDate   
     ORDER BY SentDateTime DESC  
       
    DELETE FROM @tblmsg   
    INSERT INTO @tblmsg(BoxmsgtypeId,CustomProp,Orgindatetime)  
     SELECT BoxMsgInTypeId,CustomProp,OriginDateTime    
      FROM rvlfMsgInHst   
       WHERE BoxMsgInTypeId IN(2,3,9)          
        AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate  
        AND BoxId = @IntBoxLoop  
       ORDER BY OriginDateTime    
   
    --CHECK IF THE FIRST MSG IS IGNITION OFF OR NOT   
    IF ((SELECT TOP 1 BoxmsgtypeId FROM @tblmsg WHERE BoxmsgtypeId IN(2,3) AND CustomProp LIKE '%SENSOR_NUM=3;%')=3)  
     BEGIN       
         UPDATE @tblIdlingInfo SET RunningTime =ISNULL(RunningTime,0)+(SELECT TOP 1 DATEDIFF(SECOND,@dtStartDate,Orgindatetime) FROM @tblmsg WHERE BoxmsgtypeId =3)  
         WHERE BoxID=@IntBoxLoop   
         SELECT TOP 1 @dtIsIgnitionoff=Orgindatetime FROM @tblmsg WHERE BoxmsgtypeId =3  
           
         SELECT TOP 1 @StartOdometer=CAST(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,  
        (CHARINDEX(';',CustomProp,  
        CHARINDEX('Odometer=',CustomProp,1))) -  
        (CHARINDEX('Odometer=',CustomProp,1)+9)) AS BIGINT)   
      FROM rvlfMsgInHst     
       WHERE  BoxId=@IntBoxLoop    
        AND CustomProp LIKE '%Odometer%'   
        AND OriginDateTime BETWEEN @dtStartDate AND @dtIsIgnitionoff  
       ORDER BY OriginDateTime ASC   
     END             
    --CHECK IF THE FIRST MSG IS IDLING END OR NOT   
    IF((SELECT TOP 1 CAST(SUBSTRING (CustomProp,CHARINDEX('Idling:',CustomProp,1)+7,  
      CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,1)) -   
      (CHARINDEX('Idling:',CustomProp,1)+7)) as int) FROM @tblmsg WHERE BoxmsgtypeId=9)!=0)  
     BEGIN  
      UPDATE @tblIdlingInfo SET IdlingTime =ISNULL(IdlingTime,0)+(SELECT TOP 1 DATEDIFF(SECOND,@dtStartDate,Orgindatetime) FROM @tblmsg WHERE BoxmsgtypeId =9)  
         WHERE BoxID=@IntBoxLoop   
         SELECT TOP 1 @dtIsIdlingEnd=Orgindatetime FROM @tblmsg WHERE BoxmsgtypeId =9  
     END  
     
      --CALCULATE THE RUNNING TIME AND IDLING FOR REMAINING MSGS  
      DECLARE @intRunning int =null,@intIdling int =null  
      SELECT @intRunning= SUM(ISNULL(CAST(SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,  
      CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -   
      (CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int),0))*60  
      FROM @tblmsg   
      WHERE BoxmsgtypeId=3  
       AND (@dtIsIgnitionoff IS NULL OR @dtIsIgnitionoff='' OR Orgindatetime>@dtIsIgnitionoff)  
      GROUP BY BoxmsgtypeId  
    							
      SELECT @intIdling=SUM(ISNULL(CAST(SUBSTRING (CustomProp,CHARINDEX('Idling:',CustomProp,1)+7,  
      CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,1)) -   
      (CHARINDEX('Idling:',CustomProp,1)+7)) as int),0))    
      FROM @tblmsg   
      WHERE BoxmsgtypeId =9   
       AND (@dtIsIdlingEnd IS NULL or @dtIsIdlingEnd='' OR Orgindatetime>@dtIsIdlingEnd)  
       AND CustomProp NOT LIKE '%Idling:0;%'   
      GROUP BY BoxmsgtypeId  
      UPDATE @tblIdlingInfo SET   
     RunningTime =ISNULL(RunningTime,0)+ ISNULL(@intRunning,0),  
     IdlingTime =ISNULL(IdlingTime,0)+ISNULL(@intIdling,0)        
     WHERE BoxID =@IntBoxLoop   
       
    --CHECK IF THE LAST MSG IS IGNITION ON OR NOT  
    IF ((SELECT TOP 1 BoxmsgtypeId FROM @tblmsg WHERE BoxmsgtypeId IN(2,3) AND CustomProp LIKE '%SENSOR_NUM=3;%' ORDER BY Orgindatetime DESC)=2)  
     BEGIN  
         UPDATE @tblIdlingInfo SET RunningTime =ISNULL(RunningTime,0)+ (SELECT TOP 1 DATEDIFF(SECOND,Orgindatetime,@dtEndDate) FROM @tblmsg WHERE BoxmsgtypeId =2  AND CustomProp LIKE '%SENSOR_NUM=3;%' ORDER BY Orgindatetime DESC)  
         WHERE BoxID=@IntBoxLoop    
           
         SELECT TOP 1 @EndOdometer=CAST(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,  
        (CHARINDEX(';',CustomProp,  
        CHARINDEX('Odometer=',CustomProp,1))) -  
        (CHARINDEX('Odometer=',CustomProp,1)+9)) AS BIGINT)   
      FROM rvlfMsgInHst     
       WHERE BoxId=@IntBoxLoop    
        AND CustomProp LIKE '%Odometer%'  
        AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate   
       ORDER BY OriginDateTime DESC           
     END  
      
    --CHECK IF THE BOXID DONT HAVE ANY IGNITION ON/OFF WITH IN THE QUERING TIME.  
    IF NOT EXISTS(SELECT BoxmsgtypeId FROM @tblmsg WHERE BoxmsgtypeId IN(2,3) AND CustomProp LIKE '%SENSOR_NUM=3;%')  
     BEGIN  
      IF((SELECT COUNT(BoxmsgtypeId) FROM @tblmsg)>0)  
       BEGIN  
        IF ((SELECT TOP 1 BoxMsgInTypeId FROM rvlfMsgInHst WHERE BoxId=@IntBoxLoop AND BoxMsgInTypeId IN(2,3) AND CustomProp LIKE '%SENSOR_NUM=3;%' AND OriginDateTime <@dtStartDate ORDER BY OriginDateTime DESC)=2)  
         BEGIN  
            UPDATE @tblIdlingInfo SET RunningTime =ISNULL(RunningTime,0)+(SELECT TOP 1 DATEDIFF(SECOND,@dtStartDate,@dtEndDate))  
            WHERE BoxID=@IntBoxLoop   
         END  
       END  
     END  
       
    --CALCULATE THE DISTANCE   
    IF @dtOdometerSetDate IS NOT NULL OR @dtOdometerSetDate !=''  
    BEGIN  
     SELECT @MaxOdometer=(SELECT TOP 1 MAX(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,  
       (CHARINDEX(';',CustomProp,  
       CHARINDEX('Odometer=',CustomProp,1))) -  
       (CHARINDEX('Odometer=',CustomProp,1)+9)))   
      FROM @tblmsg    
       WHERE Orgindatetime BETWEEN @dtStartDate AND @dtOdometerSetDate   
        AND CustomProp LIKE '%Odometer%')        
        
    END  
   IF @StartOdometer IS NULL OR @StartOdometer =''  
    SELECT TOP 1 @StartOdometer=CAST(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,  
        (CHARINDEX(';',CustomProp,  
        CHARINDEX('Odometer=',CustomProp,1))) -  
        (CHARINDEX('Odometer=',CustomProp,1)+9)) AS BIGINT)   
      FROM @tblmsg    
       WHERE CustomProp LIKE '%Odometer%'  
       ORDER BY Orgindatetime ASC    
             
   IF @EndOdometer IS NULL OR @EndOdometer =''    
    SELECT TOP 1 @EndOdometer=CAST(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,  
        (CHARINDEX(';',CustomProp,  
        CHARINDEX('Odometer=',CustomProp,1))) -  
        (CHARINDEX('Odometer=',CustomProp,1)+9)) AS BIGINT)   
      FROM @tblmsg    
       WHERE CustomProp LIKE '%Odometer%'  
       ORDER BY Orgindatetime DESC      
          
   UPDATE @tblIdlingInfo SET Distance =CASE WHEN @SetOdometer =0 OR @SetOdometer IS NULL THEN   
    CEILING((@EndOdometer - @StartOdometer)*@ConversionFactor)   
    ELSE CEILING(((@MaxOdometer - @StartOdometer) + (@EndOdometer - @SetOdometer)) *@ConversionFactor) END  
   WHERE BoxID=@IntBoxLoop   
      
   SELECT @IntBoxLoop=MIN(BoxID)FROM @tblIdlingInfo WHERE BoxID>@IntBoxLoop       
    
  END  
   DECLARE @QueryingTime INT=DateDiff(MINUTE,@dtstartDate,@dtendDate)  
        
   select Idling.BoxID,Idling.IdlingTime,Idling.RunningTime,  
   Idling.IdlingTimeFormatted,Idling.RunningTimeFormatted,Idling.VehicleDescription,Idling.VehicleName,Idling.RunningPercentage,Idling.IdlingPercentage,Idling.QueryingTimePercentage,row_number() over(order by Idling.RunningTime DESC) as IdlingRowno,
   PasGenerateddate =dbo.rvlf_fn_DayLightSavings(GETUTCDATE(),@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())
 --  Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate    
   from (  SELECT TOP(@bigTopNos) BoxID,CEILING(IdlingTime / 60.00) AS IdlingTime,CEILING(RunningTime / 60.00) AS RunningTime,  
    dbo.rvlf_fn_GetTimeFromSeconds(IdlingTime) as IdlingTimeFormatted,  
    dbo.rvlf_fn_GetTimeFromSeconds(RunningTime) as RunningTimeFormatted,VehicleDescription, VehicleName,   
    (CASE WHEN RunningTime > 0 THEN (CEILING(RunningTime/60) * 100 /@QueryingTime) ELSE 0 END) AS RunningPercentage,     
    Ceiling((CASE WHEN IdlingTime > 0 AND RunningTime > 0 THEN ((IdlingTime) * 100 /(RunningTime)) Else 0 End)) AS IdlingPercentage,  
    @QueryingTime QueryingTime, 100 as QueryingTimePercentage  
   FROM @tblIdlingInfo   
   WHERE IdlingTime > 0 OR RunningTime > 0  
   ORDER BY RunningTime DESC) as Idling  
     
 /**************** Speed Alerts ****************************************************************************/  
 --SELECT TOP (@bigTopNos)   
 --  SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END) as SpeedAlerts,  
 --   a.BoxID,v.VehicleDescription,     
 --  v.VehicleDescription VehicleName  
 -- FROM rvlfMsgInHst  a  
 --  INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
 --  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
 --  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
 -- WHERE(@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID)   
 --  AND(@bigFleetID IS NULL OR fv.FleetId = @bigFleetID)   
 --  AND((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
 --    a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
 --  AND BoxMsgInTypeId=4  
 -- GROUP BY a.BoxId, v.VehicleDescription,v.DisplayName  
 -- HAVING SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END)>0  
 -- ORDER BY SpeedAlerts DESC  
   
 --Included by ranjith for Dashboard Code Optimization  
 select SpeedAlert.SpeedAlerts,SpeedAlert.BoxId,SpeedAlert.VehicleDescription,SpeedAlert.VehicleName, row_number() over(order by SpeedAlert.SpeedAlerts desc) as SpeedAlertRowno, 
 PasGenerateddate =dbo.rvlf_fn_DayLightSavings(GETUTCDATE(),@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate    
 from (SELECT top (@bigTopNos)   
   SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END) as SpeedAlerts,  
    a.BoxID, v.VehicleDescription as VehicleDescription,  
   --v.DisplayName  as VehicleName  
    v.VehicleDescription as VehicleName  
  FROM rvlfMsgInHst  a  
   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  WHERE   
   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND  
   (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID)   
   AND   
   ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
     a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
  GROUP BY a.BoxId, v.VehicleDescription,v.DisplayName
  HAVING SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END)>0  
  ORDER BY   
  --CASE WHEN   
  SpeedAlerts DESC) as SpeedAlert  
    
   
 /***************** Distance Travelled ****************************************************************/     
 select Distance.BoxID,Distance.VehicleDescription,Distance.VehicleName,Distance.DistanceTravelled,Distance.CaptionPrefix, row_number() over(order by DistanceTravelled DESC) as DistanceRowno, 
 PasGenerateddate =dbo.rvlf_fn_DayLightSavings(GETUTCDATE(),@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate
  from ( SELECT TOP (@bigTopNos) BoxID,VehicleDescription,VehicleName,Distance as DistanceTravelled,@CaptionPrefix as CaptionPrefix  
  FROM @tblIdlingInfo    
  WHERE Distance > 0  
 ORDER BY Distance DESC) as Distance

/***************** Get login active users ****************************************************************/     
SELECT COUNT(UserId)AS ActiveUsers 
FROM rvlfUserLogin 
WHERE CONVERT(DATE,LoginDateTime)=CONVERT(DATE,GETUTCDATE()) AND LogOffDateTime IS NULL
UNION ALL
SELECT COUNT(UserId) AS InternalUsers
FROM rvlfUserLogin UL 
WHERE CONVERT(DATE,LoginDateTime)=CONVERT(DATE,GETUTCDATE()) AND LogOffDateTime IS NULL AND OrgId IN(1,6)

    
   
END  
  
 /***************** Get User Prefered Chart****************************************************************/
  --SELECT distinct(UP.UserPreferedChart) from rvlfUserPreferences UP
  --INNER JOIN rvlfUserLoginDetails UL ON UL.UserId = UP.UserId
  --WHERE UP.UserId = @bigUserID
  
  
--Begin      
  
-- DECLARE @HoursToBeAdded INT = 0  
-- DECLARE @MinsToBeAdded INT = 0  
-- DECLARE @ConversionFactor numeric (10,2) = 1.0  
-- DECLARE @CaptionPrefix varchar(10)  
  
--    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,  
--     @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,  
--     @CaptionPrefix = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'kms' END  
--    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz  
--    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser           
   
   
--    IF @bigFleetID IS NULL  
--  SELECT @bigFleetID = FleetID FROM rvlfFleet where OrganizationId = @bigOrganizationID and  IsDefault=1  
      
--/***************** Organization Statistics ***************/  
-- SELECT COUNT(VehicleId) as 'No of Vehicles' from rvlfVehicle where OrganizationId = @bigOrganizationID  
  
-- SELECT SUM(CASE WHEN SUBSTRING(B.LastSensorMask,6,1) =1 and b.LastSpeed > 0 THEN 1 ELSE 0 END) as Moving,  
--  SUM(CASE WHEN SUBSTRING(b.LastSensorMask,6,1) =1 and b.LastSpeed = 0 THEN 1 ELSE 0 END) as Idling,  
--  SUM(CASE WHEN SUBSTRING(b.LastSensorMask,6,1) =0 THEN 1 ELSE 0 END) as Parked FROM rvlfBoxId b  
--  INNER JOIN rvlfBoxId va ON b.BoxId = va.BoxId     
--  WHERE va.OrganizationId = @bigOrganizationID  
  
  
------/********************* Alarms ********************/  
  
--IF(@bigOrganizationID=55)  
--BEGIN  
--SELECT top (@bigTopNos)   
--   SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) as CriticalAlarms,  
--    a.BoxID,v.VehicleDescription,  
--   --v.DisplayName  as VehicleName  
--   v.VehicleDescription  as VehicleName  
--  FROM rvlfAlarm a  
--   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
--   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
--   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
--  WHERE   
--   (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID) AND  
--   (@bigFleetID IS NULL OR fv.FleetId = @bigFleetID) AND   
--   ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
--     a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)  
       
--  GROUP BY a.BoxId, v.VehicleDescription,v.VehicleDescription--v.DisplayName   
--  HAVING  
--     SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) >0  
--  ORDER BY   
--  a.BoxId ASC,CriticalAlarms DESC  
--END   
--ELSE   
-- BEGIN  
  
-- SELECT top (@bigTopNos)   
--   SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) as CriticalAlarms,  
--    a.BoxID,v.VehicleDescription,  
--   --v.DisplayName  as VehicleName  
--   v.VehicleDescription  as VehicleName  
--  FROM rvlfAlarm a  
--   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
--   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
--   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
--  WHERE   
--   (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID) AND  
--   (@bigFleetID IS NULL OR fv.FleetId = @bigFleetID) AND   
--   ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
--     a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)  
       
--  GROUP BY a.BoxId, v.VehicleDescription,v.VehicleDescription--v.DisplayName   
--  HAVING  
--     SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) >0  
--  ORDER BY   
--  CriticalAlarms DESC  
  
-- END     
----/********************* Running vs Idling ********************/  
  
--  DECLARE @tblIdlingInfo table  
--  (  
--   BoxID int,  
--   VehicleDescription varchar(50),  
--   VehicleName varchar(50),  
--   IdlingTime int,  
--   RunningTime int  
--  )  
--  --CHECK IF THE ORGANIZATION IS DEFENSE THAN SELECT TOP 20  
--  --IF(@bigOrganizationID=55)  
--  -- BEGIN  
--  --  INSERT INTO @tblIdlingInfo (BoxID, VehicleDescription, VehicleName)  
--  --   SELECT TOP 10 va.BoxId , v.VehicleDescription,v.VehicleDescription--v.DisplayName   
--  --   FROM rvlfMsgInHst h  
--  --     INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId  
--  --     INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
--  --     INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
--  --    WHERE h.OriginDateTime between @dtStartDate and @dtEndDate  
--  --     AND (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID)   
--  --     AND (@bigFleetID IS NULL OR fv.FleetId = @bigFleetID)  
--  --    GROUP BY  va.BoxId , v.VehicleDescription,v.VehicleDescription  
--  --     ORDER BY va.BoxId   
--  -- END  
--  --ELSE  
--   --BEGIN  
--    INSERT INTO @tblIdlingInfo (BoxID, VehicleDescription, VehicleName)  
--     --SELECT distinct h.BoxId , v.VehicleDescription,v.VehicleDescription--v.DisplayName   
--     --FROM rvlfMsgInHst h  
--     --  INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId  
--     --  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
--     --  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
--     -- WHERE h.OriginDateTime between @dtStartDate and @dtEndDate  
--     --  AND (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID)   
--     --  AND (@bigFleetID IS NULL OR fv.FleetId = @bigFleetID)  
--     --  --AND h.BoxId=159  
       
--     SELECT BoxId,VEH,VehicleDescription  FROM (   
--     SELECT h.BoxId , v.VehicleDescription AS VEH,v.VehicleDescription,ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,  
--           CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -   
--           ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0)AS Runing  
--          FROM rvlfMsgInHst h  
--            INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId  
--            INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
--            INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
--           WHERE h.OriginDateTime between @dtStartDate and @dtEndDate  
--            AND (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID)   
--            AND (@bigFleetID IS NULL OR fv.FleetId = @bigFleetID)  
--            AND BoxMsgInTypeId =3  
--           GROUP BY h.BoxId , v.VehicleDescription,v.VehicleDescription,BoxMsgInTypeId        
--        )A      
--        ORDER BY Runing  DESC  
--   --END          
    
--  DECLARE @intCounter int  
    
--  --Idling Time-------  
--  DECLARE @bigIdlingDuration bigint = 0    
--  DECLARE @firstIdlingOffDateTime datetime --firstignitionoff  
--  DECLARE @firstIdlingOffDuration int =0  
--  DECLARE @lastIdlingOnDateTime Datetime   
--  DECLARE @lastIdlingOffDuration int =0  
--  --End  
    
--  --Running Time-------  
--  DECLARE @bigTripDuration bigint = 0  
--  DECLARE @firstIgnitionOffDateTime datetime --firstignitionoff  
--  DECLARE @firstIgnitionOffDuration int =0   
--  DECLARE @lastIgnitionOnDateTime Datetime  
--  DECLARE @lastIgnitionOffDuration int =0  
--  DECLARE @LastBoxMsgInTypeId int=0  
      
--  --End  
    
    
--  SET nocount on  
--  SELECT @intCounter = MAX(BoxID) FROM @tblIdlingInfo  
--  WHILE @intCounter IS NOT NULL  
--   BEGIN  
--    SET @bigIdlingDuration = 0 ; SET @firstIdlingOffDateTime = null; SET @firstIdlingOffDuration = 0;  
--    SET @lastIdlingOnDateTime = NULL;SET @lastIdlingOffDuration=0;  
      
--    SET @bigTripDuration = 0 ; SET @firstIgnitionOffDateTime = null; SET @firstIgnitionOffDuration = 0;  
--    SET @lastIgnitionOnDateTime = NULL; SET @lastIgnitionOffDuration=0; SET @LastBoxMsgInTypeId=0  
--    --End  
      
--    /************ Idling Duration ****************/  
--    -- Gets the idling packet duration withing the querying period and sums it.      
--    SET @bigIdlingDuration = (SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)  
--     as int)), 0) FROM rvlfmsginhst where BoxId = @intCounter   
--     and OriginDateTime between @dtStartDate and @dtEndDate AND BoxMsgInTypeId = 9 AND CustomProp NOT LIKE'%Idling:0;%')  
      
--    --Included By Jeyanthi on 28-Jul-10  
--    SET @firstIdlingOffDateTime = (SELECT TOP 1 OriginDateTime from rvlfMsgInHst where BoxId= @intCounter and BoxMsgInTypeId = 9   
--      and OriginDateTime between @dtStartDate and @dtEndDate  
--      order by OriginDateTime asc)    
        
--    SET @lastIdlingOnDateTime =(SELECT Top 1 OriginDateTime from rvlfMsgInHst where BoxId= @intCounter and BoxMsgInTypeId = 8  
--      and OriginDateTime between @dtStartDate and @dtEndDate  
--      order by OriginDateTime Desc)          
      
--    SET @firstIdlingOffDuration =(SELECT TOP 1 CAST(dbo.rvlf_fn_GetDuration(CustomProp,   
--      BoxMsgInTypeID, BoxID, 0)as int)  
--     FROM rvlfmsginhst where BoxId = @intCounter and OriginDateTime between   
--      @dtStartDate and @dtEndDate  
--     AND BoxMsgInTypeId = 9 order by Origindatetime)  
       
--    SET @lastIdlingOffDuration= (SELECT TOP 1 CAST(dbo.rvlf_fn_GetDuration(CustomProp,   
--      BoxMsgInTypeID, BoxID, 0)as int)  
--     FROM rvlfmsginhst where BoxId = @intCounter and OriginDateTime between   
--      @dtStartDate and @dtEndDate  
--     AND BoxMsgInTypeId = 9 order by Origindatetime Desc)      
      
--    IF @firstIdlingoffDuration > DATEDIFF(N,@dtStartDate,@firstIdlingOffDateTime)  
--     BEGIN        
--      SET @bigIdlingDuration = @bigIdlingDuration - (@firstIdlingoffDuration-DATEDIFF(N,@dtStartDate,@firstIdlingOffDateTime))  
--     END      
     
--    If @lastIdlingOffDuration =0  
--     BEGIN        
--      SET @bigIdlingDuration = @bigIdlingDuration + DATEDIFF(N,@lastIdlingOnDateTime,@dtEndDate)  
--     END   
       
--    UPDATE @tblIdlingInfo SET IdlingTime = @bigIdlingDuration WHERE BoxID = @intCounter  
      
--    SET @bigIdlingDuration = 0  
--   /*********************************************/  
     
--   /************Running Time*********************/  
         
--    SET @bigTripDuration = (SELECT ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,  
--      CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -   
--      ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0)  
--      FROM rvlfMsgInHst Where BoxMsgInTypeId=3 and OriginDateTime between @dtStartDate  and @dtEndDate  
--      AND BoxId = @intCounter  
--      GROUP BY BoxId)   
        
--    SET @firstIgnitionOffDateTime = (SELECT TOP 1 OriginDateTime from rvlfMsgInHst where BoxId= @intCounter and BoxMsgInTypeId = 3   
--      and OriginDateTime between @dtStartDate and @dtEndDate  
--      order by OriginDateTime asc)  
        
       
--    SET @lastIgnitionOnDateTime = (SELECT TOP 1 OriginDateTime from rvlfMsgInHst where BoxId= @intCounter and BoxMsgInTypeId = 2  
--      and OriginDateTime between @dtStartDate and @dtEndDate  
--      order by OriginDateTime Desc)   
        
       
       
--    SET @firstIgnitionOffDuration =(SELECT Top 1 ISNULL(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,  
--      CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -   
--      ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int),0)  
--      FROM rvlfMsgInHst Where BoxId = @intCounter and OriginDateTime between   
--      @dtStartDate and @dtEndDate  
--     AND BoxMsgInTypeId = 3 order by Origindatetime Asc)  
       
        
--    --SET @lastIgnitionOffDuration =(SELECT TOP 1  CAST(dbo.rvlf_fn_GetDuration(CustomProp,   
--    --  BoxMsgInTypeID, BoxID, 0)as int)  
--    -- FROM rvlfmsginhst where BoxId = @intCounter and OriginDateTime between   
--    --  @dtStartDate and @dtEndDate  
--    -- AND BoxMsgInTypeId = 2 order by Origindatetime Desc)         
      
--    SET @LastBoxMsgInTypeId=(SELECT TOP 1 BoxMsgInTypeID FROM rvlfmsginhst where   
--    BoxId = @intCounter and OriginDateTime between   
--      @dtStartDate and @dtEndDate  
--     AND (BoxMsgInTypeId = 2 OR BoxMsgInTypeId = 3) order by Origindatetime Desc)   
      
--    IF @firstIgnitionOffDuration > DATEDIFF(N,@dtStartDate,@firstIgnitionOffDateTime)  
--     BEGIN  
--      SET @bigTripDuration = @bigTripDuration - (@firstignitionoffDuration-DATEDIFF(N,@dtStartDate,@firstIgnitionOffDateTime))     
--     END       
       
--       If @LastBoxMsgInTypeId = 2  
--     BEGIN  
--      SET @bigTripDuration = @bigTripDuration + DATEDIFF(N,@lastIgnitionOnDateTime,@dtEndDate)            
--     END       
       
--    UPDATE @tblIdlingInfo SET RunningTime = (@bigTripDuration) WHERE BoxID = @intCounter  
--    SELECT @intCounter = MAX(BoxID) FROM @tblIdlingInfo WHERE BoxID < @intCounter  
     
--   END  
        
--   Declare @QueryingTime int=DateDiff(N,@dtstartDate,@dtendDate)  
     
--   SELECT top(@bigTopNos) BoxID as BoxId, CEILING(IdlingTime / 60.00) AS IdlingTime,  
--    RunningTime  AS RunningTime,  
--    dbo.rvlf_fn_GetTimeFromSeconds(IdlingTime ) as IdlingTimeFormatted,  
--    dbo.rvlf_fn_GetTimeFromSeconds(RunningTime * 60) as RunningTimeFormatted,  
--    VehicleDescription, VehicleName,   
--    (case when RunningTime > 0 then (RunningTime * 100 /@QueryingTime) Else 0 End) AS RunningPercentage,     
--    Ceiling((case when IdlingTime > 0 and RunningTime > 0 then ((IdlingTime) * 100 /(RunningTime * 60)) Else 0 End)) AS IdlingPercentage,  
--    @QueryingTime QueryingTime, 100 as QueryingTimePercentage  
--   FROM @tblIdlingInfo t  
--   WHERE IdlingTime > 0 OR RunningTime > 0  
--    ORDER BY RunningTime DESC --t.IdlingTime Desc--  
       
    
-- /**************** Speed Alerts *************/  
-- SELECT top (@bigTopNos)   
--   SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END) as SpeedAlerts,  
--    a.BoxID,v.VehicleDescription,  
--   --v.DisplayName  as VehicleName  
--   v.VehicleDescription VehicleName  
--  FROM rvlfMsgInHst  a  
--   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
--   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
--   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
--  WHERE   
--   (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID) AND  
--   (@bigFleetID IS NULL OR fv.FleetId = @bigFleetID)   
--   AND   
--   ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
--     a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
--   AND BoxMsgInTypeId=4  
--  GROUP BY a.BoxId, v.VehicleDescription,v.DisplayName  
--  HAVING SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END)>0  
--  ORDER BY   
--  --CASE WHEN   
--  SpeedAlerts DESC  
    
-- /***************** Distance Travelled *****************/  
--  DECLARE @tblUtilizationBoxes TABLE  
-- (  
--  SlNo int identity(1,1), BoxID int, VehicleDescription varchar(250), VehicleName varchar(50),  
--  StartOdometer bigint,MaxOdometer bigint, SetOdometer bigint,EndOdometer bigint  
-- )  
-- --CHECK IF THE ORGANIZATION IS DEFENSE THAN SELECT TOP 20  
-- IF(@bigOrganizationID=55)  
--  BEGIN  
--   INSERT INTO @tblUtilizationBoxes (BoxID, VehicleName, VehicleDescription )  
--    SELECT TOP 10 va.BoxId ,  
--     v.VehicleDescription as VehicleName,  
--     v.VehicleDescription   
--     FROM rvlfMsgInHst h   
--     INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
--     INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
--     INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId and fv.FleetId= @bigFleetID  
--    WHERE  
--     v.OrganizationId = @bigOrganizationID   
--     AND h.OriginDateTime between @dtStartDate and @dtEndDate   
--     GROUP BY  va.BoxId ,v.VehicleDescription   
--     ORDER BY VA.BoxId   
--  END  
-- ELSE  
--  BEGIN  
--   INSERT INTO @tblUtilizationBoxes (BoxID, VehicleName, VehicleDescription )  
--    --SELECT distinct h.BoxId ,  
--    -- v.VehicleDescription as VehicleName,  
--    -- v.VehicleDescription   
--    -- FROM rvlfMsgInHst h   
--    -- INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
--    -- INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
--    -- INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId and fv.FleetId= @bigFleetID  
--    --WHERE  
--    -- v.OrganizationId = @bigOrganizationID   
--    -- AND h.OriginDateTime between @dtStartDate and @dtEndDate   
      
--    SELECT TOP (@bigTopNos) BoxId,VehicleName,VehicleDescription FROM (  
--    SELECT distinct h.BoxId ,  
--     v.VehicleDescription as VehicleName,  
--     v.VehicleDescription, 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)) AS DISTANCE  
--     FROM rvlfMsgInHst h   
--     INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
--     INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
--     INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId and fv.FleetId= @bigFleetID  
--    WHERE  
--     v.OrganizationId = @bigOrganizationID   
--     AND h.OriginDateTime between @dtStartDate and @dtEndDate   
--     AND CustomProp LIKE '%Odometer%'  
--    GROUP BY  h.BoxId , v.VehicleDescription  
--    ) A  
--    ORDER BY DISTANCE DESC  
--  END     
      
  
-- DECLARE @dtOdometerSetDate DateTime=Null, @SetOdometer bigint=0  
-- DECLARE @MaxOdometer bigint=0,@StartOdometer bigint=0,@EndOdometer bigint=0  
   
   
-- --DECLARE @intCounter int  
-- SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes   
-- DECLARE @intBoxID int=0  
-- WHILE @intCounter IS NOT NULL  
--  BEGIN  
     
--   SET @dtOdometerSetDate=NULL;SET @SetOdometer=0; SET @MaxOdometer=0;SET @StartOdometer=0; SET @EndOdometer=0;  
     
--   SELECT @intBoxID = BoxID FROM @tblUtilizationBoxes WHERE slno = @intCounter     
     
--   SELECT TOP 1 @dtOdometerSetDate=SentDateTime, @SetOdometer=CustomProp FROM rvlfMsgOutHst        
--      WHERE BoxCmdOutTypeId =14 and BoxId=@intBoxID and SentDateTime between   
--      @dtStartDate and @dtEndDate order by SentDateTime desc  
      
     
--   IF @dtOdometerSetDate IS NOT NULL  
--    BEGIN  
--     SELECT @MaxOdometer=(SELECT TOP 1 Max(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,  
--       (CHARINDEX(';',CustomProp,  
--       CHARINDEX('Odometer=',CustomProp,1))) -  
--       (CHARINDEX('Odometer=',CustomProp,1)+9))) FROM rvlfMsgInHst   
--      WHERE   
--       BoxId = @intBoxID  
--       AND OriginDateTime between @dtStartDate and @dtOdometerSetDate   
--       AND CustomProp LIKE '%Odometer%')        
        
--    END  
     
--   SET @StartOdometer=(SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,  
--       (CHARINDEX(';',CustomProp,  
--       CHARINDEX('Odometer=',CustomProp,1))) -  
--       (CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst   
--      WHERE   
--       BoxId = @intBoxID  
--       AND OriginDateTime between @dtStartDate and @dtEndDate   
--       AND CustomProp LIKE '%Odometer%'  
--      ORDER BY OriginDateTime ASC)        
       
--   SET @EndOdometer =(SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,  
--       (CHARINDEX(';',CustomProp,  
--       CHARINDEX('Odometer=',CustomProp,1))) -  
--       (CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst   
--      WHERE   
--       BoxId = @intBoxID  
--       AND OriginDateTime between @dtStartDate and @dtEndDate   
--       AND CustomProp LIKE '%Odometer%'  
--      ORDER BY OriginDateTime DESC)  
     
        
     
--   UPDATE @tblUtilizationBoxes SET StartOdometer=@StartOdometer,EndOdometer=@EndOdometer,  
--    SetOdometer =@SetOdometer,MaxOdometer=@MaxOdometer  Where BoxID=@intBoxID    
     
--   SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes WHERE SlNo < @intCounter  
--  END  
   
    
--  SELECT TOP (@bigTopNos)  BoxID, VehicleDescription, VehicleName,   
--  CASE WHEN SetOdometer =0 THEN CEILING((EndOdometer - StartOdometer)*@ConversionFactor)   
--  ELSE CEILING(((MaxOdometer - StartOdometer) + (EndOdometer - SetOdometer)) *@ConversionFactor) END as DistanceTravelled,  
--  @CaptionPrefix as CaptionPrefix  
--   FROM @tblUtilizationBoxes   
--  WHERE (EndOdometer - StartOdometer) >0   
--  ORDER BY (EndOdometer - StartOdometer) DESC  
--END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrgStatistics_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

           
CREATE  PROCEDURE [dbo].[rvlf_sp_GetOrgStatistics_PhoneGap]              
(              
 @bigOrganizationID bigint,            
 @bigFleetID bigint = null,            
 @dtStartDate datetime,            
 @dtEndDate datetime,            
 @bigQueryingUser bigint,  
 @bigVehicleTypeID bigint = null,  
 @bigVehicleID bigint = null  
)                 
AS               
/******************************************************************************/              
-- Name  : rvlf_sp_GetOrgStatistics_PhoneGap 86,176,'10-Jan-18','12-Jan-18',322,null,null 
-- Description : To get the organization statistics.              
-- Author  : N.Ranjith              
-- Company  : Angler Technologies              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
--    : 07-May-14  ranjith
/******************************************************************************/              
              
              
BEGIN                  
              
 DECLARE @HoursToBeAdded INT = 0              
 DECLARE @MinsToBeAdded INT = 0              
 DECLARE @ConversionFactor numeric (10,2) = 1.0              
 DECLARE @CaptionPrefix varchar(10)              
 DECLARE @DefaultDateFormat INT = 0     
 DECLARE @VarUserPreferedChart  varchar(20) = null  
 DECLARE @UserLang  varchar(20) = NULL  
 Declare @bigTopNos bigint   = 10          
              
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,              
     @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,              
     @CaptionPrefix = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'kms' END,            
     @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end)
     --,@VarUserPreferedChart = ISNULL(UserPreferedChart,'1,2,3,4,5') 
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz              
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser                       
        
       --SELECT @VarUserPreferedChart = ISNULL(UserPreferedChart,'1,2,3,4,5,302,303,315') from rvlfUserPreferences  WHERE UserId = @bigQueryingUser              
        --select @UserLang =  Lang  from rvlfUserPreferences  WHERE UserId = @bigQueryingUser
        
    IF @bigFleetID IS NULL              
  SELECT @bigFleetID = FleetID FROM rvlfFleet where OrganizationId = @bigOrganizationID and  IsDefault=1    
            
 --SET @dtEndFDate= @dtStartDate 
 --SET @dtStartFDate= DATEADD(HOUR,(@bigLastHours*-1),@dtStartDate)
 
 --SET @dtStartFDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartFDate))                          
 --SET @dtEndFDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndFDate))   
 

DECLARE @tblmsgsDeviceType table                      
(      
 VehicleName varchar(200),  
 VehicleTypeId bigint,
 VehicleTypeName  varchar(200),  
 FleetName varchar(200),
 TotalCount Bigint,  
 OnlineCount Bigint,  
 OfflineCount Bigint,
 StatusType varchar(50),
 LastStatusDateTime datetime  
)   

insert into @tblmsgsDeviceType
select distinct v.Vehicledescription as VehicleName, vt.VehicleTypeId, vt.VehicleTypeName,f.FleetName as SiteName,0 as TotalCount, 0 as OnlineCount,
0 as OfflineCount,(Case when DATEDIFF(HH,b.LastCommunicatedDateTime,getutcdate()) <= 12 then 'Online' else 'Offline' end) as StatusType,
b.LastStatusDateTime
from rvlfBoxId b   
inner join rvlfVehicleAssignment va on va.BoxId =b.BoxId  
inner join rvlfVehicle v on v.VehicleId =va.VehicleId  
inner join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
inner join rvlffleet f on f.FleetId=fv.Fleetid
inner join rvlfVehicleType vt on vt.VehicleTypeId =v.VehicleTypeId  
inner join rvlfMAKDevices md on md.VehicleId=v.VehicleId  
where b.OrganizationId= @bigOrganizationID and fv.FleetId IN  (@bigFleetID)   
 AND  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR v.VehicleTypeId = @bigVehicleTypeID)   
 AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID) 
 And (md.IsDelete = 0)   
    
/********************************** Critical Alarms **********************************************************/

 --select Alarms.CriticalAlarms, row_number() over(order by Alarms.CriticalAlarms DESC) as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ 
 --Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,VehicleTypeName  from                
 -- (SELECT TOP (@bigTopNos) SUM(CASE WHEN a.AlarmLevelId in (2,1,3) THEN 1 ELSE 0 END) as CriticalAlarms,                
 --  vt.VehicleTypeName    
     
 -- FROM rvlfAlarm a                
 --  INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId                
 --  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
 --  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId    
 --  inner join rvlfVehicleType vt on vt.VehicleTypeId =v.VehicleTypeId             
     
 -- WHERE                 
 --  (v.OrganizationId = @bigOrganizationID) AND                
 --  (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) AND                 
 --  (CONVERT(date,a.DateTimeCreated) BETWEEN CONVERT(date,@dtStartDate) AND CONVERT(date,@dtEndDate))and  
 --  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR v.VehicleTypeId = @bigVehicleTypeID) AND     
 --  (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID)                      
 -- GROUP BY vt.VehicleTypeName,v.OrganizationId  
 -- HAVING                
 --    SUM(CASE WHEN a.AlarmLevelId in (2,1,3) THEN 1 ELSE 0 END) >0                
 -- ORDER BY                 
 --  CriticalAlarms DESC)as Alarms    

  Declare @TempAlarm as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500),  
	VehicleDescription varchar(1000),
	AlarmLevelId BIGINT,
	ControllerID Bigint
	)	

    Insert into @TempAlarm
    Select Distinct vt.VehicleTypeName,Vi.VehicleDescription,a.AlarmLevelId,a.ControllerID   from rvlfAlarmTransaction a 
	Inner Join rvlfalarm a1 on a.AlarmId=a1.AlarmId     
	inner join rvlfVehicleAssignment v on v.BoxId=a.BoxId inner join rvlfVehicle vi on vi.VehicleId =v.VehicleId
	INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId  inner join rvlfBoxMsgInType mt on a.AlarmType=mt.BoxMsgInTypeId 
	inner join rvlfVehicleType vt on vt.VehicleTypeId =vi.VehicleTypeId
	where  
	(vi.OrganizationId = @bigOrganizationID) AND
            (fv.FleetId = @bigFleetID) and
	--(vi.OrganizationId = 86) AND     (fv.FleetId = 176) and
	CONVERT(date,a.DateTimeCreated)  between Convert(Date,dateadd(dd,-1,getutcdate())) and Convert(Date,getutcdate())  and
	--CONVERT(date,a.DateTimeCreated)  between CONVERT(date,@dtStartDate) and CONVERT(date,@dtEndDate)  and
	--CONVERT(date,a.DateTimeCreated)  between'25-July-15' and '26-July-17' and
	 (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR vi.VehicleTypeId = @bigVehicleTypeID) AND  
	a.AlarmLevelId in(2,1,3) and a.AlarmType = mt.BoxMsgInTypeId and a1.IsClosed <> 1 order by VehicleTypeName

	Declare @TempAlarm1 as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500), 
	VehicleDescription varchar(1000)
	)

	Declare @TempAlarmFinal as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500),  
	NoofAlarmsCritical bigint,
	NoofAlarmsWarning1 bigint,
	NoofAlarmsWarning2 bigint,
	TotalCount bigint
	)
    
	insert into @TempAlarm1
	select distinct VehicleTypeName,VehicleDescription from @TempAlarm	

	insert into @TempAlarmFinal 
	select distinct VehicleTypeName,0,0,0,0 from @TempAlarm			

   DECLARE @intBoxLooping varchar(max)                                 
   SELECT @intBoxLooping = MIN(AlarmTID) from @TempAlarm1            
   WHILE @intBoxLooping IS NOT NULL                
   BEGIN  
	Declare @TAlarmTypeCritical bigint=0,@TAlarmTypeWarning1 bigint=0,@TAlarmTypeWarning2 bigint =0,@TAlarmTotalCount bigint =0        
	     
	   --select 
	   --@TAlarmTypeCritical =  isnull(SUM(CASE WHEN AlarmLevelId = 3  THEN 1 ELSE 0 END),0),
	   --@TAlarmTypeWarning1 =  isnull(SUM(CASE WHEN AlarmLevelId = 1 THEN 1 ELSE 0 END),0),
	   --@TAlarmTypeWarning2 =  isnull(SUM(CASE WHEN AlarmLevelId = 2 THEN 1 ELSE 0 END),0)		
	   --from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @TempAlarm where AlarmTID = @intBoxLooping)

	   --Delete from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @TempAlarm1 where AlarmTID = @intBoxLooping)
	   --and AlarmLevelId in (1,2)
	   --select VehicleDescription  from @TempAlarm1 where AlarmTID = @intBoxLooping

	   --select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @TempAlarm1 where AlarmTID = @intBoxLooping) and AlarmLevelId = 2

	   if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @TempAlarm1 where AlarmTID = @intBoxLooping) and AlarmLevelId = 3)
	   Begin
		 Set @TAlarmTypeCritical = 1
		
	   End
	   Else if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @TempAlarm1 where AlarmTID = @intBoxLooping) and AlarmLevelId = 2)
	    Begin
		 Set @TAlarmTypeWarning2 = 1
	   End
	   Else if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @TempAlarm1 where AlarmTID = @intBoxLooping) and AlarmLevelId = 1)
	    Begin
		 Set @TAlarmTypeWarning1 = 1
	   End

	   Update @TempAlarmFinal set NoofAlarmsCritical = NoofAlarmsCritical + @TAlarmTypeCritical,
	    NoofAlarmsWarning1 = NoofAlarmsWarning1 + @TAlarmTypeWarning1, NoofAlarmsWarning2 = NoofAlarmsWarning2 + @TAlarmTypeWarning2,
		--TotalCount= ((NoofAlarmsCritical + @TAlarmTypeCritical)+(NoofAlarmsWarning1 + @TAlarmTypeWarning1)+(NoofAlarmsWarning2 + @TAlarmTypeWarning2))--@TAlarmTotalCount
		TotalCount= @TAlarmTypeCritical+ @TAlarmTypeWarning1+ @TAlarmTypeWarning2
		where VehicleTypeName =  (select VehicleTypeName  from @TempAlarm1 where AlarmTID = @intBoxLooping)

        SELECT @intBoxLooping = MIN(AlarmTID) from @TempAlarm1 WHERE AlarmTID > @intBoxLooping                
   END


if exists(Select * from @TempAlarmFinal)
Begin
insert into @TempAlarmFinal
Select 'Total',sum(NoofAlarmsCritical),sum(NoofAlarmsWarning1),sum(NoofAlarmsWarning2),
sum(NoofAlarmsCritical)+sum(NoofAlarmsWarning1)+sum(NoofAlarmsWarning2)--sum(TotalCount)
from @TempAlarmFinal
End

Select distinct 1 as CriticalAlarms, VehicleTypeName , NoofAlarmsCritical ,NoofAlarmsWarning1,NoofAlarmsWarning2,
TotalCount,
 1 as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ 
 Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate from @TempAlarmFinal

  

--/********************* Productwise ********************/                
           
 
 Declare @Oncount Bigint = 0,@Offcount bigint = 0 
 -- select @Oncount=count(Distinct(b.VehicleName)) from @tblmsgsDeviceType b  
 --  where     
 --    DATEDIFF(HH,B.LastStatusDateTime,getutcdate())<=24  
   
 -- select @Offcount=  count(Distinct(b.VehicleName)) from @tblmsgsDeviceType b  
 --  where     
 --    DATEDIFF(HH,B.LastStatusDateTime,getutcdate())>=24     
   

   Select distinct VehicleName, VehicleTypeId, VehicleTypeName,FleetName as SiteName,@Oncount as OnlineCount,
    @Offcount as OfflineCount,TotalCount = @Oncount + @Offcount,StatusType,
   Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) 
   as PasGenerateddate
   from @tblmsgsDeviceType  

/****************************Warranty Active*********************************************/     
 
declare @Temp as Table(  
Total  BIGINT,  
Warranty BIGINT,  
NonWarranty BIGINT,  
VehicleDescription varchar(150),  
vehicleTypeId int  
)  
  
if (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='') AND (@bigVehicleID IS NULL OR @bigVehicleID='' )  
  
Begin  
insert into @Temp (vehicleTypeId,VehicleDescription)  
select DISTINCT VehicleTypeId,VehicleTypeName from rvlfVehicleType  
  
End  
else  
  
Begin   
  
insert into @Temp (vehicleTypeId,VehicleDescription)  
  
select distincT VT.VehicleTypeId,VT.VehicleTypeName   
 from  rvlfVehicleType VT   
 INNER JOIN rvlfVehicle V   
 on VT.VehicleTypeId = V.VehicleTypeId   
 INNER join rvlfFleetVehicles fv   
 on fv.VehicleId=v.VehicleId  
 INNER JOIN rvlfFleet f   
 ON fv.FleetId = F.FleetId  
 INNER JOIN rvlfMAKDevices MD on V.VehicleId = MD.VehicleId  
 WHERE   
   (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR VT.VehicleTypeId = @bigVehicleTypeID)  
    AND f.FleetId IN(@bigFleetID)     
    AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID)      
End  
--SELECT * FROM @Temp  
  
update T set T.Total = A.Total from @Temp T INNER JOIN   
(   
select COUNT(*) as Total, NULL as Warranty,NULL as NonWarranty, vt.VehicleTypeName as VehicleDescription,vt.VehicleTypeId  
from rvlfMakdevices MD 
--rvlfMakSubProducts SP on MD.SubTypeId = SP.SubtypeId  
INNER join rvlfVehicle v on v.VehicleId =MD.VehicleId  
LEFT JOIN rvlfVehicleType vt on V.VehicleTypeId = vt.VehicleTypeId  
LEFT join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
LEFT JOIN rvlfFleet f ON fv.FleetId = F.FleetId  
WHERE   
MD.OrganizationId= @bigOrganizationID and fv.FleetId IN  (@bigFleetID)   
AND  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR vt.VehicleTypeId = @bigVehicleTypeID)   
AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID)   
and vt.VehicleTypeId is not NULL  
and MD.IsDelete = 0  
--AND SP.Isdelete =0  
GROUP BY vt.VehicleTypeName,vt.VehicleTypeId) A  
on T.vehicleTypeId = A.VehicleTypeId  
--SELECT * FROM @Temp  
  
update T1 set T1.NonWarranty = ISNULL(B.NonWarranty,0) from @Temp T1 INNER JOIN   
(  
select NULL as Total, NULL as Warranty, COUNT(*) as NonWarranty,vt.VehicleTypeName as VehicleDescription,vt.VehicleTypeId  
from rvlfMakdevices MD 
--LEFT JOIN rvlfMakSubProducts SP on MD.SubTypeId = SP.SubtypeId  
INNER join rvlfVehicle v on v.VehicleId =MD.VehicleId  
LEFT JOIN rvlfVehicleType vt on V.VehicleTypeId = vt.VehicleTypeId  
LEFT join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
LEFT JOIN rvlfFleet f ON fv.FleetId = F.FleetId  
WHERE MD.WarrantyEndDate IS NULL and   
MD.OrganizationId= @bigOrganizationID and fv.FleetId IN  (@bigFleetID)   
AND  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR vt.VehicleTypeId = @bigVehicleTypeID)   
and vt.VehicleTypeId is not NULL  
 AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID)   
and MD.IsDelete = 0  
--AND SP.Isdelete =0  
GROUP BY vt.VehicleTypeName,vt.VehicleTypeId  
) B   
on T1.vehicleTypeId = B.VehicleTypeId  
  
  
update T2 set T2.NonWarranty = ISNULL(T2.NonWarranty,0) + ISNULL(C.NonWarranty,0) from @Temp T2 INNER JOIN  
(select NULL as Total, NULL as Warranty,COUNT(*) as NonWarranty,vt.VehicleTypeName as VehicleDescription,vt.VehicleTypeId  
from rvlfMakdevices MD 
--LEFT JOIN rvlfMakSubProducts SP on MD.SubTypeId = SP.SubtypeId  
INNER join rvlfVehicle v on v.VehicleId =MD.VehicleId  
LEFT JOIN rvlfVehicleType vt on V.VehicleTypeId = vt.VehicleTypeId   
LEFT join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
LEFT JOIN rvlfFleet f ON fv.FleetId = F.FleetId  
WHERE --MD.WarrantyEndDate IS NOT NULL  
MD.WarrantyEndDate < CONVERT(date,@dtEndDate)  
and   
MD.OrganizationId= @bigOrganizationID and fv.FleetId IN  (@bigFleetID)   
AND  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR vt.VehicleTypeId = @bigVehicleTypeID)   
and vt.VehicleTypeId is not NULL  
 AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID)   
and MD.IsDelete = 0  
--AND SP.Isdelete =0  
GROUP BY vt.VehicleTypeName,vt.VehicleTypeId) C   
on T2.vehicleTypeId = C.VehicleTypeId  
  
update T3 set T3.Warranty = ISNULL(D.Warranty,0) from @Temp T3 INNER JOIN  
(  
select NULL as Total, COUNT(*) as Warranty, NULL as NonWarranty,vt.VehicleTypeName as VehicleDescription,vt.VehicleTypeId  
from rvlfMakdevices MD 
--LEFT JOIN rvlfMakSubProducts SP on MD.SubTypeId = SP.SubtypeId  
INNER join rvlfVehicle v on v.VehicleId =MD.VehicleId  
LEFT JOIN rvlfVehicleType vt on V.VehicleTypeId = vt.VehicleTypeId  
LEFT join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
LEFT JOIN rvlfFleet f ON fv.FleetId = F.FleetId  
WHERE --MD.WarrantyEndDate IS NOT NULL  
MD.WarrantyEndDate >= CONVERT(date,@dtEndDate)  
and   
MD.OrganizationId= @bigOrganizationID and fv.FleetId IN  (@bigFleetID)   
AND  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR vt.VehicleTypeId = @bigVehicleTypeID)   
and vt.VehicleTypeId is not NULL  
 AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID)   
and MD.IsDelete = 0  
--AND SP.Isdelete =0  
GROUP BY vt.VehicleTypeName,vt.VehicleTypeId) D  
on T3.vehicleTypeId = D.VehicleTypeId  
  
if EXISTS (select VehicleDescription from @Temp group by VehicleDescription having COUNT(Total) > 0 OR COUNT(Warranty) > 0 OR COUNT (NonWarranty) > 0 )  

select vehicleTypeId, VehicleDescription,ISNULL(Total,0) TotalDevices,ISNULL(Warranty,0) as Warranty,ISNULL(NonWarranty,0)as NonWarranty,SUM(ISNULL(Warranty,0)),SUM(ISNULL(NonWarranty,0)),  
Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' ' 
+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate  
from @Temp  
WHERE  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR vehicleTypeId = @bigVehicleTypeID)   
group by vehicleTypeId,VehicleDescription,Total,Warranty,NonWarranty  
--HAVING (ISNULL(SUM(Warranty),0) > 0 OR ISNULL(SUM(NonWarranty),0) > 0 OR ISNULL(SUM(Total),0) > 0)  
 --AND (@bigVehicleID1 IS NULL OR @bigVehicleID1='' OR VehicleId = @bigVehicleID1)   
Union All
Select 0 as VehicleTypeId, 'Total' as VehicleDescription, SUM(Total), SUM(Warranty), SUM(NonWarranty), 0, 0, 
Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' ' 
+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate from @Temp  
order by  vehicleTypeId   
  


/****************************Portal Usage***********************************************/   
  
 
   
  SELECT DISTINCT  u.UserName,-- SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime))as Seconds,   
 CEILING(SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime)) / 60.00) as DurationInMinutes,  
    dbo.rvlf_fn_GetTimeFromSeconds(SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime))) AS [UsageTimeFormatted],       
 row_number() over(order by SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime)) desc) as PortalUsageRowno,  
 '-' as DriverName,  
  CONVERT(VARCHAR,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+   
 ' '+ CONVERT(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) AS TIME),22) as PasGenerateddate   
 FROM dbo.rvlfUserLogin ul    
 INNER JOIN dbo.rvlfUser u ON u.UserId=ul.UserId AND u.UserId IN   
   (SELECT DISTINCT fu.UserID FROM dbo.rvlfFleetUsers fu INNER JOIN dbo.rvlfFleet f ON f.FleetId=fu.FleetId  
 WHERE f.OrganizationID=@bigOrganizationID AND f.FleetId=@bigFleetID)    
 INNER JOIN rvlfUserPreferences up ON up.UserId=u.UserId  
 WHERE u.IsHidden=0 AND ul.LoginDateTime BETWEEN @dtStartDate AND @dtEndDate and ul.LogoffDateTime is not null group by u.UserName  


 /***************** Get User Prefered Chart****************************************************************/            
 
  DECLARE @List as varchar(max)              
  DECLARE @ISExport  int              
  SELECT @ISExport = ug.OperationTypeId  from rvlfOperationType op               
  INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId               
  INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId              
  INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId              
  INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId              
  INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId              
  INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId                
  WHERE  ga.UserId = @bigQueryingUser and ug.ModuleId = 1 and ug.OperationTypeId not in (1,2,3,4)              
              
  ----SELECT distinct(case when @ISExport is not null or @ISExport = '' then @VarUserPreferedChart + ',5' else @VarUserPreferedChart end)                
                
  DECLARE @tblmsgs table                    
  (                       
  OperationTypeId varchar(20),              
  Export  Bigint               
  )              
  insert into @tblmsgs(OperationTypeId,Export)               
  select  distinct(ug.OperationTypeId), Export = case when ug.OperationTypeId in (1,2,3,4,5) Then '5'  END   from rvlfOperationType op               
  INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId               
  INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId              
  INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId              
  INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId              
  INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId              
  INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId               
  where ga.UserId = @bigQueryingUser and ug.ModuleId = 1 order by ug.OperationTypeId  desc               
  SELECT @List = case  WHEN  @ISExport is not  null THEN COALESCE(@List + ',',',') + cast(OperationTypeId as varchar(25)) ELSE   COALESCE(@List + ',','') + cast(OperationTypeId as varchar(25))  END  from @tblmsgs where OperationTypeId  in 
  (SELECT * FROM rvlf_fn_ConvertArrayToTable(@VarUserPreferedChart, ','))              
  SELECT @List as OperationTypeId     


  /*****************For Product/ESP status chart data***********************/
--Select VehicleTypeName,sum((case when StatusType = 'Online'  then 1 else 0 end)) as OnlineTotalCount,sum((case when StatusType = 'Offline'  then 1 else 0 end)) as OfflineTotalCount
-- from @tblmsgsDeviceType where 
--(@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR VehicleTypeId = @bigVehicleTypeID)    group by VehicleTypeName
Select 'Total' as VehicleTypeName,sum(case when StatusType = 'Online'  then 1 else 0 end) as OnlineTotalCount,0 as OfflineTotalCount,(sum((case when StatusType in ('Online','Offline')  then 1 else 0 end))) as TotalCount
from @tblmsgsDeviceType where (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR VehicleTypeId = @bigVehicleTypeID)
union all
Select VehicleTypeName, sum(case when StatusType = 'Online'  then 1 else 0 end) as OnlineTotalCount,sum(case when StatusType = 'Offline'  then 1 else 0 end) as OfflineTotalCount,
(sum(case when StatusType = 'Online'  then 1 else 0 end)  + sum(case when StatusType = 'Offline'  then 1 else 0 end)) as TotalCount
from @tblmsgsDeviceType where (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR VehicleTypeId = @bigVehicleTypeID) group by VehicleTypeName

 /*************************************** HVR Communication Status  ***********************************/

 DECLARE @tblmsgsDeviceTypeHVRComm table                      
	(      
	VehicleName varchar(200),  
	VehicleTypeId bigint,
	VehicleTypeName  varchar(200),  
	FleetName varchar(200),
	TotalCount Bigint,  
	OnlineCount Bigint,  
	OfflineCount Bigint,
	StatusType varchar(50),
	LastStatusDateTime datetime,
	ControllerId Bigint  
	)   

	insert into @tblmsgsDeviceTypeHVRComm
	Select distinct v.Vehicledescription as VehicleName, vt.VehicleTypeId, vt.VehicleTypeName,f.FleetName as SiteName,0 as TotalCount, 0 as OnlineCount,
	0 as OfflineCount,(Case when DATEDIFF(HH,b.lastreportedatetime,getutcdate()) <= 12 then 'Online' else 'Offline' end) as StatusType,
	b.lastreportedatetime,b.ControllerId
	from adrControllerMaster b  	
	inner join rvlfVehicleAssignment va on va.BoxId =b.EquipmentID  
	inner join rvlfVehicle v on v.VehicleId =va.VehicleId  
	inner join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
	inner join rvlffleet f on f.FleetId=fv.Fleetid
	inner join rvlfVehicleType vt on vt.VehicleTypeId =v.VehicleTypeId  
	inner join rvlfMAKDevices md on md.VehicleId=v.VehicleId  
	where v.OrganizationId= @bigOrganizationID and 
	fv.FleetId IN  (@bigFleetID)   
	AND  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR v.VehicleTypeId = @bigVehicleTypeID)   
	AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID) 
	And (md.IsDelete = 0)  and b.IsDeleted = 0   

	Declare @OncountHVRComm Bigint = 0,@OffcountHVRComm  bigint = 0 
  

	--Select distinct VehicleName, VehicleTypeId, VehicleTypeName,FleetName as SiteName,@OncountHVRComm as OnlineCount,
	--@OffcountHVRComm  as OfflineCount,TotalCount = @OncountHVRComm + @OffcountHVRComm ,StatusType,
	--Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) 
	--as PasGenerateddate,ControllerId
	--from @tblmsgsDeviceTypeHVRComm  

    Select 'Total' as VehicleTypeName,sum(case when StatusType = 'Online'  then 1 else 0 end) as OnlineTotalCount,0 as OfflineTotalCount,(sum((case when StatusType in ('Online','Offline')  then 1 else 0 end))) as TotalCount
	from @tblmsgsDeviceTypeHVRComm where (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR VehicleTypeId = @bigVehicleTypeID)
	union all
	Select VehicleTypeName, sum(case when StatusType = 'Online'  then 1 else 0 end) as OnlineTotalCount,sum(case when StatusType = 'Offline'  then 1 else 0 end) as OfflineTotalCount,
	(sum(case when StatusType = 'Online'  then 1 else 0 end)  + sum(case when StatusType = 'Offline'  then 1 else 0 end)) as TotalCount
	from @tblmsgsDeviceTypeHVRComm where (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR VehicleTypeId = @bigVehicleTypeID) group by VehicleTypeName

 /*************************************** HVR Alarm Status  ***********************************/

	Declare @HVRTempAlarm as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500), 
	VehicleDescription varchar(1000),
	ControllerID Bigint
	)

	Declare @TempHVRAlarmFinal as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500),  
	NoofAlarmsCritical bigint,
	NoofAlarmsWarning1 bigint,
	NoofAlarmsWarning2 bigint,
	TotalCount bigint,
	ControllerID Bigint
	)
   
	insert into @HVRTempAlarm
	select distinct VehicleTypeName,VehicleDescription,ControllerID from @TempAlarm	

	insert into @TempHVRAlarmFinal 
	select distinct VehicleTypeName,0,0,0,0,ControllerID from @TempAlarm			

	DECLARE @intHVRAlarmBoxLooping varchar(max)                                 
	SELECT @intHVRAlarmBoxLooping = MIN(AlarmTID) from @HVRTempAlarm            
	WHILE @intHVRAlarmBoxLooping IS NOT NULL                
	BEGIN    
	Declare @THVRAlarmTypeCritical bigint=0,@THVRAlarmTypeWarning1 bigint=0,@THVRAlarmTypeWarning2 bigint =0,@THVRAlarmTotalCount bigint =0    
	   

		if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @HVRTempAlarm where AlarmTID = @intHVRAlarmBoxLooping) and AlarmLevelId = 3)
		Begin
			Set @THVRAlarmTypeCritical = 1		
		End
		Else if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @HVRTempAlarm where AlarmTID = @intHVRAlarmBoxLooping) and AlarmLevelId = 2)
		Begin
			Set @THVRAlarmTypeWarning2 = 1
		End
		Else if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @HVRTempAlarm where AlarmTID = @intHVRAlarmBoxLooping) and AlarmLevelId = 1)
		Begin
			Set @THVRAlarmTypeWarning1 = 1
		End
	   
		set @THVRAlarmTotalCount = (Select(sum(case when StatusType = 'Online'  then 1 else 0 end)  + sum(case when StatusType = 'Offline'  then 1 else 0 end)) from @tblmsgsDeviceType  where (VehicleTypeName = (select VehicleTypeName  from @HVRTempAlarm where AlarmTID = @intHVRAlarmBoxLooping)))
	   
		Update @TempHVRAlarmFinal set NoofAlarmsCritical = NoofAlarmsCritical + @THVRAlarmTypeCritical,
		NoofAlarmsWarning1 = NoofAlarmsWarning1 + @THVRAlarmTypeWarning1, NoofAlarmsWarning2 = NoofAlarmsWarning2 + @THVRAlarmTypeWarning2,
		TotalCount= @THVRAlarmTotalCount
		where VehicleTypeName =  (select VehicleTypeName  from @HVRTempAlarm where AlarmTID = @intHVRAlarmBoxLooping)

		SELECT @intHVRAlarmBoxLooping = MIN(AlarmTID) from @HVRTempAlarm WHERE AlarmTID > @intHVRAlarmBoxLooping                
	END


	if exists(Select * from @TempHVRAlarmFinal)
	Begin
	insert into @TempHVRAlarmFinal
	Select 'Total',sum(NoofAlarmsCritical),sum(NoofAlarmsWarning1),sum(NoofAlarmsWarning2),
	sum(TotalCount),ControllerID
		from @TempHVRAlarmFinal
		group by ControllerID
	End

	Select distinct 1 as CriticalAlarms, VehicleTypeName , NoofAlarmsCritical ,NoofAlarmsWarning1,NoofAlarmsWarning2,
	TotalCount,		1 as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ 
	Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,null as ControllerID from @TempHVRAlarmFinal

/*************************************** HVR Warranty Alarm Status  ***********************************/

	Declare @WHVRTempAlarm as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500), 
	VehicleDescription varchar(1000),
	ControllerID Bigint
	)

	Declare @TempWHVRAlarmFinal as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500),  
	NoofAlarmsCritical bigint,
	NoofAlarmsWarning1 bigint,
	NoofAlarmsWarning2 bigint,
	TotalCount bigint,
	ControllerID Bigint
	)
   
	insert into @WHVRTempAlarm
	select distinct A.VehicleTypeName,A.VehicleDescription,A.ControllerID from @TempAlarm	A
	--inner join adrControllerMaster aCM on A.ControllerID = aCM.ControllerID
	--where getutcdate() between aCM.WarrantyStartDate and aCM.WarrantyEndDate

	insert into @TempWHVRAlarmFinal 
	select distinct VehicleTypeName,0,0,0,0,ControllerID from @TempAlarm			

	DECLARE @intWHVRAlarmBoxLooping varchar(max)                                 
	SELECT @intWHVRAlarmBoxLooping = MIN(AlarmTID) from @WHVRTempAlarm            
	WHILE @intWHVRAlarmBoxLooping IS NOT NULL                
	BEGIN    
	Declare @TWHVRAlarmTypeCritical bigint=0,@TWHVRAlarmTypeWarning1 bigint=0,@TWHVRAlarmTypeWarning2 bigint =0,@TWHVRAlarmTotalCount bigint =0            
	   

	if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @WHVRTempAlarm where AlarmTID = @intWHVRAlarmBoxLooping) and AlarmLevelId = 3)
	Begin
		Set @TWHVRAlarmTypeCritical = 1		
	End
	Else if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @WHVRTempAlarm where AlarmTID = @intWHVRAlarmBoxLooping) and AlarmLevelId = 2)
	Begin
		Set @TWHVRAlarmTypeWarning2 = 1
	End
	Else if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @WHVRTempAlarm where AlarmTID = @intWHVRAlarmBoxLooping) and AlarmLevelId = 1)
	Begin
		Set @TWHVRAlarmTypeWarning1 = 1
	End
	   
	set @TWHVRAlarmTotalCount = (Select(sum(case when StatusType = 'Online'  then 1 else 0 end)  + sum(case when StatusType = 'Offline'  then 1 else 0 end)) from @tblmsgsDeviceType  where (VehicleTypeName = (select VehicleTypeName  from @WHVRTempAlarm where 



AlarmTID = @intWHVRAlarmBoxLooping)))
	   
	Update @TempWHVRAlarmFinal set NoofAlarmsCritical = NoofAlarmsCritical + @TWHVRAlarmTypeCritical,
	NoofAlarmsWarning1 = NoofAlarmsWarning1 + @TWHVRAlarmTypeWarning1, NoofAlarmsWarning2 = NoofAlarmsWarning2 + @TWHVRAlarmTypeWarning2,
	TotalCount= @TWHVRAlarmTotalCount
	where VehicleTypeName =  (select VehicleTypeName  from @WHVRTempAlarm where AlarmTID = @intWHVRAlarmBoxLooping)

	SELECT @intWHVRAlarmBoxLooping = MIN(AlarmTID) from @WHVRTempAlarm WHERE AlarmTID > @intWHVRAlarmBoxLooping                
	END

	if exists(Select * from @TempWHVRAlarmFinal)
	Begin
	insert into @TempWHVRAlarmFinal
	Select 'Total',sum(NoofAlarmsCritical),sum(NoofAlarmsWarning1),sum(NoofAlarmsWarning2),
	sum(TotalCount),ControllerID
	from @TempWHVRAlarmFinal group by ControllerID
	End	
	
   
	Select distinct 1 as CriticalAlarms, VehicleTypeName , NoofAlarmsCritical ,NoofAlarmsWarning1,NoofAlarmsWarning2,
	TotalCount,	1 as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ 
	Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,null as ControllerID from @TempWHVRAlarmFinal
	

END     





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrgStatistics_PhoneGap_Test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

           
CREATE  PROCEDURE [dbo].[rvlf_sp_GetOrgStatistics_PhoneGap_Test]              
(              
 @bigOrganizationID bigint,              
 @bigFleetID bigint = null,              
 @dtStartDate datetime,  
 @dtEndDate datetime = null,            
 @bigLastHours bigint,              
 @bigQueryingUser bigint,              
 @bigTopNos bigint 
)                 
AS               
/******************************************************************************/              
-- Name  : rvlf_sp_GetOrgStatistics_PhoneGap_Test 170,301,'7/31/2014 7:30:19 AM','7/30/2014 11:30:19 PM',8,845,3
-- Description : To get the organization statistics.              
-- Author  : N.Ranjith              
-- Company  : Angler Technologies              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
--    : 07-May-14  ranjith
/******************************************************************************/              
              
              
BEGIN                  
              
 DECLARE @HoursToBeAdded INT = 0              
 DECLARE @MinsToBeAdded INT = 0              
 DECLARE @ConversionFactor numeric (10,2) = 1.0              
 DECLARE @CaptionPrefix varchar(10)              
 DECLARE @DefaultDateFormat INT = 0     
 DECLARE @VarUserPreferedChart  varchar(20) = null  
 DECLARE @UserLang  varchar(20) = NULL 
 --Declare @dtStartFDate datetime
 --Declare @dtEndFDate datetime         
              
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,              
     @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,              
     @CaptionPrefix = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'kms' END,            
     @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end)
     --,@VarUserPreferedChart = ISNULL(UserPreferedChart,'1,2,3,4,5') 
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz              
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser                       
        
       --SELECT @VarUserPreferedChart = ISNULL(UserPreferedChart,'1,2,3,4,5,302,303,315') from rvlfUserPreferences  WHERE UserId = @bigQueryingUser              
        --select @UserLang =  Lang  from rvlfUserPreferences  WHERE UserId = @bigQueryingUser
        
    IF @bigFleetID IS NULL              
  SELECT @bigFleetID = FleetID FROM rvlfFleet where OrganizationId = @bigOrganizationID and  IsDefault=1    
            
 --SET @dtEndFDate= @dtStartDate 
 --SET @dtStartFDate= DATEADD(HOUR,(@bigLastHours*-1),@dtStartDate)
 
 --SET @dtStartFDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartFDate))                          
 --SET @dtEndFDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndFDate))   
 
     print @dtStartDate     
     print @dtEndDate
     
 /**************** Speed Alerts ****************************************************************************/              
        
               
 --Included by ranjith for Dashboard Code Optimization  
 select SpeedAlert.SpeedAlerts,SpeedAlert.VehicleName, row_number() over(order by SpeedAlert.SpeedAlerts desc) as SpeedAlertRowno 
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate         
  from (SELECT distinct top (@bigTopNos)               
   SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END) as SpeedAlerts,              
    a.BoxID,v.VehicleDescription,              
   --v.DisplayName  as VehicleName              
   v.VehicleDescription VehicleName         
  FROM rvlfMsgInHst  a              
   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId              
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId              
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId     
  WHERE               
   (v.OrganizationId = @bigOrganizationID) AND              
   (fv.FleetId = @bigFleetID)               
   AND               
   (a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)              
  GROUP BY a.BoxId, v.VehicleDescription,v.DisplayName
  HAVING SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END)>0              
  ORDER BY               
  --CASE WHEN               
  SpeedAlerts DESC) as SpeedAlert              
             
               
    
DECLARE @tblVehicles TABLE              
 (              
  VehicleId bigint,              
  VehicleDescription varchar(50),                
  Boxid bigint,                
  TotalNoofIdling int,              
  TotalRunningTime int,              
  TotalIdlingTime int,        
  UNIQUE CLUSTERED(BoxId,VehicleId)            
 )              
              
  DECLARE @TBLSTARTIdling TABLE              
  (              
   Processid bigint identity(1,1),              
   Boxid int,              
   StartTime datetime,              
   Running int,              
   tripId int,        
   UNIQUE CLUSTERED(TripId,Boxid,Processid)        
  )              
               
  DECLARE @TBLSTOPIdling TABLE              
  (              
   Boxid int,              
   StopTime datetime,              
   tripId int        
   --UNIQUE CLUSTERED(TripId,Boxid,StopTime)              
  )               
              
  DECLARE @tblMessageForProcessingTripIdling TABLE (                  
   [OriginDateTime] [datetime] NOT NULL,              
   [BoxMsgInTypeId] [tinyint] NULL,                
   [Address] varchar(300) null,                
   [Ignition] tinyint null,                
   [CustomProp] [varchar](600) NULL        
   --UNIQUE CLUSTERED(OriginDateTime,BoxMsgInTypeId,Ignition,CustomProp)                      
  )              
  INSERT INTO @tblVehicles (VehicleId,Boxid,VehicleDescription)              
    --SELECT va.BoxId , v.VehicleId  AS VEH,v.VehicleDescription as VehicleDescription
    --      FROM rvlfVehicleAssignment va   
    --       INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
    --       INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
    --      WHERE(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)   
    --       AND (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID)       
    
  SELECT VA.VehicleId,BI.BoxId,V.VehicleDescription 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 V.OrganizationId =@bigOrganizationID AND F.OrganizationId =@bigOrganizationID)              
  AND (@bigFleetID IS NULL OR F.FleetId=@bigFleetID)                
  ORDER BY BI.BOXID   
              
DECLARE @TBLIDLINGDETAILS TABLE              
 (              
  --Processid bigint identity(1,1),              
  Boxid int,              
  StartTime datetime,              
  EndTime datetime,              
  StartTrip datetime,              
  EndTrip datetime,                
  StreetAddress nvarchar(300),              
  Running int,              
  idling int,              
  DriverId bigint,        
  UNIQUE CLUSTERED(Boxid,StartTrip,EndTrip,StartTime,EndTime)              
 )              
              
DECLARE @intBoxLoop int =(SELECT MIN(Boxid) FROM @tblVehicles)              
              
WHILE @intBoxLoop IS NOT NULL              
 BEGIN              
                  
  DELETE FROM @tblMessageForProcessingTripIdling                  
  INSERT INTO @tblMessageForProcessingTripIdling(OriginDateTime,BoxMsgInTypeId,CustomProp,Ignition,Address)              
  SELECT  h.OriginDateTime, h.BoxMsgInTypeId,h.CustomProp,CASE WHEN CustomProp LIKE '%SENSOR_NUM=%' THEN SUBSTRING(CustomProp,CHARINDEX('SENSOR_NUM=',CustomProp,1)+11,(CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_NUM=',CustomProp,1))-( CHARINDEX('SENSOR_NUM=',CustomProp,1)+11))) ELSE NULL END,              
  CASE WHEN (H.LandMarkID IS NULL OR H.LandMarkID = 0) THEN               
  REPLACE(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''') ELSE L.LandmarkName END                     
  from rvlfMsgInHst h INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId               
  LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID                            
  where h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId IN (2,3,9)              
  AND 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               
                      
  -- GET THE IGNITION ON DETAILS              
  DELETE FROM @TBLSTARTIdling                   
  INSERT INTO @TBLSTARTIdling (Boxid,StartTime)              
  SELECT @intBoxLoop,OriginDateTime FROM @tblMessageForProcessingTripIdling                     
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId IN(2)              
  AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTripIdling               
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)              
  AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTripIdling               
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                
  AND Ignition=3  AND CustomProp LIKE '%SENSOR_NUM=3%'         
                 
  --GET THE IGNITION OFF DETAILS                 
  DELETE FROM @TBLSTOPIdling               
  INSERT INTO @TBLSTOPIdling  (Boxid,StopTime)              
  SELECT @intBoxLoop,OriginDateTime                
  FROM @tblMessageForProcessingTripIdling                 
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
  AND BoxMsgInTypeId IN(3)              
  AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTripIdling                
  WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)              
  AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTripIdling                
  WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                
  AND CustomProp LIKE '%SENSOR_NUM=3%'             
          
  --PREPARE THE TRIPS AND DETAILS              
  DECLARE @LOOP1 BIGINT =(SELECT MIN(Processid) FROM @TBLSTARTIdling  )               
  DECLARE @DTSTART1 DATETIME=null,@DTEND1 DATETIME=null                
  DECLARE @INC1 INT=1                     
  WHILE @LOOP1 IS NOT NULL              
  BEGIN              
      SELECT TOP 1 @DTSTART1=StartTime  FROM @TBLSTARTIdling  WHERE Processid >=@LOOP1 AND (@DTEND1 IS NULL OR StartTime >@DTEND1)                  
      SELECT TOP 1 @DTEND1=StopTime   FROM @TBLSTOPIdling  WHERE StopTime >@DTSTART1               
      UPDATE top(1) @TBLSTARTIdling  SET tripId=@INC1 WHERE StartTime =@DTSTART1               
      UPDATE top(1) @TBLSTOPIdling  SET tripId=@INC1 WHERE StopTime =@DTEND1                           
      SET @INC1 =@INC1 +1                    
      SELECT @LOOP1 =MIN(Processid) FROM @TBLSTARTIdling  WHERE Processid >@LOOP1  AND StartTime >@DTSTART1                    
  END                                  
  
                
  --GET THE IDLING DETAILS               
  INSERT INTO @TBLIDLINGDETAILS (Boxid,EndTime,StartTime,StreetAddress)     
  SELECT idl.BoxId,idl.OriginDateTime,idl.StartTime,idl.Address FROM
  (SELECT @intBoxLoop AS BoxID ,OriginDateTime, DATEADD(S,-CAST(SUBSTRING(CUSTOMPROP,CHARINDEX('Idling:',CUSTOMPROP,0)+7,              
  (CHARINDEX(';',CUSTOMPROP,CHARINDEX('Idling:',CUSTOMPROP,0))- (CHARINDEX('Idling:',CUSTOMPROP,0)+7))) AS INT),OriginDateTime) AS StartTime,Address                 
  FROM @tblMessageForProcessingTripIdling  WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
  AND BoxMsgInTypeId IN(9) AND CustomProp NOT LIKE '%Idling:0;%') idl WHERE idl.OriginDateTime BETWEEN (SELECT MIN(StartTime) FROM @TBLSTARTIdling )
  AND (SELECT MAX(StopTime) FROM @TBLSTOPIdling )       
  --SELECT @intBoxLoop,OriginDateTime, DATEADD(S,-CAST(SUBSTRING(CUSTOMPROP,CHARINDEX('Idling:',CUSTOMPROP,0)+7,              
  --(CHARINDEX(';',CUSTOMPROP,CHARINDEX('Idling:',CUSTOMPROP,0))- (CHARINDEX('Idling:',CUSTOMPROP,0)+7))) AS INT),OriginDateTime),Address                 
  --FROM @tblMessageForProcessingTrip WHERE  OriginDateTime BETWEEN @dtStartFDate AND @dtEndFDate               
  --AND BoxMsgInTypeId IN(9) AND CustomProp NOT LIKE '%Idling:0;%'              
                    
  UPDATE @TBLIDLINGDETAILS SET StartTrip=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTripIdling  WHERE OriginDateTime<=StartTime               
  AND BoxMsgInTypeId =2 AND Ignition=3 AND OriginDateTime <= StartTime              
  ORDER BY OriginDateTime DESC),EndTrip=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTripIdling  WHERE OriginDateTime>=EndTime                
  AND BoxMsgInTypeId =3 AND OriginDateTime >= EndTime              
  ORDER BY OriginDateTime) WHERE StartTrip IS NULL AND EndTrip IS NULL                
                
  IF EXISTS(SELECT Boxid FROM @TBLIDLINGDETAILS WHERE StartTrip IS NULL)              
  BEGIN            
   --GET THE IGINITION DETAILS FROM MAIN TABLE               
   UPDATE @TBLIDLINGDETAILS SET StartTrip=(SELECT TOP 1 OriginDateTime FROM rvlfMsgInHst WHERE OriginDateTime<=StartTime               
   AND Boxid=@intBoxLoop  AND BoxMsgInTypeId =2 AND CAST(SUBSTRING(sensormask,6,1) as bit)=1 AND OriginDateTime <= EndTime               
   ORDER BY OriginDateTime DESC) WHERE StartTrip IS NULL               
  END           
              
  IF EXISTS(SELECT Boxid FROM @TBLIDLINGDETAILS WHERE EndTrip IS NULL)              
   BEGIN               
    --GET THE IGINITION DETAILS FROM MAIN TABLE               
    UPDATE @TBLIDLINGDETAILS SET EndTrip=(SELECT TOP 1 OriginDateTime FROM rvlfMsgInHst WHERE OriginDateTime>=EndTime                
    AND Boxid=@intBoxLoop AND BoxMsgInTypeId =3 AND OriginDateTime >= EndTime ORDER BY OriginDateTime)                
    WHERE EndTrip IS NULL               
   END              
  UPDATE @TBLIDLINGDETAILS SET Running=DATEDIFF(S,StartTrip,EndTrip),idling=DATEDIFF(S,StartTime,EndTime)               
  WHERE Running IS NULL AND idling IS NULL              
                 
  UPDATE @tblVehicles SET TotalNoofIdling =(SELECT COUNT(Boxid) FROM @TBLIDLINGDETAILS WHERE Boxid=@intBoxLoop),              
  TotalIdlingTime=(SELECT SUM(idling) FROM @TBLIDLINGDETAILS WHERE Boxid=@intBoxLoop GROUP BY Boxid)--,              
  WHERE Boxid =@intBoxLoop AND TotalNoofIdling IS NULL AND TotalIdlingTime IS NULL --AND MaxIdlingTime IS NULL                             
                
            
  SELECT @intBoxLoop = MIN(Boxid) FROM @tblVehicles WHERE Boxid >@intBoxLoop               
 END              
              
 --DELETE THE INVALID IDLINGS              
 DELETE FROM @TBLIDLINGDETAILS WHERE Running IS NULL              
 
 DECLARE @QueryingTime1 INT=DateDiff(MINUTE,@dtStartDate,@dtEndDate)                   
 
 select distinct TOP(@bigTopNos) Idling.IdlingTime,
   Idling.IdlingTimeFormatted,Idling.VehicleName,row_number() over(order by Idling.IdlingInstances DESC) as IdlingRowno,
   IdlingInstances   from              
      (              
 SELECT distinct V.Boxid,
 CEILING(TotalIdlingTime / 60.00) as IdlingTime,
 ISNULL (dbo.rvlf_fn_GetTimeFromSeconds(CASE WHEN TotalRunningTime<TotalIdlingTime THEN TotalRunningTime ELSE TotalIdlingTime END),'-')as IdlingTimeFormatted,              
 VehicleDescription as VehicleName,  
 TotalNoofIdling as IdlingInstances
 FROM @tblVehicles V INNER JOIN @TBLIDLINGDETAILS T ON T.Boxid =V.Boxid                 
 ) as Idling ORDER BY IdlingTime desc 

/********************************** Critical Alarms **********************************************************/

select Alarms.CriticalAlarms,Alarms.BoxId,Alarms.VehicleDescription,Alarms.VehicleName, row_number() over(order by Alarms.CriticalAlarms DESC) as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate   from              
  (SELECT TOP (@bigTopNos) SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) as CriticalAlarms,              
    a.BoxID,v.VehicleDescription,                 
   v.VehicleDescription  as VehicleName
  FROM rvlfAlarm a              
   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId              
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId              
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId        
  WHERE               
   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND              
   (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) AND               
   ( a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
  GROUP BY a.BoxId, v.VehicleDescription,v.VehicleDescription,v.OrganizationId
  HAVING              
     SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) >0              
  ORDER BY               
   CASE WHEN v.OrganizationId=55 THEN a.BoxId END ASC,CriticalAlarms DESC)as Alarms  

END     



 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOrgStatisticsTest]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

           
CREATE  PROCEDURE [dbo].[rvlf_sp_GetOrgStatisticsTest]              
(              
 @bigOrganizationID bigint,              
 @bigFleetID bigint = null,              
 @dtStartDate datetime,              
 @dtEndDate datetime,              
 @bigQueryingUser bigint,              
 @bigTopNos bigint              
)                 
AS               
/******************************************************************************/              
-- Name  : rvlf_sp_GetOrgStatisticsTest 6,182,'06/11/2013 11:00:21 AM','06/12/2013 11:00:21 AM',48,10            
-- Description : To get the organization statistics.              
-- Author  : V.Narayanasamy              
-- Company  : Angler Technologies              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
--    : 12-May-2011 VN Altered the running and idling logic              
--  Updated by  :  Ranjith - getting rowno of each chart for datatable filteration              
--  Updated date:  27-Jun-11            
--  Updated date:  27-Apr-13 Sakthi Include code for mobile application (distance travelled)
/******************************************************************************/              
              
              
BEGIN                  
              
 DECLARE @HoursToBeAdded INT = 0              
 DECLARE @MinsToBeAdded INT = 0              
 DECLARE @ConversionFactor numeric (10,2) = 1.0              
 DECLARE @CaptionPrefix varchar(10)              
 DECLARE @DefaultDateFormat INT = 0     
   DECLARE @VarUserPreferedChart  varchar(15) = null                
              
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,              
     @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,              
     @CaptionPrefix = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'kms' END,            
     @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end)
     --,@VarUserPreferedChart = ISNULL(UserPreferedChart,'1,2,3,4,5') 
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz              
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser                       
        
       SELECT @VarUserPreferedChart = ISNULL(UserPreferedChart,'1,2,3,4,5') from rvlfUserPreferences  WHERE UserId = @bigQueryingUser              
                
    IF @bigFleetID IS NULL              
  SELECT @bigFleetID = FleetID FROM rvlfFleet where OrganizationId = @bigOrganizationID and  IsDefault=1              
                  
/***************** Organization Statistics ******************************************************************/              
 --SELECT COUNT(VehicleId) as 'No of Vehicles' from rvlfVehicle where OrganizationId = @bigOrganizationID              
              
 --SELECT SUM(CASE WHEN SUBSTRING(B.LastSensorMask,6,1) =1 and b.LastSpeed > 0 THEN 1 ELSE 0 END) as Moving,              
 -- SUM(CASE WHEN SUBSTRING(b.LastSensorMask,6,1) =1 and b.LastSpeed = 0 THEN 1 ELSE 0 END) as Idling,              
 -- SUM(CASE WHEN SUBSTRING(b.LastSensorMask,6,1) =0 THEN 1 ELSE 0 END) as Parked               
 --FROM rvlfBoxId b               
 -- WHERE B.OrganizationId = @bigOrganizationID              
              
--   select count(distinct(fv.VehicleId)) as 'No of Vehicles' from rvlfFleetUsers FU  inner join rvlfFleetVehicles fv            
-- on fv.FleetId = FU.FleetId inner join rvlfFleet f on f.FleetId = fv.FleetId             
-- inner join rvlfVehicleAssignment VA on VA.VehicleId = FV.VehicleId            
-- where FU.UserId= @bigQueryingUser and f.OrganizationId =@bigOrganizationID            
             
--;WITH cteVehicleStatus AS            
            
--(SELECT DISTINCT(b.BoxId),b.LastSensorMask,b.LastSpeed            
--FROM rvlfBoxId b INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId            
--INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = va.VehicleId            
--INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId INNER JOIN rvlfFleetUsers fu ON fu.FleetId=f.FleetId            
--INNER JOIN rvlfUser u ON u.UserId = fu.UserId WHERE u.UserId=@bigQueryingUser)             
--SELECT isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0 THEN 1 ELSE 0 END),0) as Moving,             
--isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN 1 ELSE 0 END),0) as Idling,             
--isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =0 THEN 1 ELSE 0 END),0) as Parked  FROM            
            
--cteVehicleStatus            
            
 declare @IsAngAdmin int             
 select @IsAngAdmin =(case when UserGroupId = 1 then 1  else 0 end) from rvlfUserGroupAssignment where UserId= @bigQueryingUser            
             
 if(@IsAngAdmin=1)            
 begin            
              
  select count(distinct(fv.VehicleId)) as 'No of Vehicles' from rvlfFleetUsers FU  inner join rvlfFleetVehicles fv              
 on fv.FleetId = FU.FleetId inner join rvlfFleet f on f.FleetId = fv.FleetId               
 inner join rvlfVehicleAssignment VA on VA.VehicleId = FV.VehicleId              
 where f.OrganizationId =@bigOrganizationID              
               
;WITH cteVehicleStatus AS              
              
(SELECT DISTINCT(b.BoxId),b.LastSensorMask,b.LastSpeed              
FROM rvlfBoxId b INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId              
INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = va.VehicleId              
INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId INNER JOIN rvlfFleetUsers fu ON fu.FleetId=f.FleetId              
INNER JOIN rvlfUser u ON u.UserId = fu.UserId where u.OrganizationId= @bigOrganizationID)               
SELECT isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0 THEN 1 ELSE 0 END),0) as Moving,               
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN 1 ELSE 0 END),0) as Idling,               
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =0 THEN 1 ELSE 0 END),0) as Parked  FROM              
              
cteVehicleStatus              
 end            
 else            
 begin            
  select count(distinct(fv.VehicleId)) as 'No of Vehicles' from rvlfFleetUsers FU  inner join rvlfFleetVehicles fv              
 on fv.FleetId = FU.FleetId inner join rvlfFleet f on f.FleetId = fv.FleetId               
 inner join rvlfVehicleAssignment VA on VA.VehicleId = FV.VehicleId              
 where FU.UserId= @bigQueryingUser and f.OrganizationId =@bigOrganizationID              
               
;WITH cteVehicleStatus AS              
              
(SELECT DISTINCT(b.BoxId),b.LastSensorMask,b.LastSpeed              
FROM rvlfBoxId b INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId              
INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = va.VehicleId              
INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId INNER JOIN rvlfFleetUsers fu ON fu.FleetId=f.FleetId              
INNER JOIN rvlfUser u ON u.UserId = fu.UserId WHERE u.OrganizationId = @bigOrganizationID and u.UserId=@bigQueryingUser)               
SELECT isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0 THEN 1 ELSE 0 END),0) as Moving,               
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN 1 ELSE 0 END),0) as Idling,               
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =0 THEN 1 ELSE 0 END),0) as Parked  FROM              
              
cteVehicleStatus              
 end             
DECLARE @tblDashboardChartIndex table              
  (
    ChartIndex int
  )              
  insert into @tblDashboardChartIndex
  select * from rvlf_fn_ConvertArrayToTable(@VarUserPreferedChart,',')                            
/********************* Alarms *******************************************************************************/              
              
 --SELECT TOP (@bigTopNos) SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) as CriticalAlarms,              
 --   a.BoxID,v.VehicleDescription,                 
 --  v.VehicleDescription  as VehicleName              
 -- FROM rvlfAlarm a              
 --  INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId              
 --  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId              
 --  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId              
 -- WHERE               
 --  (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID) AND              
 --  (@bigFleetID IS NULL OR fv.FleetId = @bigFleetID) AND               
 --  ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR              
 --    a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
 -- GROUP BY a.BoxId, v.VehicleDescription,v.VehicleDescription,OrganizationId              
 -- HAVING              
 --    SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) >0              
 -- ORDER BY               
 --  CASE WHEN OrganizationId=55 THEN a.BoxId END ASC,CriticalAlarms DESC              
 if Exists(select * from @tblDashboardChartIndex where ChartIndex =1)
 begin  
 select Alarms.CriticalAlarms,Alarms.BoxId,Alarms.VehicleDescription,Alarms.VehicleName, row_number() over(order by Alarms.CriticalAlarms DESC) as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,isnull(DriverDetails,'-') as DriverDetails   from              
  (SELECT TOP (@bigTopNos) SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) as CriticalAlarms,              
    a.BoxID,v.VehicleDescription,                 
   v.VehicleDescription  as VehicleName,            
   dm.DisplayName + ' (' + isnull(DM.MobileNo,'-') + ')' as DriverDetails                
  FROM rvlfAlarm a              
   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId              
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId              
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId     
   LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId in (select Top 1 DA.DriverId from rvlfDriverAssignment DA where DA.Boxid = va.BoxId order by Da.AssignmentId desc)                             
  WHERE               
   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND              
   (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) AND               
   ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR              
     a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)                   
  GROUP BY a.BoxId, v.VehicleDescription,v.VehicleDescription,v.OrganizationId,dm.DisplayName,DM.MobileNo                 
  HAVING              
     SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) >0              
  ORDER BY               
   CASE WHEN v.OrganizationId=55 THEN a.BoxId END ASC,CriticalAlarms DESC)as Alarms                
   end          
  else          
  begin          
  select Null as CriticalAlarms,Null as BoxId,Null as VehicleDescription,Null as VehicleName, Null as  PasGenerateddate,Null as DriverDetails Where 1 = 2
  end                
  --/********************* Running vs Idling ********************/              
	 DECLARE @tblIdlingInfo table  
  (  
   BoxID int,  
   VehicleDescription nvarchar(50),  
   VehicleName nvarchar(50),  
   IdlingTime int,  
   RunningTime int,  
   Distance int  
  )  
 
  DECLARE @tblMessageForProcessingTrip 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  @TBLSTART 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  @TBLSTOP   Table     
 (            
  Boxid int,            
  StopTime datetime,            
  OdoEnd bigint,            
  EndAddress varchar(300),            
  tripId int,            
  Lat numeric(10,6),            
  Long numeric(10,6),            
 IsTripCompleted bit            
 )   

Declare   @tblTripDetailsForTD TABLE(            
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,            
  [BoxId] [int] NOT NULL,            
  [StartDate] [datetime] NOT NULL,            
  [EndDate] [datetime] NULL,            
  [OdometerStart] [bigint] NOT NULL,            
  [OdometerEnd] [bigint] NULL,            
  [IsTripClosed] [bit] NULL,            
  [IdlingDuration] [int] NULL,            
  [StopTime] [int] NULL,            
  [StartAddress] nvarchar(300) NULL,            
  [EndAddress] nvarchar(300) NULL,            
  [Speed] int NULL,            
  [RunningTime] int null,            
  StartLat numeric(10,6),            
  StartLong numeric(10,6),            
  StopLat numeric(10,6),            
  StopLong numeric(10,6)              
 )   
  INSERT INTO @tblIdlingInfo (BoxID, VehicleDescription, VehicleName)              
    SELECT va.BoxId , v.VehicleDescription  AS VEH,v.VehicleDescription as VehicleDescription  
          FROM rvlfVehicleAssignment va   
           INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
           INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
          WHERE(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)   
           AND (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID)            
    
  DECLARE @intBoxLooping INT =(SELECT MIN(BoxID) FROM @tblIdlingInfo)  
    
  WHILE @intBoxLooping IS NOT NULL  
   BEGIN  
    
    -- GET THE MSGS FOR THE BOXID            
    DELETE FROM @tblMessageForProcessingTrip                 
    INSERT INTO @tblMessageForProcessingTrip(OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,OdoMeter,Lat,Long)            
      SELECT  h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,
      CASE WHEN @bigOrganizationID=23 AND BoxMsgInTypeId=2 AND CustomProp like 'SENSOR_NUM=2;%' THEN 1 ELSE CAST(SUBSTRING(sensormask,6,1) as bit) END,
      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.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate    
        ORDER BY h.origindatetime ASC             
                    
    -- GET THE IGNITION ON DETAILS            
    DELETE FROM @TBLSTART                 
    INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)            
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long             
     FROM @tblMessageForProcessingTrip                   
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
      AND BoxMsgInTypeId IN(2)            
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)            
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)              
      AND Ignition=1 AND (@bigOrganizationID <> 23 OR (@bigOrganizationID=23 AND CustomProp LIKE '%SENSOR_NUM=2%'))
      --AND CustomProp LIKE '%SENSOR_NUM=3%'            
                   
                 
    --GET THE IGNITION OFF DETAILS               
    DELETE FROM @TBLSTOP             
    INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)            
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                
     FROM @tblMessageForProcessingTrip              
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
      AND BoxMsgInTypeId IN(3)            
      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)            
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip             
       WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)              
       AND (@bigOrganizationID <> 23 OR (@bigOrganizationID=23 AND CustomProp LIKE '%SENSOR_NUM=2%'))
                
    --CHECK THE ONGOING TRIPS             
    --IF ((SELECT TOP 1 BoxMsgInTypeId FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) ORDER BY OriginDateTime DESC)=2)            
    -- BEGIN            
    --  INSERT INTO #TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)            
    --   SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long             
    --    FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC                 
    -- IF EXISTS(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)            
    --    AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime            
    --    FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC)                    
    --  BEGIN                    
    --   INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long,IsTripCompleted)            
    --    --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,OdoMeter,Address,Lat,Long,0             
    --    SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long,0             
    --    FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)            
    --     AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime            
    --     FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC            
    --  END             
    -- ELSE            
    --  BEGIN            
    --   INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)            
    --    --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                     
    --    SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                     
    --  END              
    -- END            
                     
    --PREPARE THE TRIPS AND DETAILS                
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )             
    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 @TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                
                  
      IF @DTSTOPSTART IS NOT NULL                     
       UPDATE top(1) @TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART             
                  
      SET @DTSTOPSTART=@DTSTART             
      SET @DTEND=NULL            
      SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART             
                  
      UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART             
      UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND              
      UPDATE top(1) @TBLSTART SET Speed =(SELECT MAX(SPEED) FROM @tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),            
      idling=(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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9             
        AND CustomProp NOT LIKE '%Idling:0;%'),            
       --Running=(SELECT ISNULL(SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,            
       --(CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60,0)                         
       --FROM #tblMessageForProcessingTrip             
       --WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =3)            
       Running=DATEDIFF(S,@DTSTART,@DTEND)            
       WHERE tripId=@INC AND StartTime=@DTSTART             
                   
      SET @INC =@INC +1            
                  
      SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART            
                  
     END             
                       
    --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME            
    UPDATE @TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END             
     WHERE Running IS NOT NULL            
                
    --INSERT THE DETAILS IN THE MASTER TABLE            
    INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,            
     OdometerEnd,IdlingDuration,Speed, IsTripClosed,StopTime,RunningTime,StartLat,StartLong,StopLat,StopLong)             
    SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,S.idling,            
     S.Speed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running,S.Lat,S.Long,ST.Lat,ST.Long            
      FROM @TBLSTART S            
       INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId                      
                 
   SELECT @intBoxLooping = MIN(BoxID) from @tblIdlingInfo WHERE BoxID > @intBoxLooping            
               
   UPDATE @tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM @tblTripDetailsForTD)           
   
    
  END  
  
  DECLARE @TBLSUMMARY TABLE            
  (            
   Boxid int,            
   RunningTime int,            
   IdlingTime int,            
   StopTime int,
   Distance bigint            
  )            
 INSERT INTO @TBLSUMMARY (Boxid,RunningTime,IdlingTime,StopTime,Distance)            
 SELECT BoxId,SUM(RunningTime),SUM(IdlingDuration),SUM(StopTime),SUM(OdometerEnd-OdometerStart) FROM @tblTripDetailsForTD t where t.IsTripClosed = 1 GROUP BY BoxId             

  --select * from @tblTripDetailsForTD
  if Exists(select * from @tblDashboardChartIndex where ChartIndex =2) 
begin                  
  DECLARE @QueryingTime INT=DateDiff(MINUTE,@dtstartDate,@dtendDate)              
                    
   select distinct Idling.BoxID,Idling.IdlingTime,Idling.RunningTime,              
   Idling.IdlingTimeFormatted,Idling.RunningTimeFormatted,Idling.VehicleDescription,Idling.VehicleName,Idling.RunningPercentage,Idling.IdlingPercentage,Idling.QueryingTimePercentage,row_number() over(order by Idling.RunningTime DESC) as IdlingRowno,Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,ISNULL(DriverDetails,'-') as DriverDetails    from              
      (              
   SELECT TOP(@bigTopNos) td.BoxID,CEILING(IdlingTime / 60.00) AS IdlingTime,CEILING(RunningTime / 60.00) AS RunningTime,              
    dbo.rvlf_fn_GetTimeFromSeconds(IdlingTime) as IdlingTimeFormatted,              
    dbo.rvlf_fn_GetTimeFromSeconds(RunningTime) as RunningTimeFormatted,VehicleDescription,VehicleDescription as VehicleName,               
    (CASE WHEN RunningTime > 0 THEN (CEILING(RunningTime/60) * 100 /@QueryingTime) ELSE 0 END) AS RunningPercentage,                 
    Ceiling((CASE WHEN IdlingTime > 0 AND RunningTime > 0 THEN ((IdlingTime) * 100 /(RunningTime)) Else 0 End)) AS IdlingPercentage,              
    @QueryingTime QueryingTime, 100 as QueryingTimePercentage,dm.DisplayName + ' (' + isnull(DM.MobileNo,'-') + ')' as DriverDetails              
   FROM @TBLSUMMARY TD
   inner join rvlfVehicleAssignment va on va.BoxId = TD.BoxId
   inner join rvlfVehicle v on v.VehicleId =va.VehicleId
   LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId in (select Top 1 DA.DriverId from rvlfDriverAssignment DA where DA.Boxid = va.BoxId order by DA.AssignmentId desc)                           
   WHERE  RunningTime > 0 --OR IdlingTime > 0             
   ORDER BY CEILING(RunningTime / 60.00) DESC
   ) as Idling 
      end               
  else          
  begin          
  select distinct Null as BoxID,Null as IdlingTime,Null as RunningTime,              
   Null as IdlingTimeFormatted,Null as RunningTimeFormatted,Null as VehicleDescription,Null as VehicleName,Null as RunningPercentage,Null as IdlingPercentage,Null as QueryingTimePercentage,Null as IdlingRowno,Null as PasGenerateddate,Null as DriverDetails  Where 1 = 2
  end  
	-------------***********************************************************************--/
              
  --DECLARE @tblIdlingInfo table              
  --(              
  -- BoxID int,              
  -- VehicleDescription varchar(50),              
  -- VehicleName varchar(50),              
  -- IdlingTime int,              
  -- RunningTime int,              
  -- Distance int,    
  -- DriverDetails nvarchar(max)                      
  --)              
  --DECLARE @tblmsg table              
  --(                 
  -- BoxmsgtypeId tinyint,              
  -- Orgindatetime datetime,              
  -- CustomProp varchar(600)              
  --)              
  --INSERT INTO @tblIdlingInfo (BoxID, VehicleDescription, VehicleName,DriverDetails)                          
  --  SELECT va.BoxId , v.VehicleDescription AS VEH,v.VehicleDescription,    
  --   dm.DisplayName + ' (' + isnull(DM.MobileNo,'-') + ')'as DriverDetails                                
  --        FROM rvlfVehicleAssignment va               
  --         INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId              
  --         INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId     
  --         LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId in (select Top 1 DA.DriverId from rvlfDriverAssignment DA where DA.Boxid = va.BoxId order by DA.AssignmentId desc)                           
  --        WHERE(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)               
  --         AND (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID)                                   
                
  --DECLARE @IntBoxLoop INT =(SELECT MIN(BoxID) FROM @tblIdlingInfo)              
                
  --WHILE @IntBoxLoop IS NOT NULL              
  -- BEGIN              
  --  DECLARE @dtIsIgnitionoff DATETIME =NULL,@dtIsIdlingEnd DATETIME =NULL,@dtOdometerSetDate DATETIME=NULL,@SetOdometer BIGINT=0,        
  --   @MaxOdometer BIGINT=0,@StartOdometer BIGINT=0,@EndOdometer BIGINT=0;              
                  
  --  --CHECK IF ANY SET ODOMETER COMMAND FOR THE BOXID              
  --  SELECT TOP 1 @dtOdometerSetDate=SentDateTime, @SetOdometer=CustomProp               
  --   FROM rvlfMsgOutHst                    
  --    WHERE BoxCmdOutTypeId =14 AND BoxId=@IntBoxLoop               
  --     AND SentDateTime BETWEEN @dtStartDate AND @dtEndDate               
  --   ORDER BY SentDateTime DESC              
                   
  --  DELETE FROM @tblmsg               
  --  INSERT INTO @tblmsg(BoxmsgtypeId,CustomProp,Orgindatetime)              
  --   SELECT BoxMsgInTypeId,CustomProp,OriginDateTime                
  --    FROM rvlfMsgInHst               
  --     WHERE BoxMsgInTypeId IN(2,3,9)                      
  --      AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate              
  --      AND BoxId = @IntBoxLoop            
  --     ORDER BY OriginDateTime                
               
  --  --CHECK IF THE FIRST MSG IS IGNITION OFF OR NOT               
  --  IF ((SELECT TOP 1 BoxmsgtypeId FROM @tblmsg WHERE BoxmsgtypeId IN(2,3) AND CustomProp LIKE '%SENSOR_NUM=3;%')=3)              
  --   BEGIN                   
  --       UPDATE @tblIdlingInfo SET RunningTime =ISNULL(RunningTime,0)+(SELECT TOP 1 DATEDIFF(SECOND,@dtStartDate,Orgindatetime) FROM @tblmsg WHERE BoxmsgtypeId =3)              
  --       WHERE BoxID=@IntBoxLoop              
  --       SELECT TOP 1 @dtIsIgnitionoff=Orgindatetime FROM @tblmsg WHERE BoxmsgtypeId =3              
                       
  --       SELECT TOP 1 @StartOdometer=CAST(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,              
  --      (CHARINDEX(';',CustomProp,              
  --      CHARINDEX('Odometer=',CustomProp,1))) -              
  --    (CHARINDEX('Odometer=',CustomProp,1)+9)) AS BIGINT)               
  --    FROM rvlfMsgInHst                 
  --     WHERE  BoxId=@IntBoxLoop                
  --      AND CustomProp LIKE '%Odometer%'               
  --      AND OriginDateTime BETWEEN @dtStartDate AND @dtIsIgnitionoff              
  --     ORDER BY OriginDateTime ASC               
  --   END                         
  --  --CHECK IF THE FIRST MSG IS IDLING END OR NOT               
  --  IF((SELECT TOP 1 CAST(SUBSTRING (CustomProp,CHARINDEX('Idling:',CustomProp,1)+7,              
  --    CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,1)) -               
  --    (CHARINDEX('Idling:',CustomProp,1)+7)) as int) FROM @tblmsg WHERE BoxmsgtypeId=9)<> 0)              
  --   BEGIN              
  --    UPDATE @tblIdlingInfo SET IdlingTime =ISNULL(IdlingTime,0)+(SELECT TOP 1 DATEDIFF(SECOND,@dtStartDate,Orgindatetime) FROM @tblmsg WHERE BoxmsgtypeId =9)              
  --       WHERE BoxID=@IntBoxLoop               
  --       SELECT TOP 1 @dtIsIdlingEnd=Orgindatetime FROM @tblmsg WHERE BoxmsgtypeId =9              
  --   END              
                 
  --    --CALCULATE THE RUNNING TIME AND IDLING FOR REMAINING MSGS              
  --    DECLARE @intRunning int =null,@intIdling int =null              
  --    SELECT @intRunning= SUM(ISNULL(CAST(SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,              
  --    CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -               
  --    (CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int),0))*60              
  --    FROM @tblmsg               
  --    WHERE BoxmsgtypeId=3              
  --     AND (@dtIsIgnitionoff IS NULL OR @dtIsIgnitionoff='' OR Orgindatetime>@dtIsIgnitionoff)           
  --    GROUP BY BoxmsgtypeId              
         
  --    SELECT @intIdling=SUM(ISNULL(CAST(SUBSTRING (CustomProp,CHARINDEX('Idling:',CustomProp,1)+7,              
  --    CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,1)) -               
  --    (CHARINDEX('Idling:',CustomProp,1)+7)) as int),0))                
  --    FROM @tblmsg               
  --    WHERE BoxmsgtypeId =9               
  --     AND (@dtIsIdlingEnd IS NULL or @dtIsIdlingEnd='' OR Orgindatetime>@dtIsIdlingEnd)  
  --     AND CustomProp NOT LIKE '%Idling:0;%'                 
  --    GROUP BY BoxmsgtypeId              
  --    UPDATE @tblIdlingInfo SET               
  --   RunningTime =ISNULL(RunningTime,0)+ ISNULL(@intRunning,0),              
  --   IdlingTime =ISNULL(IdlingTime,0)+ISNULL(@intIdling,0)                    
  --   WHERE BoxID =@IntBoxLoop               
                   
  --  --CHECK IF THE LAST MSG IS IGNITION ON OR NOT              
  --  IF ((SELECT TOP 1 BoxmsgtypeId FROM @tblmsg WHERE BoxmsgtypeId IN(2,3) AND CustomProp LIKE '%SENSOR_NUM=3;%' ORDER BY Orgindatetime DESC)=2)              
  --   BEGIN              
  --       UPDATE @tblIdlingInfo SET RunningTime =ISNULL(RunningTime,0)+ (SELECT TOP 1 DATEDIFF(SECOND,Orgindatetime,@dtEndDate) FROM @tblmsg WHERE BoxmsgtypeId =2  AND CustomProp LIKE '%SENSOR_NUM=3;%' ORDER BY Orgindatetime DESC)              
  --       WHERE BoxID=@IntBoxLoop                
                       
  --       SELECT TOP 1 @EndOdometer=CAST(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,              
  --      (CHARINDEX(';',CustomProp,              
  --      CHARINDEX('Odometer=',CustomProp,1))) -              
  --      (CHARINDEX('Odometer=',CustomProp,1)+9)) AS BIGINT)               
  --    FROM rvlfMsgInHst                 
  --     WHERE BoxId=@IntBoxLoop                
  --      AND CustomProp LIKE '%Odometer%'              
  --      AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate               
  --     ORDER BY OriginDateTime DESC                       
  --   END              
          
  --  ----CHECK IF THE BOXID DONT HAVE ANY IGNITION ON/OFF WITH IN THE QUERING TIME.              
  --  --IF NOT EXISTS(SELECT BoxmsgtypeId FROM @tblmsg WHERE BoxmsgtypeId IN(2,3) AND CustomProp LIKE '%SENSOR_NUM=3;%')              
  --  -- BEGIN              
  --  --  IF((SELECT COUNT(BoxmsgtypeId) FROM @tblmsg)>0)              
  --  --   BEGIN              
  --  --    IF ((SELECT TOP 1 BoxMsgInTypeId FROM rvlfMsgInHst WHERE BoxId=@IntBoxLoop AND BoxMsgInTypeId IN(2,3) AND CustomProp LIKE '%SENSOR_NUM=3;%' AND OriginDateTime <@dtStartDate ORDER BY OriginDateTime DESC)=2)              
  --  --     BEGIN          
  --  --        UPDATE @tblIdlingInfo SET RunningTime =ISNULL(RunningTime,0)+(SELECT TOP 1 DATEDIFF(SECOND,@dtStartDate,@dtEndDate))              
  --  --        WHERE BoxID=@IntBoxLoop               
  --  --     END              
  --  --   END              
  --  -- END              
                   
  --  --CALCULATE THE DISTANCE               
  --  IF @dtOdometerSetDate IS NOT NULL OR @dtOdometerSetDate !=''              
  --  BEGIN              
  --   SELECT @MaxOdometer=(SELECT TOP 1 MAX(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,              
  --     (CHARINDEX(';',CustomProp,              
  --     CHARINDEX('Odometer=',CustomProp,1))) -              
  --     (CHARINDEX('Odometer=',CustomProp,1)+9)))               
  --    FROM @tblmsg                
  --     WHERE Orgindatetime BETWEEN @dtStartDate AND @dtOdometerSetDate               
  --      AND CustomProp LIKE '%Odometer%')                    
                    
  --  END              
  -- IF @StartOdometer IS NULL OR @StartOdometer =''              
  --  SELECT TOP 1 @StartOdometer=CAST(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,              
  --      (CHARINDEX(';',CustomProp,              
  --      CHARINDEX('Odometer=',CustomProp,1))) -              
  --      (CHARINDEX('Odometer=',CustomProp,1)+9)) AS BIGINT)               
  --    FROM @tblmsg                
  --     WHERE CustomProp LIKE '%Odometer%'              
  --     ORDER BY Orgindatetime ASC                
                         
  -- IF @EndOdometer IS NULL OR @EndOdometer =''                
  --  SELECT TOP 1 @EndOdometer=CAST(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,              
  --      (CHARINDEX(';',CustomProp,              
  --      CHARINDEX('Odometer=',CustomProp,1))) -              
  --      (CHARINDEX('Odometer=',CustomProp,1)+9)) AS BIGINT)               
  --    FROM @tblmsg                
  --     WHERE CustomProp LIKE '%Odometer%'              
  --     ORDER BY Orgindatetime DESC                  
                      
  -- UPDATE @tblIdlingInfo SET Distance =CASE WHEN @SetOdometer =0 OR @SetOdometer IS NULL THEN           
  --  CEILING((@EndOdometer - @StartOdometer)*@ConversionFactor)               
  --  ELSE CEILING(((@MaxOdometer - @StartOdometer) + (@EndOdometer - @SetOdometer)) *@ConversionFactor) END              
  -- WHERE BoxID=@IntBoxLoop               
                  
  -- SELECT @IntBoxLoop=MIN(BoxID)FROM @tblIdlingInfo WHERE BoxID>@IntBoxLoop                   
                
  --END              
  -- DECLARE @QueryingTime INT=DateDiff(MINUTE,@dtstartDate,@dtendDate)              
                    
  -- select distinct Idling.BoxID,Idling.IdlingTime,Idling.RunningTime,              
  -- Idling.IdlingTimeFormatted,Idling.RunningTimeFormatted,Idling.VehicleDescription,Idling.VehicleName,Idling.RunningPercentage,Idling.IdlingPercentage,Idling.QueryingTimePercentage,row_number() over(order by Idling.RunningTime DESC) as IdlingRowno,Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,ISNULL(DriverDetails,'-') as DriverDetails    from              
  --    (              
  -- SELECT TOP(@bigTopNos) BoxID,CEILING(IdlingTime / 60.00) AS IdlingTime,CEILING(RunningTime / 60.00) AS RunningTime,              
  --  dbo.rvlf_fn_GetTimeFromSeconds(IdlingTime) as IdlingTimeFormatted,              
  --  dbo.rvlf_fn_GetTimeFromSeconds(RunningTime) as RunningTimeFormatted,VehicleDescription, VehicleName,               
  --  (CASE WHEN RunningTime > 0 THEN (CEILING(RunningTime/60) * 100 /@QueryingTime) ELSE 0 END) AS RunningPercentage,                 
  --  Ceiling((CASE WHEN IdlingTime > 0 AND RunningTime > 0 THEN ((IdlingTime) * 100 /(RunningTime)) Else 0 End)) AS IdlingPercentage,              
  --  @QueryingTime QueryingTime, 100 as QueryingTimePercentage,DriverDetails              
  -- FROM @tblIdlingInfo               
  -- WHERE  RunningTime > 0 --OR IdlingTime > 0             
  -- ORDER BY RunningTime DESC
  -- ) as Idling              
                 
 /**************** Speed Alerts ****************************************************************************/              
 --SELECT TOP (@bigTopNos)               
 --  SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END) as SpeedAlerts,              
 --   a.BoxID,v.VehicleDescription,                 
 --  v.VehicleDescription VehicleName              
 -- FROM rvlfMsgInHst  a              
 --  INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId              
 --  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId              
 --  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId              
 -- WHERE(@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID)               
 --  AND(@bigFleetID IS NULL OR fv.FleetId = @bigFleetID)               
 --  AND((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR              
 --    a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)              
 --  AND BoxMsgInTypeId=4              
 -- GROUP BY a.BoxId, v.VehicleDescription,v.DisplayName              
 -- HAVING SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END)>0              
 -- ORDER BY SpeedAlerts DESC              
               
 --Included by ranjith for Dashboard Code Optimization              
 if Exists(select * from @tblDashboardChartIndex where ChartIndex =3) 
begin           
 select SpeedAlert.SpeedAlerts,SpeedAlert.BoxId,SpeedAlert.VehicleDescription,SpeedAlert.VehicleName, row_number() over(order by SpeedAlert.SpeedAlerts desc) as SpeedAlertRowno,isnull(DriverDetails,'-') as DriverDetails,             
 PasGenerateddate =dbo.rvlf_fn_DayLightSavings(GETUTCDATE(),@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())            
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate         
  from (SELECT distinct top (@bigTopNos)               
   SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END) as SpeedAlerts,              
    a.BoxID,v.VehicleDescription,              
   --v.DisplayName  as VehicleName              
   v.VehicleDescription VehicleName,    
    dm.DisplayName  + ' (' + isnull(DM.MobileNo,'-') + ')' as DriverDetails              
  FROM rvlfMsgInHst  a              
   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId              
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId              
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId    
   LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId in (select Top 1 DA.DriverId from rvlfDriverAssignment DA where DA.Boxid = va.BoxId order by DA.AssignmentId Desc)                              
  WHERE               
   (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND              
   (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID)               
   AND               
   ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR              
     a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)              
  GROUP BY a.BoxId, v.VehicleDescription,v.DisplayName,dm.DisplayName,DM.MobileNo                
  HAVING SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END)>0              
  ORDER BY               
  --CASE WHEN               
  SpeedAlerts DESC) as SpeedAlert              
   end               
  else          
  begin          
  select Null as SpeedAlerts,Null as BoxId,Null as VehicleDescription,Null as VehicleName, Null as  SpeedAlertRowno,Null as DriverDetails, Null as  PasGenerateddate  Where 1 = 2
  end               
               
 /***************** Distance Travelled ****************************************************************/    
 if Exists(select * from @tblDashboardChartIndex where ChartIndex =4)
 begin          
 select Distance.BoxID,Distance.VehicleDescription,Distance.VehicleName,Distance.DistanceTravelled,Distance.CaptionPrefix, row_number() over(order by DistanceTravelled DESC) as DistanceRowno,isnull(DriverDetails,'-') as DriverDetails,            
 PasGenerateddate =dbo.rvlf_fn_DayLightSavings(GETUTCDATE(),@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())                  
  --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate        
  
    from  ( SELECT TOP (@bigTopNos) td.BoxID,VehicleDescription,VehicleDescription as VehicleName,CEILING((ABS(ISNULL((TD.Distance), 0)) * @ConversionFactor)) as DistanceTravelled,@CaptionPrefix as CaptionPrefix,
    dm.DisplayName + ' (' + isnull(DM.MobileNo,'-') + ')' as DriverDetails                        
  FROM @TBLSUMMARY TD
   inner join rvlfVehicleAssignment va on va.BoxId = TD.BoxId
   inner join rvlfVehicle v on v.VehicleId =va.VehicleId
   LEFT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId in (select Top 1 DA.DriverId from rvlfDriverAssignment DA where DA.Boxid = va.BoxId order by DA.AssignmentId desc)                                      
  WHERE CEILING((ABS(ISNULL((TD.Distance), 0)) * @ConversionFactor)) > 0 and len(CEILING((ABS(ISNULL((TD.Distance), 0)) * @ConversionFactor))) <=4     
 ORDER BY CEILING((ABS(ISNULL((TD.Distance), 0)) * @ConversionFactor)) DESC) as Distance                 
 END   
Else
Begin
select Null as BoxID,Null as VehicleDescription,Null as VehicleName,Null as DistanceTravelled,Null as CaptionPrefix, Null as  DistanceRowno,Null as  DriverDetails,            
 Null as  PasGenerateddate  Where 1 = 2
End           
          
 --********************************************************************/               
 --select Distance.BoxID,Distance.VehicleDescription,Distance.VehicleName,Distance.DistanceTravelled,Distance.CaptionPrefix, row_number() over(order by DistanceTravelled DESC) as DistanceRowno,isnull(DriverDetails,'-') as DriverDetails,            
 --PasGenerateddate =dbo.rvlf_fn_DayLightSavings(GETUTCDATE(),@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())            
 -- --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate        
 
     
      
 --   from  ( SELECT TOP (@bigTopNos) BoxID,VehicleDescription,VehicleName,Distance as DistanceTravelled,@CaptionPrefix as CaptionPrefix,DriverDetails              
 -- FROM @tblIdlingInfo                
 -- WHERE Distance > 0 and len(CEILING(Distance)) <=4         
 --ORDER BY Distance DESC) as Distance            
            
/***************** Get login active users ****************************************************************/                 
SELECT COUNT(UserId)AS ActiveUsers             
FROM rvlfUserLogin             
WHERE CONVERT(DATE,LoginDateTime)=CONVERT(DATE,GETUTCDATE()) AND LogOffDateTime IS NULL            
UNION ALL            
SELECT COUNT(UserId) AS InternalUsers            
FROM rvlfUserLogin UL             
WHERE CONVERT(DATE,LoginDateTime)=CONVERT(DATE,GETUTCDATE()) AND LogOffDateTime IS NULL AND OrgId IN(1,6)            
        
            
/***************** Get User Prefered Chart****************************************************************/            
  --SELECT distinct(UP.UserPreferedChart) from rvlfUserPreferences UP            
  --INNER JOIN rvlfUserLoginDetails UL ON UL.UserId = UP.UserId            
  --WHERE UP.UserId = @bigUserID             
  DECLARE @List as varchar(max)              
  DECLARE @ISExport  int              
  SELECT @ISExport = ug.OperationTypeId  from rvlfOperationType op               
  INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId               
  INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId              
  INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId              
  INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId              
  INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId              
  INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId                
  WHERE  ga.UserId = @bigQueryingUser and ug.ModuleId = 1 and ug.OperationTypeId not in (1,2,3,4)              
              
  --SELECT distinct(case when @ISExport is not null or @ISExport = '' then @VarUserPreferedChart + ',5' else @VarUserPreferedChart end)                
                
  DECLARE @tblmsgs table                    
  (                       
  OperationTypeId varchar,              
  Export  Bigint               
  )              
  insert into @tblmsgs(OperationTypeId,Export)               
  select  distinct(ug.OperationTypeId), Export = case when ug.OperationTypeId in (1,2,3,4,5) Then '5'  END   from rvlfOperationType op               
  INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId               
  INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId              
  INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId              
  INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId              
  INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId              
  INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId               
  where ga.UserId = @bigQueryingUser and ug.ModuleId = 1 order by ug.OperationTypeId  desc               
  SELECT @List = case  WHEN  @ISExport is not  null THEN COALESCE(@List + ',','5,') + cast(OperationTypeId as varchar(25)) ELSE   COALESCE(@List + ',','') + cast(OperationTypeId as varchar(25))  END  from @tblmsgs where OperationTypeId  in 
  (SELECT * FROM rvlf_fn_ConvertArrayToTable(@VarUserPreferedChart, ','))              
  SELECT @List as OperationTypeId           
             
  --  SELECT distinct(UP.UserPreferedChart) from rvlfUserPreferences UP            
  --INNER JOIN rvlfUserLoginDetails UL ON UL.UserId = UP.UserId            
  --WHERE UP.UserId = @bigQueryingUser            
     
     
        
  /****************************Fleet Statistics******************************************/      
    
 select count(distinct(fv.VehicleId)) as 'No of Vehicles' from rvlfFleetUsers FU  inner join rvlfFleetVehicles fv                
 on fv.FleetId = FU.FleetId inner join rvlfFleet f on f.FleetId = fv.FleetId                 
 inner join rvlfVehicleAssignment VA on VA.VehicleId = FV.VehicleId                
 where  f.OrganizationId =@bigOrganizationID AND    
 f.FleetId =@bigFleetID     
 --FU.UserId= @bigUserID  Unassign user for fleet    
       
 ;WITH cteVehicleStatusbyFleet AS                
(SELECT DISTINCT(b.BoxId),b.LastSensorMask,b.LastSpeed                
FROM rvlfBoxId b INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId                
INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = va.VehicleId                
INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId INNER JOIN rvlfFleetUsers fu ON fu.FleetId=f.FleetId                
LEFT OUTER JOIN rvlfUser u ON u.UserId = fu.UserId WHERE u.OrganizationId= @bigOrganizationID and     
f.FleetId =  @bigFleetID)                 
SELECT isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0 THEN 1 ELSE 0 END),0) as Moving,                 
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN 1 ELSE 0 END),0) as Idling,                 
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =0 THEN 1 ELSE 0 END),0) as Parked  FROM                
cteVehicleStatusbyFleet 

END     

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOTAAckTOSLS]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[rvlf_sp_GetOTAAckTOSLS]
	@intBoxid int=null,
	@bigVehicleID bigint = null
	
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_GetOTAAckTOSLS]999986
--	Description	:	To get to check the OTA inprogress time for SLS
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	14-Jul-2011	VN	Created Intial Version 
/****************************************************************************/
BEGIN
	SELECT TOP 1 SentDateTime as StartTime,DATEADD(HOUR,5,DATEADD(MINUTE,30,SentDateTime)) as DisplayStartTime,Acknowledged as Ack,BoxId 
		FROM rvlfMsgOutHst 
		WHERE BoxId=@intBoxid 
			AND BoxCmdOutTypeId=22 
			--AND Acknowledged IS NULL 
		ORDER BY SentDateTime DESC
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOTACommands]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetOTACommands]        
(        
 @bigVehicleID bigint = null,        
 @intBoxID int = null,        
 @dtStartDate datetime = null,        
 @dtEndDate datetime = null,        
 @bigFleetId bigint =null,        
 @bigOrganizationID bigint =NULL,        
    @bigQueryingUser bigint = 0        
)                                                                    
AS        
/******************************************************************************/        
-- Name  : rvlf_sp_GetOTACommands        
-- Description : To get the OTA commands from the messages out.        
-- Author  : M. Jebamalai Jaya Chitra.        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--    : 04-Sep-2009 MJJC Created Intial Version         
--    : 19-Aug-2010 LK  Removed the Display Name        
--    : 26-Apr-2011 LK      Included the Acknowledged '6' for 'Aborted' for OTA        
--    : 28-Jun-2011  Sakthi Gopinath S Included OTA Filename    
--    : 05-aug-2011 Ranjith Date format included
/******************************************************************************/        
BEGIN        
        
 DECLARE @HoursToBeAdded INT = 0        
 DECLARE @MinsToBeAdded INT = 0        
 DECLARE @DefaultDateFormat INT = 0        
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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        
            
    SELECT ROW_NUMBER()over (Order by SentDateTime) as SlNo, OH.BoxId, convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OH.SentDateTime)),@DefaultDateFormat) + ' ' + convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OH.SentDateTime)) as time),22) as SentDateTime, 
    DateAdd(hh,@HoursToBeAdded,OH.SentDateTime) as SentDateTimeSort,
  V.VehicleDescription AS DisplayName, VehicleDescription, OH.BoxCmdOutTypeId , CT.BoxcmdTypeDesc as Command, OH.UserId, OH.Priority,        
  CASE         
   WHEN Acknowledged = 1 THEN 'Acknowledged'         
   WHEN Acknowledged = 0 THEN 'Expired'         
   WHEN  Acknowledged = 2 THEN 'Success'        
   WHEN  Acknowledged = 3 THEN 'Update Failed'        
   WHEN  Acknowledged = 4 THEN 'CRC Incorrect'        
   WHEN  Acknowledged = 5 THEN 'No Communication'        
   WHEN  Acknowledged = 6 THEN 'Aborted'        
   WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'        
   ELSE 'Nothing' END AS Status,        
   --WHEN Acknowledged = 1 THEN 'Completed'         
   --WHEN Acknowledged = 0 THEN 'Aborted' ELSE 'Under Process' END as Status,        
  --CASE         
  -- WHEN Acknowledged = 1 THEN 1        
  -- WHEN Acknowledged = 0 THEN 0 ELSE 2 END         
  Acknowledged as StatusNo,        
  ru.UserName ,    
  REVERSE(LEFT(REVERSE(SUBSTRING(OH.CustomProp,10,CHARINDEX(',',OH.CustomProp,0)-10)), CHARINDEX('\', REVERSE(SUBSTRING(OH.CustomProp,10,CHARINDEX(',',OH.CustomProp,0)-10)))-1)) as 'FileName'    
 FROM rvlfMsgOutHst OH        
  INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID        
  INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID        
  INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId        
  INNER JOIN rvlfUser ru ON OH.UserId = ru.UserId        
  INNER JOIN rvlfFleetVehicles FV ON V.VehicleId = FV.VehicleId         
  INNER JOIN rvlfFleet F ON F.FleetId = FV.FleetId         
 WHERE         
  (@intBoxID IS NULL OR @intBoxID='' OR OH.BoxID = @intBoxID)        
  AND (@dtStartDate IS NULL OR (SentDateTime Between @dtStartDate and @dtEndDate))        
   AND OH.BoxCmdOutTypeId = 22 AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR V.OrganizationId=@bigOrganizationID)        
   AND (@bigFleetId IS NULL OR @bigFleetId='' OR F.FleetId = @bigFleetId) AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR V.VehicleId = @bigVehicleID)        
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetOTALastPacket]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_GetOTALastPacket]
 @Boxid varchar(7),
 @SeqNo varchar(7),
 @opr char='S'
 as 
 --Get the Last updated OTA SeqNo also updated the Last update / failed OTA SeqNo to start from the last packets which hav failed
 --02-Feb-16
 --SLS Services
 begin
 if @opr='U'
 update rvlfBoxId set OTASeqNoLastpdated=@SeqNo where BoxId=@Boxid
 else
 select isnull(OTASeqNoLastpdated,0) as OTASeqNoLastpdated from rvlfBoxId where BoxId=@Boxid
 end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetPackageAssignments]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetPackageAssignments]
@bigQueryingUser bigint=NULL
AS

/******************************************************************************/
--	Name		:	rvlf_sp_GetPackageAssignments
--	Description	:	To get the Package Assignment Details, Package Details,
--                  Organization which is not assigned to package
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	25-Nov-2009	LK	Created Intial Version 
--              :   12-Jan-2010 LK  Excluding the Organization Id 1 for package assignment
/******************************************************************************/
BEGIN
SET NOCOUNT ON  
	DECLARE @ConversionFactor decimal(18,2) = 1.0  
  DECLARE @DefaultDateFormat INT = 0
     
  SELECT @ConversionFactor = CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 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 = @bigQueryingUser  
  
	SELECT OP.PackageOrgId, OP.PackageId, P.PackageName, OP.OrganizationID, O.OrganizationName, Convert(varchar,OP.PurchasedOn,@DefaultDateFormat)  as PurchasedOn, Convert(varchar,OP.ExpiresOn,@DefaultDateFormat) as ExpiresOn FROM rvlfOrganizationPackage OP
	INNER JOIN rvlfOrganization O ON O.OrganizationId = OP.OrganizationID
	INNER JOIN rvlfPackage P ON P.PackageId = OP.PackageId WHERE OP.IsActive = 1 AND O.OrganizationId <> 1
	
	SELECT OrganizationId, OrganizationName FROM rvlfOrganization
	WHERE OrganizationId NOT IN (SELECT OrganizationID FROM rvlfOrganizationPackage) AND OrganizationId <> 1
	
	SELECT PackageId, PackageName FROM rvlfPackage
	
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetPackageDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetPackageDetails]
	@vcPackageName varchar(50) = NULL
AS
/**************************************************************************************/
--	Name		:	rvlf_sp_GetPackageDetails
--	Description	:	To get the package details
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	27-Nov-2009		Created Intial Version 
/**************************************************************************************/
BEGIN
SET NOCOUNT ON 
			
	SELECT P.PackageId, P.PackageName, P.PackageDesc,
	CASE WHEN EXISTS(SELECT OP.PackageId FROM rvlfOrganizationPackage OP WHERE OP.PackageId = P.PackageId AND OP.IsActive = 1)
	THEN 1 ELSE 0 END AssignedStatus 
	FROM rvlfPackage P
	WHERE (@vcPackageName IS NULL OR @vcPackageName = '' OR P.PackageName = @vcPackageName)

SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_Getparam]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_Getparam]
 (
 @bigOrganizationID bigint =NULL
 )
AS
-- =============================================
-- Author:		GK
-- Create date: 2-Sep-2019
-- Description:	Get parameter details
-- =============================================
BEGIN
SELECT a.ParamId,a.ParamName,ParamDescription,VehicleTypeId,OrganizationId FROM rvlfParamMst a 
where OrganizationId=@bigOrganizationID and ParamDescription is not null order by ParamName
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_Getparameterdetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [dbo].[rvlf_sp_Getparameterdetails] 
 @bigOrganizationID bigint =NULL,
 @bigVehicleId bigint = NULL
AS
-- =============================================
-- Author:		Asan Raj N
-- Create date: 27-Jan-2018
-- Description:	Get parameter details
--				rvlf_sp_Getparameterdetails 86,187
-- =============================================
BEGIN
DECLARE @bigEquipmentId		BIGINT = NULL
	SELECT	@bigEquipmentId = MD.BoxId 
	FROM	rvlfVehicleAssignment VA
	INNER	JOIN rvlfMAKDevices MD ON VA.BoxId = MD.BoxId
	WHERE	VA.VehicleId = @bigVehicleId

SELECT a.ParamId,a.ParamName FROM rvlfMAKDevices m 
INNER JOIN rvlfVehicle v ON m.VehicleId = v.VehicleId
INNER JOIN rvlfVehicleType vt ON vt.VehicleTypeId = v.VehicleTypeId
INNER JOIN rvlfParamMst a ON a.VehicleTypeId  = vt.VehicleTypeId
WHERE m.OrganizationId=@bigOrganizationID  and m.BoxId=@bigEquipmentId
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetParamRang]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_GetParamRang]
(
@boxid varchar(15)=null,
@vehicleid bigint= null
)
as
begin
select * from rvlfParamRange where Boxid=@boxid and IsActive=1
end
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetParentNotification_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
            
CREATE Procedure [dbo].[rvlf_sp_GetParentNotification_PhoneGap]    
(
@bigOrganizationID bigint = null,
 @intUserID        int = null  
 )           
/****************************************************************************************/            
-- Name    : rvlf_sp_GetParentNotification_PhoneGap            
-- Description   : To get the news details            
-- Author    : ranjith N         
-- Created Date  : 25-June-2015            
/***************************************************************************************/            
AS  
BEGIN            
 SET NOCOUNT ON    
                       
 SELECT top 10 row_number() over (order by NotificationId Desc) as AutoNocolumn,NotificationId,NotificationName,[Description],    
    CONVERT(varchar(20),PublishedDate,106) as PublishedDate  
 FROM rvlfNotificationToParents    where publisheddate is not null and  getutcdate() <=  expirydate                    
 Order by CONVERT(datetime,PublishedDate) desc                
  
         
 SET NOCOUNT OFF    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetParentNotifications]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 27-06-2015
-- Description:	Save,Update and Delete query for Parent Notifications
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetParentNotifications] 
	-- Add the parameters for the stored procedure here
	@bigNotificationId				bigint = NULL,
	@bigOrganizationId				bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT  NotificationId, NotificationName, Description, OrganizationId, CONVERT(VARCHAR,ExpiryDate,106) ExpiryDate, NotificationType,
			CASE WHEN NotificationType=0 THEN 'Individual' 
				 WHEN NotificationType=1 THEN 'General' 
			END AS NotificationTypeName,
			CONVERT(VARCHAR,PublishedDate,106) PublishedDate, ISNULL(IsNotificationSent,0) as IsNotificationSent
	FROM	rvlfNotificationToParents
	WHERE	OrganizationId = @bigOrganizationId 
	AND		(@bigNotificationId IS NULL OR @bigNotificationId = '' OR NotificationId = @bigNotificationId)
	ORDER BY PublishedDate
	
	SELECT * FROM rvlfNotificationToParentsLog 
	WHERE  (@bigNotificationId IS NULL OR @bigNotificationId = '' OR NotificationId = @bigNotificationId)
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetParentsDevRegIDs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 29-06-2015
-- Description:	Gets Device Ids of Parents to send notifications.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetParentsDevRegIDs]
	@NotificationId		bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
    IF((SELECT NotificationType FROM rvlfNotificationToParents WHERE NotificationId = @NotificationId) = 0)
    BEGIN 
		SELECT	DISTINCT DevRegID 
		FROM	rvlfParentMaster pm
		INNER	JOIN rvlfStudentMaster sm ON sm.ContactNo = pm.MobileNo
		LEFT OUTER	JOIN rvlfStudentMaster sm1 ON sm.AlternateContactNo = pm.MobileNo
		INNER	JOIN rvlfNotificationToParentsLog nlog ON  sm.StudentMasterID = nlog.StudentId
		WHERE	DevRegID IS NOT NULL
		AND		DevOS = 'A'
    END
    ELSE
    BEGIN
		SELECT	DevRegID 
		FROM	rvlfParentMaster 
		WHERE	DevRegID IS NOT NULL
		AND		DevOS = 'A'
	END
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetPartnerDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetPartnerDetails]        
 @bigPartnerId BIGINT=NULL,        
 @bitType BIT=NULL,        
 @bitAll bit=null        
AS        
/******************************************************************************/        
-- Name  : rvlf_sp_GetPartnerDetails null,0,0        
-- Description : To get the partner details        
-- Author  : V.Narayanasamy        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--    : 04-Aug-2010 VN Created Intial Version         
--    : 20-Oct-2011 Sakthi Add SMS Reminder column for group by clause      
--    : 06-Dec-2011 Sakthi Add DistancePercent column for group by clause      
/******************************************************************************/        
BEGIN        
 IF EXISTS(SELECT * FROM rvlfUserGroupAssignment WHERE UserId =@bigPartnerId AND UserGroupId =1)          
 BEGIN        
   SELECT O.*,'all' as status,COUNT(V.OrganizationId)AS NoOfVehicles  FROM rvlfOrganization O         
      INNER JOIN rvlfVehicle V ON V.OrganizationId=O.OrganizationId         
      --WHERE PARTNERID=@bigPartnerId         
      GROUP BY V.OrganizationId,O.Address,O.CityName,O.CngOnFirstLogin,O.ContactEmailID,O.ContactPerson,O.CountryId,        
      O.CreatedBy,O.CreatedDateTime,O.Description,O.Designation,O.EnforcePasswordPolicy,O.ExpiresOn,O.IPLockDuration,        
      O.IPTries,O.LockIP,O.LockIP,O.LockUser,O.LockUserTries,O.LogoName,O.MapGroupId,O.MapGroupId,O.MobileNo,O.ModifiedBy,        
      O.ModifiedDateTime,O.NoOfFleet,O.NoOfUsers,O.NoOfVehicles,O.OrganizationCode,O.OrganizationDisplayName,O.OrganizationEmailID,        
      O.OrganizationId,O.OrganizationName,O.OrgDistance,O.PhoneNo,O.PwdMinCharacters,O.StateName,O.TotalNoofEmailTries,O.TotalNoofSMSTries,        
      O.VATNumber,O.WebsiteURL,O.Mktg_PhoneNo,O.MaxSMSLimit,O.IsVehicleStatusNotification,O.NotificationEffectiveFrom,O.SMSReminder,O.OrgDistIncPercentValue,O.OrgMapProvider,O.OrgLatitude,O.OrgLongitude,O.OrgZoomlevel,  
      O.ISRoadSpeedEnabled   
      ,O.ContactPerson2,O.ContactPerson3,O.ContactPerson4,O.ContactPerson5,O.ContactPerson6,O.ContactEmailID2,  
      O.ContactEmailID3,O.ContactEmailID4,O.ContactEmailID5,O.ContactEmailID6,O.CurrencyTypeId,O.OrgLang,O.SMSQryCount,O.OrgLangSettings,
      O.NoOfLandmarks,O.NoOfGeozones,O.NoOfUSerGroups,O.AppExpDays,O.AppInsDate,O.AppReminder1,O.EnableApp      
      ORDER BY OrganizationName         
 END          
 ELSE        
 BEGIN        
 IF(@bitType=0)        
  BEGIN        
   SELECT * FROM rvlfUser U        
     INNER JOIN rvlfUserGroupAssignment UA ON UA.UserId=U.UserId         
    WHERE UA.UserGroupId=35 AND OrganizationId=1        
  END        
 ELSE        
  BEGIN        
   DECLARE @bigOrganizationId bigint=null        
   SELECT @bigOrganizationId=ORGANIZATIONID FROM rvlfUserPreferences WHERE UserId=@bigPartnerId         
   IF(@bitAll=1)        
    BEGIN             
     IF NOT EXISTS(SELECT * FROM rvlfUserPreferences WHERE UserId=@bigPartnerId AND OrganizationId IN(SELECT O.OrganizationId FROM RVLFPARTNERMASTER PM        
      INNER JOIN rvlfOrganization O ON O.OrganizationId=PM.ORGANIZATIONID WHERE PARTNERID=@bigPartnerId))        
      BEGIN        
       UPDATE rvlfUserPreferences SET OrganizationId=0 WHERE UserId=@bigPartnerId         
      END        
     SELECT O.* FROM RVLFPARTNERMASTER PM        
      INNER JOIN rvlfOrganization O ON O.OrganizationId=PM.ORGANIZATIONID               
      WHERE PARTNERID=@bigPartnerId         
     ORDER BY OrganizationName         
    END        
   ELSE IF(@bigOrganizationId =0)        
    BEGIN        
     SELECT O.*,'all' as status,COUNT(V.OrganizationId)AS NoOfVehicles  FROM RVLFPARTNERMASTER PM        
      INNER JOIN rvlfOrganization O ON O.OrganizationId=PM.ORGANIZATIONID        
      INNER JOIN rvlfVehicle V ON V.OrganizationId=PM.OrganizationId         
      WHERE PARTNERID=@bigPartnerId         
      GROUP BY V.OrganizationId,O.Address,O.CityName,O.CngOnFirstLogin,O.ContactEmailID,O.ContactPerson,O.CountryId,        
      O.CreatedBy,O.CreatedDateTime,O.Description,O.Designation,O.EnforcePasswordPolicy,O.ExpiresOn,O.IPLockDuration,        
      O.IPTries,O.LockIP,O.LockIP,O.LockUser,O.LockUserTries,O.LogoName,O.MapGroupId,O.MapGroupId,O.MobileNo,O.ModifiedBy,        
      O.ModifiedDateTime,O.NoOfFleet,O.NoOfUsers,O.NoOfVehicles,O.OrganizationCode,O.OrganizationDisplayName,O.OrganizationEmailID,        
      O.OrganizationId,O.OrganizationName,O.OrgDistance,O.PhoneNo,O.PwdMinCharacters,O.StateName,O.TotalNoofEmailTries,O.TotalNoofSMSTries,        
      O.VATNumber,O.WebsiteURL,O.Mktg_PhoneNo,O.MaxSMSLimit,O.IsVehicleStatusNotification,O.NotificationEffectiveFrom,O.SMSReminder,O.OrgDistIncPercentValue,O.OrgMapProvider,O.OrgLatitude,O.OrgLongitude,O.OrgZoomlevel,O.ISRoadSpeedEnabled  
      ,O.ContactPerson2,O.ContactPerson3,O.ContactPerson4,O.ContactPerson5,O.ContactPerson6,O.ContactEmailID2,  
      O.ContactEmailID3,O.ContactEmailID4,O.ContactEmailID5,O.ContactEmailID6,O.CurrencyTypeId,O.OrgLang,O.SMSQryCount,O.OrgLangSettings,
      O.NoOfLandmarks,O.NoOfGeozones,O.NoOfUSerGroups,O.AppExpDays,O.AppInsDate,O.AppReminder1,O.EnableApp  ORDER BY OrganizationName         
    END        
   ELSE        
    BEGIN        
     SELECT O.*,'default' as status FROM RVLFPARTNERMASTER PM        
      INNER JOIN rvlfOrganization O ON O.OrganizationId=PM.ORGANIZATIONID WHERE PARTNERID=@bigPartnerId AND PM.OrganizationId=@bigOrganizationId  ORDER BY OrganizationName         
    END        
  END        
 END         
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetPendingScheduleofCommands]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetPendingScheduleofCommands]  
 @dtStartDate datetime = null,  
 @dtEndDate datetime = null  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_GetPendingScheduleofCommands] '2015-08-18','2015-08-18'  
-- Description : To get and update the pending of schedule commands   
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 15-Dec-2010 VN Created Intial Version   
/******************************************************************************/  
BEGIN   
  
  --UPDATE THE ACK FOR OLD OTA MESSAGES  
  UPDATE rvlfMsgOutHst SET Acknowledged=3 WHERE BoxCmdOutTypeId =22   
   AND GETUTCDATE()>DATEADD(MINUTE,40,SentDateTime) AND Acknowledged IS NULL  
   
  --Check IF any not executed schedules are avilable or not  
  DELETE SL FROM rvlfSchedulingOfCommandsLog SL JOIN rvlfScheduleOfCommandsMaster SM ON SM.ScheduleId=SL.ScheduleId   
  WHERE SL.ResponseId IN (0,1,2,4,7,8,9,10) AND EffectiveTo < GETUTCDATE()         
    
  IF EXISTS(SELECT ScheduleId FROM rvlfScheduleOfCommandsMaster WHERE EffectiveTo < GETUTCDATE() AND NextExecutionOn IS NULL)  
  BEGIN  
   INSERT INTO rvlfSchedulingOfCommandsLog (ScheduleId,IsCommandSend,ResponseMsg,[No.ofTries],ResponseId)  
    Select ScheduleId,0,'Expired',0,6  from rvlfScheduleOfCommandsMaster where ScheduleId not in(select ScheduleId  from rvlfSchedulingOfCommandsLog) and EffectiveTo < GETUTCDATE()  
  END  
  
  DECLARE @tblInprogressCmds TABLE  
  (  
   SchedulelogId bigint,  
   ScheduleId bigint,  
   CmdSenttime datetime,  
   Boxid int,  
   BoxCmdOutTypeId tinyint  
  )  
  INSERT INTO @tblInprogressCmds (SchedulelogId,ScheduleId,Boxid,CmdSenttime,BoxCmdOutTypeId)  
   SELECT SL.ScheduleLogId,SM.ScheduleId,SM.BoxId,SL.ExecutionOn,SM.BoxCmdOutTypeId      
    FROM rvlfSchedulingOfCommandsLog SL  
     INNER JOIN rvlfScheduleOfCommandsMaster SM ON SM.ScheduleId=SL.ScheduleId   
     --INNER JOIN rvlfVehicleAssignment V ON V.VehicleId=SM.VehicleId   
     --INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId =V.VehicleId   
    WHERE (SL.IsCommandSend=0) AND SL.ResponseId = 2 AND SM.BoxCmdOutTypeId !=22    
     ORDER BY SL.ScheduleLogId   
  DECLARE @bitIsInprogress bit=0     
  DECLARE @bigScheduleLogLoop bigint=(SELECT MIN(SchedulelogId) FROM @tblInprogressCmds)  
    
  WHILE @bigScheduleLogLoop IS NOT NULL  
   BEGIN  
    DECLARE @intBoxid int=null,@bigScheduleId bigint=null,@dtCmdsenttime datetime=null,  
     @tintResponse tinyint=null,@tintBoxcmdouttypeId tinyint=null  
       
    SELECT @bitIsInprogress=1,@tintBoxcmdouttypeId=BoxCmdOutTypeId,@intBoxid=Boxid,@bigScheduleId=ScheduleId,@dtCmdsenttime=CmdSenttime    
     FROM @tblInprogressCmds WHERE SchedulelogId=@bigScheduleLogLoop   
       
     SELECT @tintResponse=Acknowledged FROM rvlfMsgOutHst WHERE BoxId=@intBoxid AND (@tintBoxcmdouttypeId IS NULL OR BoxCmdOutTypeId=@tintBoxcmdouttypeId) AND SentDateTime =@dtCmdsenttime   
     IF @tintResponse =1  
      EXEC [rvlf_sp_UpdatePendingScheduleofCommands] @dtCmdsenttime,1,'The command sent successfully.',@bigScheduleLogLoop,@bigScheduleId,0,null  
     ELSE IF @tintResponse !=1  
      EXEC [rvlf_sp_UpdatePendingScheduleofCommands] @dtCmdsenttime,0,'The command has failed.',@bigScheduleLogLoop,@bigScheduleId,0,null  
     ELSE IF (@tintResponse IS NULL AND DATEADD(S,30,@dtCmdsenttime)<GETUTCDATE())  
      EXEC [rvlf_sp_UpdatePendingScheduleofCommands] @dtCmdsenttime,0,'The command has failed.',@bigScheduleLogLoop,@bigScheduleId,0,null  
    SELECT @bigScheduleLogLoop=MIN(SchedulelogId) FROM @tblInprogressCmds WHERE SchedulelogId >@bigScheduleLogLoop   
   END  
     
 --update the ota commands     
 DECLARE @TblCommands TABLE  
 (  
  ScheduleId bigint,  
  Boxid int  
 )  
 INSERT INTO @TblCommands (ScheduleId,Boxid)  
 SELECT DISTINCT SM.ScheduleId,SM.BoxId   FROM rvlfScheduleOfCommandsMaster SM  
  INNER JOIN rvlfMsgOutHst MO ON MO.SentDateTime BETWEEN SM.EffectiveFrom AND SM.EffectiveTo AND MO.BoxCmdOutTypeId=SM.BoxCmdOutTypeId   
   WHERE SM.BoxCmdOutTypeId=22 AND GETUTCDATE() BETWEEN SM.EffectiveFrom AND SM.EffectiveTo AND MO.Acknowledged IS NULL   
  
  DECLARE @INC BIGINT=NULL  
  SELECT @INC =MIN(ScheduleId) FROM  @TblCommands    
  WHILE @INC IS NOT NULL  
   BEGIN    
    IF NOT EXISTS(SELECT ScheduleId  FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId=@INC)  
     BEGIN  
      INSERT INTO rvlfSchedulingOfCommandsLog (ScheduleId,ExecutionOn,IsCommandSend,ResponseMsg,[No.ofTries],ResponseId)  
      SELECT TOP 1 sm.ScheduleId,MAX(mo.SentDateTime),1,'Command sent successfully.',1,3 FROM rvlfScheduleOfCommandsMaster sm  
         INNER JOIN rvlfMsgOutHst mo on mo.BoxId=sm.Boxid AND mo.BoxCmdOutTypeId=sm.BoxCmdOutTypeId AND mo.SentDateTime BETWEEN sm.EffectiveFrom AND sm.EffectiveTo   
          WHERE mo.Acknowledged IS NULL AND sm.Boxid=(SELECT BoxId FROM @TblCommands WHERE sm.ScheduleId =@INC)  
           AND sm.ScheduleId=@INC GROUP BY sm.ScheduleId        
     END  
       
    SELECT @INC =MIN(ScheduleId) FROM  @TblCommands  WHERE  ScheduleId>@INC     
   END  
    
   --GET THE SCHEDULED COMMANDS BASED ON THE VEHICLES  
  SELECT SM.ScheduleId,SL.ScheduleLogId,SM.PacketInfo,BO.BoxCmdOutTypeCode AS CommandCode,SM.UserId,SM.BoxId as BoxId      
   FROM rvlfSchedulingOfCommandsLog SL  
    INNER JOIN rvlfScheduleOfCommandsMaster SM ON SM.ScheduleId=SL.ScheduleId   
    INNER JOIN rvlfBoxCmdOutType BO ON BO.BoxCmdOutTypeId=SM.BoxCmdOutTypeId   
    --INNER JOIN rvlfVehicleAssignment V ON V.BoxId=SM.Boxid    
    --INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId =V.VehicleId   
   WHERE (SL.IsCommandSend IS NULL OR SL.IsCommandSend=0)  and (SM.Isdelete is null or SM.Isdelete =0)  
    AND (SL.ResponseId IN (0,1,3,4,5,7,8,9,10) OR SL.ResponseId IS NULL)  
    --AND (SL.ResponseMsg IS NULL OR SL.ResponseMsg NOT IN('In-Progress','Expired'))  
    AND (SM.Boxid IN (SELECT  Boxid FROM rvlfSchedulingOfCommandsLog SL 
    INNER JOIN rvlfScheduleOfCommandsMaster SM ON SM.ScheduleId=SL.ScheduleId  
    WHERE (SL.[NO.OFTRIES] IS NULL OR SL.[NO.OFTRIES]<=SM.[No.ofRetries])      
    AND (SM.EffectiveTo>=GETUTCDATE()) AND SL.ResponseId IN (0,1,3,4,5,6,7,8,9,10) OR SL.ResponseId IS NULL))  
    --AND (SL.ResponseMsg IS NULL OR SL.ResponseMsg !='In-Progress')) )  
    AND(SL.[NO.OFTRIES] IS NULL OR SL.[NO.OFTRIES]<=SM.[No.ofRetries])      
    AND (SM.EffectiveTo>=GETUTCDATE())    
    
   -- AND SM.ScheduleId IN(SELECT MIN(SM.ScheduleId) FROM rvlfSchedulingOfCommandsLog SL  
   -- INNER JOIN rvlfScheduleOfCommandsMaster SM ON SM.ScheduleId=SL.ScheduleId       
   --WHERE (SL.IsCommandSend IS NULL OR SL.IsCommandSend=0)  
   -- AND SL.ResponseId IN (0,1,3,4,5,7,8,9,10)  
   -- --AND (SL.ResponseMsg IS NULL OR SL.ResponseMsg NOT IN('In-Progress','Expired'))  
   -- AND (SM.Boxid IN (SELECT Boxid FROM rvlfSchedulingOfCommandsLog SL INNER JOIN rvlfScheduleOfCommandsMaster SM ON SM.ScheduleId=SL.ScheduleId  WHERE (SL.[NO.OFTRIES] IS NULL OR SL.[NO.OFTRIES]<=SM.[No.ofRetries])      
   -- AND (SM.EffectiveTo>=GETUTCDATE()) AND SL.ResponseId IN (0,1,3,4,5,6,7,8,9,10)))  
   -- --AND (SL.ResponseMsg IS NULL OR SL.ResponseMsg !='In-Progress')) )  
   -- AND(SL.[NO.OFTRIES] IS NULL OR SL.[NO.OFTRIES]<=SM.[No.ofRetries])      
   -- AND (SM.EffectiveTo>=GETUTCDATE())  
   -- AND Boxid IN(SELECT MIN(Boxid) FROM rvlfSchedulingOfCommandsLog SL  
   -- INNER JOIN rvlfScheduleOfCommandsMaster SM ON SM.ScheduleId=SL.ScheduleId       
   --WHERE (SL.IsCommandSend IS NULL OR SL.IsCommandSend=0)  
   -- AND SL.ResponseId IN (0,1,3,4,5,7,8,9,10)  
   -- --AND (SL.ResponseMsg IS NULL OR SL.ResponseMsg NOT IN('In-Progress','Expired'))  
   -- AND (SM.Boxid IN (SELECT Boxid FROM rvlfSchedulingOfCommandsLog SL INNER JOIN rvlfScheduleOfCommandsMaster SM ON SM.ScheduleId=SL.ScheduleId  WHERE (SL.[NO.OFTRIES] IS NULL OR SL.[NO.OFTRIES]<=SM.[No.ofRetries])      
   -- AND (SM.EffectiveTo>=GETUTCDATE()) AND SL.ResponseId IN (0,1,3,4,5,6,7,8,9,10)))  
   -- --AND (SL.ResponseMsg IS NULL OR SL.ResponseMsg !='In-Progress')) )  
   -- AND(SL.[NO.OFTRIES] IS NULL OR SL.[NO.OFTRIES]<=SM.[No.ofRetries])      
   -- AND (SM.EffectiveTo>=GETUTCDATE()) GROUP BY Boxid)GROUP BY SM.Boxid )  
    
    AND SM.Boxid NOT IN(SELECT DISTINCT Boxid  FROM rvlfSchedulingOfCommandsLog SL  
    INNER JOIN rvlfScheduleOfCommandsMaster SM ON SM.ScheduleId=SL.ScheduleId    
    WHERE SL.ResponseMsg = 'In-Progress') --ResponseId =2)  
     
   
END  
  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetPersonDeviationRpt_App]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetPersonDeviationRpt_App]
@bigFleetID bigint = null,
@intBoxID int = null,
@bigFromLandmarkId int = null,
@dtStartDate datetime = null,
@dtEndDate datetime = null,
@bigOrganizationID bigint = null,
@bigQueryingUser bigint = null
AS
/************************************************************************************************************************
Procedure Name	: rvlf_sp_GetPersonDeviationRpt_App 8,null,1366,'2013-04-22 08:00:00.000','2013-04-22 23:00:00.000',6,94
Description		: Get the person schedule deviation list
Created By		: Sakthi Gopinath S
Created Date	: 22-Apr-2013
*************************************************************************************************************************/
BEGIN
SET NOCOUNT ON
	DECLARE @Lang varchar(50)     
	SELECT @Lang=isnull(Lang,'LanguageEn') from dbo.rvlfUserPreferences where UserId = @bigQueryingUser  

	DECLARE @HoursToBeAdded INT = 0        
	DECLARE @MinsToBeAdded INT = 0        
	DECLARE @ConversionFactor numeric (10,2) = 1.0        
	DECLARE @DistanceCaptionPrefix varchar(15)        
	DECLARE @SpeedCaptionPrefix varchar(15)      
	DECLARE @DefaultDateFormat INT = 0;
	DECLARE @bigFleetName varchar(30)      

	IF @bigFleetID IS NULL        
	BEGIN        
		SELECT @bigFleetID=FleetID from dbo.rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1        
	END  

	IF @bigFleetID IS NOT NULL
	BEGIN
		SELECT @bigFleetName=FleetName FROM dbo.rvlfFleet WHERE OrganizationId=@bigOrganizationID AND FleetId=@bigFleetID
	END

	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,
	@DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)        
	FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz        
	ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser  

	DECLARE @tblMessages TABLE
	(
		MessageInId uniqueidentifier,
		BoxId bigint,
		VehicleID int,
		VehicleDescription varchar(50),
		OriginDateTime datetime,
		OriginDateTimeSort datetime,
		BoxMsgInTypeId int,
		CustomProp varchar(500),
		Speed int,
		StreetAddress varchar(250),
		LandmarkId int
	)

	INSERT INTO @tblMessages
	SELECT h.MessageInID,h.BoxId,v.VehicleId,v.VehicleDescription,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,h.OriginDateTime)),
	h.OriginDateTime,h.BoxMsgInTypeId,h.CustomProp,h.Speed,h.StreetAddress,h.LandMarkID FROM rvlfMsgInHst h 
	INNER JOIN rvlfVehicleAssignment va ON va.BoxId=h.BoxId
	INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId
	INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=v.VehicleId 
	WHERE v.OrganizationId=@bigOrganizationID AND fv.FleetId=@bigFleetID AND
	(@intBoxID IS NULL OR @intBoxID='' OR h.BoxId=@intBoxID) AND h.OriginDateTime BETWEEN 
	DATEADD(HOUR,-1*@HoursToBeAdded,DATEADD(MINUTE,-1*@MinsToBeAdded,@dtStartDate)) AND
	DATEADD(HOUR,-1*@HoursToBeAdded,DATEADD(MINUTE,-1*@MinsToBeAdded,@dtEndDate)) AND
	h.LandMarkID IS NOT NULL AND(@bigFromLandmarkId IS NULL OR @bigFromLandmarkId=0 OR h.LandMarkID=@bigFromLandmarkId)
	
	SELECT o.OrganizationDisplayName,@bigFleetName AS FleetName,A.ScheduleId,m.BoxId,A.VehicleId,m.VehicleDescription,app.MobileNo,
	l.LandmarkName,Convert(varchar,A.FromTime,@DefaultDateFormat) +' '+ Convert(varchar,cast(A.FromTime as time),22) AS FromTime,
	A.GraceTime,CASE WHEN m.BoxMsgInTypeId=1 AND m.CustomProp LIKE '%IsAck:1%' THEN 'Mobile settings changed'
	WHEN m.BoxMsgInTypeId=1 AND m.CustomProp LIKE '%IsAlarm=1;AlarmMsg=%' THEN 
	'Alarm : '+SUBSTRING(m.CustomProp,CHARINDEX('AlarmMsg=',m.CustomProp,0)+9,LEN(m.CustomProp)-(CHARINDEX(m.CustomProp,'AlarmMsg=',0)+9))	
	ELSE dbo.rvlf_fn_GetAlarmDetails(m.customprop,m.BoxMsgInTypeID, m.BoxId, m.MessageInID, m.OriginDateTime ) END AS MessageDetails,--CT.BoxMsgInTypeDesc 
	A.GraceMins,Convert(varchar,m.OriginDateTime,@DefaultDateFormat) +' '+ Convert(varchar,cast(m.OriginDateTime as time),22) AS OriginDateTime,
	m.CustomProp,CASE WHEN m.OriginDateTime < A.FromTime THEN 'No' WHEN m.OriginDateTime BETWEEN A.FromTime AND A.GraceTime 
	THEN 'No' ELSE 'Yes' END AS [Status], CASE WHEN  m.OriginDateTime < A.FromTime THEN 'NA' WHEN 
	m.OriginDateTime BETWEEN A.FromTime AND A.GraceTime THEN 'NA' ELSE dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SECOND,A.FromTime,m.OriginDateTime)) END AS [DeviatedDuration],
	m.StreetAddress,Convert(varchar,@dtStartDate,@DefaultDateFormat) +' '+ Convert(varchar,cast(@dtStartDate as time),22) as PasStartDate,
	Convert(varchar,@dtEndDate,@DefaultDateFormat) +' '+Convert(varchar,cast(@dtEndDate as Time),22) as PasEndDate,  
	dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()) AS PasGenerateddate
	FROM (SELECT ap.*,DATEDIFF(MINUTE,ap.FromTime,ap.GraceTime) AS GraceMins,
	CASE WHEN (SELECT TOP 1 1 FROM @tblMessages WHERE VehicleId=ap.VehicleId AND OriginDateTime > ap.FromTime and LandmarkId=ap.LandmarkId ORDER BY OriginDateTimeSort)=1 THEN
	(SELECT TOP 1 MessageInId FROM @tblMessages WHERE VehicleId=ap.VehicleId AND OriginDateTime > ap.FromTime and LandmarkId=ap.LandmarkId ORDER BY OriginDateTimeSort) 
	ELSE 
		(SELECT TOP 1 MessageInId FROM @tblMessages WHERE VehicleId=ap.VehicleId AND CONVERT(DATE,OriginDateTime) = CONVERT(DATE,ap.FromTime) and LandmarkId=ap.LandmarkId ORDER BY OriginDateTimeSort DESC) 
	END AS MessageInId
	FROM rvlfModelSchedule_App ap WHERE ap.FromTime BETWEEN @dtStartDate AND @dtEndDate) A INNER JOIN @tblMessages m ON m.MessageInId=A.MessageInId
	INNER JOIN rvlfLandmark l ON l.LandmarkID=m.LandmarkId INNER JOIN rvlfOrganization o ON o.OrganizationId=l.OrganizationId
	INNER JOIN rvlfModelBoxSettings_App bxApp ON bxApp.BoxID = m.BoxId
	INNER JOIN rvlfModel_App app ON app.ModelId=bxApp.ModelId
	WHERE o.OrganizationId=@bigOrganizationID ORDER BY m.OriginDateTime
	
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetPortalUsageDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetPortalUsageDetails]
@bigFleetID bigint = NULL,
@intBoxID int = NULL,
@dtStartDate datetime = NULL,
@dtEndDate datetime = NULL,
@bigOrganizationID bigint = NULL,
@bigQueryingUser bigint = NULL
AS
/****************************************************************************************************************
Procedure Name	: rvlf_sp_GetPortalUsageDetails 8,NULL,'2012-11-01 00:00:00.000','2012-11-02 23:00:00.000',6,303
Description		: Get the portal usage details by user
Created By		: Sakthi Gopinath S
Created Date	: 19-Sep-2012
*****************************************************************************************************************/
BEGIN
SET NOCOUNT ON

	DECLARE @dtFDate DATETIME =@dtStartDate      
	DECLARE @dtEDate DATETIME =@dtEndDate 
	DECLARE @HoursToBeAdded INT = 0        
	DECLARE @MinsToBeAdded INT = 0        
	DECLARE @DisplayName nvarchar(30)
	DECLARE @DefaultDateFormat INT = 0
	DECLARE @cntUser INT = 0
	SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@DisplayName = U.UserName,     
	@DefaultDateFormat=(CASE WHEN ISNULL(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)        
	FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser
	INNER JOIN dbo.rvlfUser U on U.UserId = up.UserId
         
	SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))        
	SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate)) 

	DECLARE @tblUserLogin TABLE (Id INT IDENTITY(1,1),OrganizationId INT,UserId SMALLINT,Username VARCHAR(50),
	LoginDT DATETIME,LogOffDT DATETIME,IP VARCHAR(25),Seconds INT,FleetId INT)
	INSERT INTO @tblUserLogin(OrganizationId,UserId,Username,LoginDT,LogOffDT,IP,Seconds,FleetId)
	SELECT DISTINCT u.OrganizationId,u.UserId,u.UserName,ul.LoginDateTime,ul.LogOffDateTime,ul.IP,
	DATEDIFF(SECOND,ul.LoginDateTime,ul.LogOffDateTime),up.DefaultFleetId
	FROM dbo.rvlfUserLogin ul INNER JOIN dbo.rvlfUser u ON u.UserId=ul.UserId AND u.UserId IN 
	(SELECT DISTINCT fu.UserID FROM dbo.rvlfFleetUsers fu INNER JOIN dbo.rvlfFleet f ON f.FleetId=fu.FleetId
	WHERE f.OrganizationID=@bigOrganizationID AND f.FleetId=@bigFleetID) 
	--INNER JOIN dbo.rvlfFleetUsers fu ON fu.UserId=u.UserId INNER JOIN dbo.rvlfFleet f ON f.FleetId=fu.FleetId
	--WHERE f.OrganizationID=@bigOrganizationID AND f.FleetId IN (select ParentChildId from dbo.rvlf_fn_GetParentChild(@bigFleetID)) 
	INNER JOIN rvlfUserPreferences up ON up.UserId=u.UserId
	WHERE u.IsHidden=0 AND ul.LoginDateTime BETWEEN @dtStartDate AND @dtEndDate

	SELECT @cntUser=COUNT(DISTINCT UserID) FROM @tblUserLogin WHERE FleetId=@bigFleetID

	SELECT @cntUser AS No_Of_Users,O.OrganizationDisplayName,ul.UserId,ul.Username,
	DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),LoginDT)) AS LoginDT,
	DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),LogOffDT)) AS LogOffDT,
	ul.Seconds,
	DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),AB.FirstLogin)) AS FirstLogin,
	DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),AB.LastLogOff)) AS LastLogOff,
	dbo.rvlf_fn_GetTimeFromSeconds(ul.Seconds) AS [HoursSpent],AB.[Total Hours (HH:MM:SS)] AS TotalHours,AB.No_Of_Attempt,f.FleetName,
	CONVERT(VARCHAR,@dtFDate,@DefaultDateFormat) + ' ' + CONVERT(VARCHAR,CAST(@dtFDate AS TIME),22) as PasStartDate,
	CONVERT(VARCHAR,@dtEDate,@DefaultDateFormat) + ' ' + CONVERT(VARCHAR,CAST(@dtEDate AS TIME),22) as PasEndDate,
	@DisplayName + ' - '+CONVERT(VARCHAR,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ 
	' '+ CONVERT(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) AS TIME),22) as PasGenerateddate         
	FROM @tblUserLogin ul INNER JOIN (SELECT OrganizationId,UserId,Username,SUM(Seconds) TotalSeconds,
	MIN(LoginDT) AS FirstLogin,MAX(LogOffDT) AS LastLogOff,dbo.rvlf_fn_GetTimeFromSeconds(SUM(Seconds)) As [Total Hours (HH:MM:SS)] ,
	COUNT(LoginDT) AS No_Of_Attempt	FROM @tblUserLogin WHERE LogOffDT IS NOT NULL
	GROUP BY UserId,Username,OrganizationId) AB ON AB.UserId=ul.UserId-- AND AB.LoginTime = CONVERT(DATE,ul.LoginDT)
	INNER JOIN dbo.rvlfOrganization O ON O.OrganizationId=AB.OrganizationId
	INNER JOIN dbo.rvlfFleet f ON f.FleetId=ul.FleetId
	WHERE LogOffDT IS NOT NULL ORDER BY ul.Username,ul.LoginDT
	
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetPortalUsageDetailsDashbrd]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetPortalUsageDetailsDashbrd]
@bigFleetID bigint = NULL,
@intBoxID int = NULL,
@dtStartDate datetime = NULL,
@dtEndDate datetime = NULL,
@bigOrganizationID bigint = NULL,
@bigQueryingUser bigint = NULL,
@bigTopNos bigint  =null

AS
/****************************************************************************************************************
Procedure Name	: rvlf_sp_GetPortalUsageDetailsDashbrd 8,null,'2012-05-11 08:00:00.000','2013-08-20 23:00:00.000',6,19,15
Created By		: Kapil
Created Date	: 20-AUG-2013
*****************************************************************************************************************/
BEGIN
SET NOCOUNT ON

	DECLARE @dtFDate DATETIME =@dtStartDate      
	DECLARE @dtEDate DATETIME =@dtEndDate 
	DECLARE @HoursToBeAdded INT = 0        
	DECLARE @MinsToBeAdded INT = 0        
	DECLARE @DisplayName nvarchar(30)
	DECLARE @DefaultDateFormat INT = 0
	DECLARE @cntUser INT = 0
	
	SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@DisplayName = U.UserName,     
	@DefaultDateFormat=(CASE WHEN ISNULL(up.DefaultDateFormat,0)= 0 THEN 106 ELSE up.DefaultDateFormat END)        
	FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser
	INNER JOIN dbo.rvlfUser U on U.UserId = up.UserId
         
	SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))        
	SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate)) 
	
	SELECT DISTINCT TOP(@bigTopNos) u.UserName,-- SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime))as Seconds,	
	CEILING(SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime)) / 60.00) as DurationInMinutes,
    dbo.rvlf_fn_GetTimeFromSeconds(SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime))) AS [UsageTimeFormatted],     
	row_number() over(order by SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime)) desc) as PortalUsageRowno,
	'-' as DriverName,
	@DisplayName + ' - '+CONVERT(VARCHAR,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ 
	' '+ CONVERT(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) AS TIME),22) as PasGenerateddate	
	FROM dbo.rvlfUserLogin ul 	
	INNER JOIN dbo.rvlfUser u ON u.UserId=ul.UserId AND u.UserId IN 
    (SELECT DISTINCT fu.UserID FROM dbo.rvlfFleetUsers fu INNER JOIN dbo.rvlfFleet f ON f.FleetId=fu.FleetId
	WHERE f.OrganizationID=@bigOrganizationID AND f.FleetId=@bigFleetID) 	
	INNER JOIN rvlfUserPreferences up ON up.UserId=u.UserId
	WHERE u.IsHidden=0 AND ul.LoginDateTime BETWEEN @dtStartDate AND @dtEndDate group by u.UserName
  		
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetPreCannedMsg]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
  
CREATE Procedure [dbo].[rvlf_sp_GetPreCannedMsg]    
 @bigCannedId bigint=null,   
 @tiMsgType tinyint = null,    
 @bigVehId bigint = null,    
 @tiOpr tinyint = 0,    
 @bigOrganizationID bigint = null ,
 @IsGarmin bit = 0     
AS    
/******************************************************************************/    
-- Name   : rvlf_sp_GetPreCannedMsg  '',1,33,4,6
-- Description : To get the precanned messages    
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 30-Aug-2011 VN Created Intial Version     
/******************************************************************************/    
BEGIN          
   --GET THE ALL MDT MESSAGE BASED ON THE ORGANIZATION.  
   IF(@tiOpr=0)  
  BEGIN     
   SELECT PM.CannedMsgId,PrecannedMsgId,MsgName,IsServerMsg,0 as Isselect,
   CASE WHEN MB.CannedMsgId IS NOT NULL THEN 0 ELSE 1 END AS IsAssigned,1 AS IsExceedMsgs,0 AS TotMsgs    
    FROM rvlfPrecannedMessages PM  
      LEFT OUTER JOIN rvlfMDTBoxMessageTable MB ON MB.CannedMsgId =PM.CannedMsgId     
     WHERE (OrganizationId = @bigOrganizationID)     
      --AND (@tiMsgType IS NULL OR IsServerMsg = @tiMsgType)  
     
   --GET THE MDT COMMANDS BASED ON THE RIGHTS  
   SELECT * FROM  rvlfBoxCmdOutType BO  
     INNER JOIN rvlfPackageOperations PO ON PO.OperationID=BO.OperationTypeId   
     INNER JOIN rvlfOrganizationPackage OP ON OP.PackageId=PO.PackageId    
    WHERE OP.OrganizationId=@bigOrganizationID    
     AND OP.IsActive=1   
     AND BO.BoxCmdOutTypeId IN(39,44,45,46,47,48)       
  END  
 --GET THE MESSAGES WHICH IS ASSIGNED ON THE VEHICLE  
 ELSE IF(@tiOpr=1)  
  BEGIN    
   DECLARE @intBoxId AS INT = NULL  
   IF @bigVehId IS NOT NULL OR @bigVehId!=''  
    BEGIN        
     SET @intBoxId = (SELECT BoxId FROM rvlfVehicleAssignment WHERE VehicleId = @bigVehId)    
    END       
   SELECT PM.CannedMsgId,PrecannedMsgId,MsgName,0 as Isselect,1 AS IsExceedMsgs,0 AS TotMsgs      
    FROM rvlfPrecannedMessages  PM   
     INNER JOIN rvlfMDTBoxMessageTable BT ON BT.CannedMsgId =PM.CannedMsgId   
    WHERE BoxId=@intBoxId   
     AND BT.CannedMsgId IS NOT NULL  
     AND IsServerMsg=1  
     AND PM.OrganizationId=@bigOrganizationID  
  END  
 --GET THE PARTICULAR MESSAGE FOR UPDATE.  
 ELSE IF(@tiOpr=2)  
  BEGIN  
   SELECT CannedMsgId,PrecannedMsgId, MsgName ,IsServerMsg,0 as Isselect,1 AS IsExceedMsgs,0 AS TotMsgs        
    FROM rvlfPrecannedMessages     
     WHERE (OrganizationId = @bigOrganizationID)        
      AND CannedMsgId=@bigCannedId   
      AND OrganizationId=@bigOrganizationID  
  END  
 --GET THE MESSAGE BASED ON THE MESSAGE TYPE  
 ELSE IF(@tiOpr=3)  
  BEGIN  
   SELECT CannedMsgId,PrecannedMsgId,MsgName,IsServerMsg,0 as Isselect,1 AS IsExceedMsgs,0 AS TotMsgs      
    FROM rvlfPrecannedMessages     
     WHERE (OrganizationId = @bigOrganizationID)     
      AND (IsServerMsg = @tiMsgType)  
      AND OrganizationId=@bigOrganizationID  
  END  
 --GET THE UNASSIGNED MESSAGES BASED ON THE BOXID  
 ELSE IF(@tiOpr=4)  
  BEGIN  
   IF @bigVehId IS NOT NULL OR @bigVehId!=''  
     BEGIN        
      SET @intBoxId = (SELECT BoxId FROM rvlfVehicleAssignment WHERE VehicleId = @bigVehId)    
     END    
     DECLARE @tiTotMsgs tinyint=(SELECT COUNT(MT.CannedMsgId) FROM rvlfMDTBoxMessageTable MT  
      INNER JOIN rvlfPrecannedMessages PM ON PM.CannedMsgId=MT.CannedMsgId   
       WHERE BoxId=@intBoxId AND UserId IS NULL AND MT.CannedMsgId IS NOT NULL  
        AND PM.IsServerMsg=@tiMsgType)  
   SELECT PM.CannedMsgId,PrecannedMsgId,MsgName,0 as Isselect,CASE WHEN @tiTotMsgs>=10 THEN 0 ELSE 1 END AS IsExceedMsgs,@tiTotMsgs AS TotMsgs  
    FROM rvlfPrecannedMessages  PM         
     WHERE CannedMsgId NOT IN(SELECT CannedMsgId FROM rvlfMDTBoxMessageTable WHERE BoxId=@intBoxId AND CannedMsgId IS NOT NULL)  
      AND IsServerMsg=@tiMsgType   
      AND PM.OrganizationId=@bigOrganizationID  
  END  
 --GET THE ASSIGNED MESSAGES BASED ON THE BOXID  
 ELSE IF(@tiOpr=5)  
  BEGIN  
   IF @bigVehId IS NOT NULL OR @bigVehId!=''  
     BEGIN        
      SET @intBoxId = (SELECT BoxId FROM rvlfVehicleAssignment WHERE VehicleId = @bigVehId)    
     END    
   SELECT PM.CannedMsgId,PrecannedMsgId,MsgName,0 as Isselect,1 AS IsExceedMsgs,0 AS TotMsgs      
    FROM rvlfPrecannedMessages  PM         
     WHERE CannedMsgId IN(SELECT CannedMsgId FROM rvlfMDTBoxMessageTable WHERE BoxId=@intBoxId AND CannedMsgId IS NOT NULL)  
      AND IsServerMsg=@tiMsgType   
      AND PM.OrganizationId=@bigOrganizationID  
  END  
   
 SET NOCOUNT OFF    
END    
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetProductSNo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_GetProductSNo]                      
(                    
@OrgID bigint =null,                  
@ProductId tinyint = null,
@BigFleetID bigint = null                  
)                    
as                    
/******************************************************************************/                                                            
-- Name  : rvlf_sp_GetProductSNo 86,1               
-- Description : Get Product and serial / boxid                                                           
-- Author  : Gopal.R                    
-- Company  : Angler Technologies                    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                    
--Created Date -19-jun-2014     
-- Updated by Ranjith  - 02-dec-2015 Dashboard bind changes
/******************************************************************************/                      
begin                    
select distinct MD.BoxId,(MP.VehicleTypeName +' - '+cast(MD.BoxId as varchar)) as pdtSno,MD.Sno,v.VehicleDescription,v.VehicleId,fv.FleetId as FleetId,  
MP.VehicleTypeId,MP.VehicleTypeName  
 from rvlfMAKDevices MD              
 inner join rvlfMakSubProducts SP on MD.SubTypeId=SP.SubtypeId              
 inner join rvlfVehicleType MP on SP.ProductId=MP.VehicleTypeId           
 inner join rvlfVehicleAssignment va on va.BoxId = MD.BoxId            
 inner join rvlfVehicle v on v.VehicleId =MD.VehicleId       
 inner join rvlfFleetVehicles fv on fv.VehicleId =v.VehicleId           
 where MD.OrganizationId=@OrgID                    
and(@BigFleetID is null or @BigFleetID ='' or fv.FleetId=@BigFleetID)
and(@ProductId is null or @ProductId ='' or v.VehicleTypeId=@ProductId) and MD.IsDelete  = 0 

select distinct MD.BoxId,(MP.VehicleTypeName +' - '+cast(MD.BoxId as varchar)) as pdtSno,MD.Sno,v.VehicleDescription,v.VehicleId,MP.VehicleTypeId,MP.VehicleTypeName from rvlfMAKDevices MD            
 inner join rvlfMakSubProducts SP on MD.SubTypeId=SP.SubtypeId            
 inner join rvlfVehicleType MP on SP.ProductId=MP.VehicleTypeId         
 inner join rvlfVehicleAssignment va on va.BoxId = MD.BoxId          
 inner join rvlfVehicle v on v.VehicleId =MD.VehicleId     
 inner join rvlfFleetVehicles fv on fv.VehicleId =v.VehicleId         
 where MD.OrganizationId=@OrgID        
 and(@BigFleetID is null or @BigFleetID ='' or fv.FleetId=@BigFleetID)
and(@ProductId is null or @ProductId ='' or v.VehicleTypeId=@ProductId) and md.IsDelete=0       
                  
end 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetPTOReportDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetPTOReportDetails]        
 @bigFleetID bigint = null,        
 @intBoxID varchar(max) = null,        
 @dtStartDate datetime = null,        
 @dtEndDate datetime = null,        
 @bitTripStatus bit = 1,        
 @bigOrganizationID bigint = null,        
 @bigQueryingUser bigint = 0        
AS        
/******************************************************************************/        
-- Name   : rvlf_sp_GetPTOReportDetails 14,NULL, '2010-01-01 08:00:00:00', '2010-12-10 08:00:00',null, 16,12        
-- Description : To get Door Sensor details to display in Report        
-- Author  : S. Jeyanthi        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--          : 19-Aug-2010         
--          : 13-Aug-2011 Ranjith Date Format included  
/******************************************************************************/        
BEGIN        
        
SET NOCOUNT ON    
Declare @dtFDate datetime =@dtStartDate  
 Declare @dtEDate datetime =@dtEndDate        
 IF @bigFleetID IS NULL        
  BEGIN        
   SELECT @bigFleetID=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)   
 DECLARE @DefaultDateFormat INT = 0  
        
    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,  
     @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 = @bigQueryingUser        
         
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))        
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))        
         
 DECLARE @tblTripDetailsForTD TABLE(        
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,        
  [BoxId] [int] NOT NULL,        
  [StartDate] [datetime] NOT NULL,        
  [EndDate] [datetime] NULL,        
  [StartAddress] varchar(300) NULL    
 )        
        
 DECLARE @intDuration int        
 DECLARE @dtOriginDateTime datetime        
 DECLARE @bigOdoMeterReading int        
 DECLARE @bitDoorStatus bit        
 DECLARE @vcStreetAddress varchar(250)        
 DECLARE @tiBoxMsgInTypeId tinyint    
 DECLARE @bigTripID bigint        
 DECLARE @intIterator int        
 DECLARE @canShowFuelMessage bit = 0       
       
        
 IF EXISTS (SELECT * FROM rvlfPackageOperations r        
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId        
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId        
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)        
   BEGIN        
    SET @canShowFuelMessage = 1        
   END        
        
 DECLARE  @tblMessageForProcessingTrip TABLE(        
  [ProcessorID] [bigint] identity(1,1) NOT NULL,      
  [Boxid] [int] NOT NULL,        
  [OriginDateTime] [datetime] NOT NULL,        
  [BoxMsgInTypeId] [tinyint] NULL,          
  [DoorStatus] [bit] NULL,        
  [IgnitionStatus] [bit] NULL,        
  [StreetAddress] [varchar](250) NOT NULL,    
  [SensorMask] varchar(250) NULL,        
  [TripId] [bigint] NULL,        
  [Duration] [int] NULL,        
  [SensorNo] [tinyint] NULL        
          
 )        
         
 DECLARE @tblBoxes TABLE (BoxID int)        
          
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va     
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId    
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId    
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or BoxId in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID    
   ORDER BY BoxId        
         
 DECLARE @intBoxLooping int     
          
   SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes        
   WHILE @intBoxLooping IS NOT NULL        
   BEGIN     
  DECLARE @DTFIRST DATETIME=NULL,@DTEND DATETIME=NULL    
    --FIND THE FIRST IGNITION ON TIME BETWEEN THE FROM AND TO TIME    
   SELECT TOP 1 @DTFIRST=OriginDateTime FROM rvlfMsgInHst WHERE Boxid=@intBoxLooping AND BoxMsgInTypeId=2 AND     
        OriginDateTime BETWEEN @dtStartDate and @dtEndDate AND CAST(SUBSTRING(CustomProp ,CHARINDEX('=',CustomProp)+1,        
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint)=1 ORDER BY OriginDateTime asc        
   SELECT TOP 1 @DTEND=OriginDateTime FROM rvlfMsgInHst WHERE Boxid=@intBoxLooping AND BoxMsgInTypeId=2 AND     
        OriginDateTime BETWEEN @dtStartDate and @dtEndDate AND CAST(SUBSTRING(CustomProp ,CHARINDEX('=',CustomProp)+1,        
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint)=1        
        ORDER BY OriginDateTime desc           
      
  INSERT INTO @tblMessageForProcessingTrip (        
   Boxid, OriginDateTime, BoxMsgInTypeId,         
   DoorStatus, IgnitionStatus, StreetAddress,                
   SensorMask, Duration, SensorNo)        
    SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,              
     CAST( SUBSTRING(h.sensormask,8,1) as bit) as DoorStatus,        
     CAST( SUBSTRING(h.sensormask,8,1) as bit) as IgnitionStatus,               
   CASE WHEN (h.LandMarkID IS NULL or h.LandMarkID = 0) THEN ISNULL(h.StreetAddress,'Address is not resolved')     
     ELSE ISNULL(L.LandmarkName, ISNULL(h.StreetAddress,'Address is not resolved'))END as StreetAddress,    
   Case WHEN h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc         
   WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +        
    CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +        
    dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'        
   ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID,         
   h.OriginDateTime, @canShowFuelMessage)END,         
     CASE WHEN h.BoxMsgInTypeID = 9 THEN         
   CAST(dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeID, h.BoxId,0) as int) ELSE 0 END,        
     CASE WHEN h.BoxMsgInTypeId = 2 THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,        
   CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END        
   from rvlfMsgInHst h         
    INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId        
    INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId        
    INNER JOIN rvlfFleetVehicles fv ON va.VehicleId = fv.VehicleId        
    INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId        
    INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId    
    LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID         
   WHERE h.BoxMsgInTypeId = 2 AND CAST(SUBSTRING(CustomProp ,CHARINDEX('=',CustomProp)+1,        
   CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint)=1         
   AND 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 ( @bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID)                  
     AND h.OriginDateTime between @DTFIRST and @DTEND                 
     AND h.BoxID = @intBoxLooping        
    order by h.origindatetime asc, h.MessageInID asc         
                  
  SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes WHERE BoxID < @intBoxLooping        
   END        
        
        
  SELECT @intIterator = MIN(ProcessorID) FROM @tblMessageForProcessingTrip         
          
  WHILE @intIterator IS NOT NULL        
  BEGIN        
   SET @intBoxID = NULL; SET @dtOriginDateTime = NULL; SET @tiBoxMsgInTypeId = NULL;        
   SET @bitDoorStatus = NULL; SET @vcStreetAddress = NULL; SET @intDuration = NULL;      
   SET @intDuration = NULL;      
      
   DECLARE @dtNextStartTime datetime=null;     
   DECLARE @bitIsTripClosed bit=0;    
       
   SELECT  @intBoxID = Boxid, @dtOriginDateTime = OriginDateTime,      
     @tiBoxMsgInTypeId = BoxMsgInTypeId,         
     @bitDoorStatus = IgnitionStatus,@vcStreetAddress = StreetAddress,         
     @intDuration = Duration    
   FROM @tblMessageForProcessingTrip WHERE ProcessorID=@intIterator and  TripId is NULL     
          
 IF(@bitDoorStatus=1 AND @tiBoxMsgInTypeId=2)    
    BEGIN    
     DECLARE @DTENDTIME DATETIME=NULL    
    --NEXT IGNITION TIME         
     SELECT TOP 1 @dtNextStartTime=OriginDateTime,@bitIsTripClosed=1 FROM @tblMessageForProcessingTrip     
      WHERE BoxMsgInTypeId=2 AND Boxid =@intBoxID AND OriginDateTime>@dtOriginDateTime     
      and DoorStatus=1    
         
        
     IF(@dtNextStartTime IS NOT NULL)         
      BEGIN         
       SELECT TOP 1 @DTENDTIME=OriginDateTime,@bitIsTripClosed=1             
        FROM @tblMessageForProcessingTrip     
        WHERE BoxMsgInTypeId=2 AND Boxid =@intBoxID AND OriginDateTime >= @dtOriginDateTime     
         AND OriginDateTime < @dtNextStartTime and DoorStatus=0     
      END    
     ELSE    
      BEGIN          
       SELECT TOP 1 @DTENDTIME=OriginDateTime,@bitIsTripClosed=1    
        FROM @tblMessageForProcessingTrip     
        WHERE BoxMsgInTypeId=2 AND Boxid =@intBoxID AND OriginDateTime > @dtOriginDateTime    
        And DoorStatus=0    
      END    
       
   --Select @dtOriginDateTime '@dtOriginDateTime', @DTENDTIME '@DTENDTIME'    
    INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress)      
     VALUES(@intBoxID,@dtOriginDateTime,@DTENDTIME, @vcStreetAddress)     
           
       
                        
    SET @bigTripID=@@IDENTITY     
    END     
    UPDATE @tblMessageForProcessingTrip SET TripId = @bigTripID where Boxid=@intBoxID AND OriginDateTime>=@dtOriginDateTime AND OriginDateTime<=@DTENDTIME     
       
    SELECT @intIterator = MIN(ProcessorID) FROM @tblMessageForProcessingTrip WHERE ProcessorID > @intIterator and TripId is NULL     
       
   END    
    
        
  SELECT t.TripId,t.BoxId,   
  StartDate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,StartDate),  
  EndDate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,EndDate),  
  --Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)),@DefaultDateFormat)+ ' ' + Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate))as time),22) as 'StartDate',        
--    CONVERT(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)),@DefaultDateFormat) + ' ' + CONVERT(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as Time),22) as 'EndDate',         
     dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,StartDate,EndDate)) as Duration,        
     ABS(DateDiff(SS,StartDate,EndDate)) as TripDuration,     
     (Select top 1 dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,StartDate,EndDate)) from @tblTripDetailsForTD tt order by ABS(DateDiff(SS,StartDate,EndDate)) Desc) MaxDuration,        
     (Select top 1 dbo.rvlf_fn_getTimeFromSeconds(ISNULL(DateDiff(SS,StartDate,EndDate),0)) from @tblTripDetailsForTD tt Where EndDate IS NOt NULL order by ABS(DateDiff(SS,StartDate,EndDate)) Asc) MinDuration,            
      StartAddress,StartAddress 'EndAddress', Vin, LicensePlate, VehicleDescription, MakeName, ModelName,ModelYear,  
      PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())  
      --Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate     
   FROM @tblTripDetailsForTD t       
   INNER JOIN rvlfVehicleAssignment va ON t.BoxId = va.BoxId        
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId        
   LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId        
   LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId     
   WHERE StartDate IS NOT NULL and EndDate IS Not Null    
   Order by TripId     
 SET NOCOUNT OFF      
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetPTOReportDetails_Old_10_Dec_2010]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create Procedure [dbo].[rvlf_sp_GetPTOReportDetails_Old_10_Dec_2010]    
 @bigFleetID bigint = null,    
 @intBoxID int = null,    
 @dtStartDate datetime = null,    
 @dtEndDate datetime = null,    
 @bitTripStatus bit = 1,    
 @bigOrganizationID bigint = null,    
 @bigQueryingUser bigint = 0    
AS    
/******************************************************************************/    
-- Name			: rvlf_sp_GetPTOReportDetails_Old_10_Dec_2010 14,Null, '2010-01-01 08:00:00:00', '2010-12-10 08:00:00',null, 16,62    
-- Description  : To get Door Sensor details to display in Report    
-- Author		: S. Jeyanthi    
-- Company		: Angler Technologies    
-- History		: <<Date(dd-MON-yyyy)>> Initial Reason    
--				: 19-Aug-2010     
/******************************************************************************/    
BEGIN    
    
SET NOCOUNT ON      
 IF @bigFleetID IS NULL    
  BEGIN    
   SELECT @bigFleetID=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 = @bigQueryingUser    
     
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))    
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))    
     
 CREATE TABLE #tblTripDetailsForTD(    
  [TripId] [bigint] NOT NULL,    
  [BoxId] [int] NOT NULL,    
  [StartDate] [datetime] NOT NULL,    
  [EndDate] [datetime] NULL,    
  [StartAddress] varchar(300) NULL,    
  [EndAddress] varchar(300) NULL,    
  [VIN] [varchar](20) NULL,    
  [LicensePlate] [varchar](20) NULL,    
  [VehDispName] [varchar](50) NULL,    
  [MakeName] [varchar](200) NULL,    
  [ModelName] [varchar](200) NULL,    
  [ModelYear] [smallint] null    
 )    
    
 DECLARE @intDuration int    
 DECLARE @dtOriginDateTime datetime    
 DECLARE @bigOdoMeterReading int    
 DECLARE @bitDoorStatus bit    
 DECLARE @vcStreetAddress varchar(250)    
 DECLARE @tiBoxMsgInTypeId tinyint    
 DECLARE @lastIdlingDuration int     
 DECLARE @lastIdlingTime DateTime    
 DECLARE @tiSensorNo tinyint    
 DECLARE @bigTripID bigint    
 DECLARE @intIterator int    
 DECLARE @canShowFuelMessage bit = 0    
 DECLARE @bigPreviousTripID bigint    
 DECLARE @vcVIN varchar(20) = NULL    
 DECLARE @vcLicensePlate varchar(20) =NULL    
 DECLARE @vcVehDispName varchar(50) = NULL    
 DECLARE @vcMakeName varchar (200) = NULL    
 DECLARE @vcModelName varchar(200) = NULL    
 DECLARE @intModelYear smallint = NULL    
    
 IF EXISTS (SELECT * FROM rvlfPackageOperations r    
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId    
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId    
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)    
   BEGIN    
    SET @canShowFuelMessage = 1    
   END    
    
 CREATE TABLE #tblMessageForProcessingTrip (    
  [ProcessorID] [bigint] identity(1,1) NOT NULL,    
  [MessageInId] [uniqueidentifier] NOT NULL,    
  [Boxid] [int] NOT NULL,    
  [OriginDateTime] [datetime] NOT NULL,    
  [BoxMsgInTypeId] [tinyint] NULL,      
  [DoorStatus] [bit] NULL,    
  [IgnitionStatus] [bit] NULL,    
  [StreetAddress] [varchar](250) NOT NULL,    
  [VehicleId] [bigint] NOT NULL,  
  [VIN] [varchar](20) NULL,    
  [LicensePlate] [varchar](20) NULL,    
  [VehDispName] [varchar](50) NULL,    
  [MakeName] [varchar](200) NULL,    
  [ModelName] [varchar](200) NULL,    
  [ModelYear] [smallint] null,    
  [SensorMask] varchar(250) NULL,    
  [TripId] [bigint] NULL,    
  [Duration] [int] NULL,    
  [SensorNo] [tinyint] NULL    
      
 )    
    
 CREATE INDEX IDX_RVLT_Processor on #tblMessageForProcessingTrip(ProcessorID)    
     
 DECLARE @tblBoxes TABLE (BoxID int, StartDate DateTime, EndDate DateTime)    
      
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va     
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId    
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId    
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL or BoxId = @intBoxID)    
     
 DECLARE @intBoxLooping int    
 DECLARE @dtFirstDate datetime    
 DECLARE @dtLastDate datetime    
     
 SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes    
  WHILE @intBoxLooping IS NOT NULL    
   BEGIN    
       -- Checking the first packet status    
    SELECT TOP 1 @bitDoorStatus = cast( SUBSTRING(SensorMask,8,1) as bit), @tiBoxMsgInTypeId = BoxMsgInTypeId,    
     @dtOriginDateTime = OriginDateTime, @tiSensorNo = CASE WHEN BoxMsgInTypeId = 2     
      THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,    
       CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END    
    FROM rvlfMsgInHst where BoxId= @intBoxLooping and OriginDateTime between @dtStartDate and @dtEndDate    
     AND BoxMsgInTypeId = 2 AND CAST(SUBSTRING(CustomProp ,CHARINDEX('=',CustomProp)+1,    
     CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint)=1     
    ORDER BY OriginDateTime asc    
        
    SET @dtFirstDate = NULL; SET @dtLastDate= NULL    
    --@bitDoorStatus = 1 for Open and     
    --@bitDoorStatus=0 for Close     
    --Checking the first packet is Opened       
    IF @bitDoorStatus=1 and @tiBoxMsgInTypeId = 2 AND @tiSensorNo = 1      
     BEGIN        
      SET @dtFirstDate = @dtOriginDateTime    
     END    
    ELSE IF @bitDoorStatus= 0 and @tiBoxMsgInTypeId = 2 AND @tiSensorNo = 1    
     BEGIN         
      SELECT TOP 1 @dtOriginDateTime = OriginDateTime FROM rvlfMsgInHst     
      WHERE BoxId= @intBoxLooping and BoxMsgInTypeId = 2     
       and SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,    
       CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) = '1'     
       AND OriginDateTime < @dtStartDate    
       ORDER BY OriginDateTime asc    
      SET @dtFirstDate =  @dtOriginDateTime    
     END    
         
        
     -- Checking the last packet status    
    SELECT TOP 1 @bitDoorStatus = cast( SUBSTRING(SensorMask,8,1) as bit), @tiBoxMsgInTypeId = BoxMsgInTypeId,    
     @dtOriginDateTime = OriginDateTime    
    FROM rvlfMsgInHst where BoxId= @intBoxLooping and OriginDateTime between @dtStartDate and @dtEndDate    
     AND BoxMsgInTypeId =  2 AND CAST(SUBSTRING(CustomProp ,CHARINDEX('=',CustomProp)+1,    
     CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint)=1    
    ORDER BY OriginDateTime desc    
        
    IF @bitDoorStatus = 1    
     BEGIN    
      SELECT TOP 1 @dtOriginDateTime = OriginDateTime FROM rvlfMsgInHst     
       WHERE BoxId = @intBoxLooping and BoxMsgInTypeId = 2     
        AND OriginDateTime >= @dtEndDate    
        AND CAST(SUBSTRING(CustomProp ,CHARINDEX('=',CustomProp)+1,    
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint)=1     
       ORDER BY OriginDateTime ASC     
           
      SET @dtLastDate = @dtOriginDateTime    
     END    
    ELSE IF @bitDoorStatus = 0 or @tiBoxMsgInTypeID = 2    
     BEGIN    
      SET @dtLastDate = @dtOriginDateTime    
     END    
         
    print @dtFirstDate ; print @dtLastDate    
INSERT INTO #tblMessageForProcessingTrip (    
     MessageInId, Boxid, OriginDateTime, BoxMsgInTypeId,     
     DoorStatus, IgnitionStatus, StreetAddress,    
     VehicleId, VIN, LicensePlate, VehDispName, MakeName, ModelName,ModelYear,      
     SensorMask, Duration, SensorNo)    
      SELECT h.MessageInId,h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,          
       CAST( SUBSTRING(h.sensormask,8,1) as bit) as DoorStatus,    
       CAST( SUBSTRING(h.sensormask,8,1) as bit) as IgnitionStatus,    
       --ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,
        CASE WHEN (h.LandMarkID IS NULL or h.LandMarkID = 0) THEN ISNULL(h.StreetAddress,'Address is not resolved') 
       ELSE ISNULL(L.LandmarkName, ISNULL(h.StreetAddress,'Address is not resolved'))END as StreetAddress,
       v.VehicleId,v.VIN,v.LicensePlate,v.VehicleDescription,mk.MakeName, md.ModelName,ModelYear,    
       Case WHEN h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc     
        WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +    
        CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +    
        dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'    
        ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID,     
        h.OriginDateTime, @canShowFuelMessage)END,     
       CASE WHEN h.BoxMsgInTypeID = 9 THEN     
        CAST(dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeID, h.BoxId,0) as int) ELSE 0 END,    
       CASE WHEN h.BoxMsgInTypeId = 2 THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,    
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END    
        from rvlfMsgInHst h     
         INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId    
         INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId    
         INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId    
         LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId    
         LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId    
         INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId    
         INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId    
         INNER JOIN rvlfOrganization g ON v.OrganizationId = g.OrganizationId
          LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID     
        where h.BoxMsgInTypeId = 2 AND CAST(SUBSTRING(CustomProp ,CHARINDEX('=',CustomProp)+1,    
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint)=1     
        AND 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 ( @bigFleetID IS NULL  OR f.FleetId = @bigFleetID)              
          AND h.OriginDateTime between @dtStartDate and @dtEndDate              
          AND h.BoxID = @intBoxLooping    
         order by h.origindatetime asc, h.MessageInID asc     
             
    SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes WHERE BoxID < @intBoxLooping    
   END    
    
    
  SELECT @intIterator = MIN(ProcessorID) FROM #tblMessageForProcessingTrip     
      
  WHILE @intIterator IS NOT NULL    
  BEGIN    
   SET @intBoxID = NULL; SET @dtOriginDateTime = NULL; SET @tiBoxMsgInTypeId = NULL;    
   SET @bitDoorStatus = NULL; SET @vcStreetAddress = NULL; SET @intDuration = NULL; SET @tiSensorNo = NULL    
   SELECT  @intBoxID = Boxid, @dtOriginDateTime = OriginDateTime,     
     @tiBoxMsgInTypeId = BoxMsgInTypeId,     
     @bitDoorStatus = IgnitionStatus,@vcStreetAddress = StreetAddress,     
     @intDuration = Duration, @tiSensorNo = SensorNo,    
     @vcVIN = VIN, @vcLicensePlate  = LicensePlate, @vcVehDispName  = VehDispName, @vcMakeName = MakeName,    
     @vcModelName = ModelName, @intModelYear =ModelYear    
   FROM #tblMessageForProcessingTrip WHERE ProcessorID=@intIterator    
       
   SELECT @bigTripID = ISNULL(MAX(TripID),0) FROM #tblTripDetailsForTD WHERE BoxID = @intBoxID     
        
        IF (@bitDoorStatus = 1 AND @tiBoxMsgInTypeId=2) 
			BEGIN		
				DECLARE @dtENDTIME DATETIME=NULL,@dtSTARTTIME DATETIME=NULL
				SELECT TOP 1 @dtENDTIME=OriginDateTime,@dtSTARTTIME=@dtOriginDateTime  FROM #tblMessageForProcessingTrip WHERE OriginDateTime>@dtOriginDateTime AND BoxMsgInTypeId=3AND Boxid=@intBoxID						
			END	
			    
    IF @bitDoorStatus = 1 AND @tiBoxMsgInTypeId = 2 AND @tiSensorNo = 1    
     BEGIN    
      SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM #tblTripDetailsForTD     
       WHERE BoxId = @intBoxID     
      SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM #tblTripDetailsForTD    
      INSERT INTO #tblTripDetailsForTD     
        (TripId, BoxId, StartDate, StartAddress, VIN, LicensePlate, VehDispName,     
         MakeName, ModelName,ModelYear)    
        VALUES     
        (@bigTripID, @intBoxID, @dtOriginDateTime,     
          @vcStreetAddress, @vcVIN, @vcLicensePlate, @vcVehDispName, @vcMakeName, @vcModelName,@intModelYear)    
               
     END    
    ELSE IF @bitDoorStatus = 0 AND @tiBoxMsgInTypeId = 2    
     BEGIN    
      set @lastIdlingDuration = 1    
      select TOP 1 @lastIdlingDuration = CAST(dbo.rvlf_fn_GetDuration(CustomProp,     
       BoxMsgInTypeID, BoxID, 0)as int) , @lastIdlingTime = OriginDateTime    
        FROM rvlfmsginhst where BoxId = @intBoxID    
         AND OriginDateTime <= @dtOriginDateTime    AND OriginDateTime>=@dtSTARTTIME AND OriginDateTime<=@dtENDTIME   
         AND BoxMsgInTypeId = 9 order by Origindatetime desc--, MessageInID asc    
          
      IF @lastIdlingDuration = 0     
       BEGIN    
         SET @lastIdlingDuration = ISNULL(DATEDIFF (SS, @lastIdlingTime, @dtOriginDateTime),0)    
       END    
      ELSE    
       BEGIN    
        SET @lastIdlingDuration = 0    
       END    
           
      DECLARE @nextTripStart Datetime = null    
      SELECT TOP 1 @nextTripStart = OrigindateTime    
       from rvlfMsgInHst where OriginDateTime > @dtOriginDateTime    
       AND BoxMsgInTypeId = 2 AND CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,    
       CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) = 1    
       AND BoxId = @intBoxID    
       Order by OriginDateTime asc    
           
      UPDATE #tblTripDetailsForTD SET     
       EndDate=@dtOriginDateTime , EndAddress = @vcStreetAddress    
      WHERE TripID = @bigTripID AND BoxId = @intBoxID    
     END    
    UPDATE #tblMessageForProcessingTrip SET TripId = @bigTripID where ProcessorID=@intIterator    
    SELECT @intIterator = MIN(ProcessorID) FROM #tblMessageForProcessingTrip WHERE ProcessorID > @intIterator --and TripId is NULL    
  END    
SELECT t.TripId,t.BoxId,         
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)) as 'StartDate',    
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as 'EndDate',     
   dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,StartDate,EndDate)) as Duration,    
   ABS(DateDiff(SS,StartDate,EndDate)) as TripDuration,     
   --(Select top 1 ABS(DateDiff(SS,StartDate,EndDate)) from #tblTripDetailsForTD tt order by ABS(DateDiff(SS,StartDate,EndDate)) Desc) MaxDuraion,    
   --(Select top 1 ABS(DateDiff(SS,StartDate,EndDate)) from #tblTripDetailsForTD tt order by ABS(DateDiff(SS,StartDate,EndDate)) Asc) MinDuraion,     
   (Select top 1 dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,StartDate,EndDate)) from #tblTripDetailsForTD tt order by ABS(DateDiff(SS,StartDate,EndDate)) Desc) MaxDuration,    
   (Select top 1 dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,StartDate,EndDate)) from #tblTripDetailsForTD tt order by ABS(DateDiff(SS,StartDate,EndDate)) Asc) MinDuration,        
   StartAddress, EndAddress, Vin, LicensePlate, VehDispName as VehicleDescription, MakeName, ModelName,ModelYear     
  FROM #tblTripDetailsForTD t    
      
  DROP Table #tblMessageForProcessingTrip    
  DROP Table #tblTripDetailsForTD    
      
 SET NOCOUNT OFF    
END    
    
    
    
  
--rvlf_sp_GetPTOReportDetails null,15, '2010-08-18 02:30:00:00', '2010-08-19 14:30:00',null, 16,12    
--rvlf_sp_GetPTOReportDetails null,15, '2010-08-18 13:33:00:00', '2010-08-19 14:30:00',null, 16,12    
--rvlf_sp_GetPTOReportDetails null,15, '2010-08-18 02:30:00:00', '2010-08-19 11:38:00',null, 16,12 



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetRecentActivityNotifications]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetRecentActivityNotifications]           
/******************************************************          
Stored Procedure Name : [rvlf_sp_GetRecentActivityNotifications] 140,40  
Purpose     : Retrieve  recent activity notifications       
Created by    : Ranjith N          
Created date   : 11-Oct-14          
Update History:          
        
*******************************************************/           
 @intUserid int =null,       
 @intLastHour int = null
       
AS          
BEGIN              
      
   Select         
 (Select count(a.AlarmId) as TotalAlarms from rvlfAlarm a
 inner join rvlfVehicleAssignment va on va.BoxId = a.BoxId
 inner join rvlfFleetVehicles fv on fv.VehicleId = va.VehicleId
 inner join rvlfFleetUsers fu on fu.FleetId = fv.FleetId 
 where FU.UserId = 140-- and a.DateTimeCreated between DATEADD(HH,(-1*@intLastHour),GETUTCDATE()) and GETUTCDATE() 
 ) as TotalAlarms,
  
  (Select count(a.BoxId) as TotalAlarms from rvlfBoxId a
 inner join rvlfVehicleAssignment va on va.BoxId = a.BoxId
 inner join rvlfFleetVehicles fv on fv.VehicleId = va.VehicleId
 inner join rvlfFleetUsers fu on fu.FleetId = fv.FleetId 
 where FU.UserId = 140-- and a.DateTimeCreated between DATEADD(HH,(-1*@intLastHour),GETUTCDATE()) and GETUTCDATE() 
 ) as TotalReportedVehicles    
        
                
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetRefreshFrequency]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetRefreshFrequency](@bigUserID int,@bigOrgID bigint = null)  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_GetRefreshFrequency]  
-- Description : To get the Screen Refesh Frequency  
-- Author  : T.Sathish  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 08-Aug-2009 TSK Created Intial Version   
/******************************************************************************/  
BEGIN  
select RefreshFrequencyValue from rvlfUserPreferences UP INNER JOIN   
         rvlfScreenRefreshFrequency RF on UP.RefreshFrequencyId = RF.FrequencyId  
         INNER JOIN rvlfUser U on U.UserId = UP.UserId INNER JOIN rvlfOrganization O  
         ON O.OrganizationId = U.OrganizationId  
         where U.UserId = @bigUserID and (@bigOrgID is null OR @bigOrgID='' or @bigOrgID = 0 OR O.OrganizationId = @bigOrgID)  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetRefrigerationDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetRefrigerationDetails]              
              
 @RefID bigint = null,              
 @bigOrganizationId bigint          
AS              
/******************************************************************************/              
-- Name  : [rvlf_sp_GetRefrigerationDetails]null,6              
-- Description : To get the Refrigeration details              
--    :   Pass the values to @RefID               
-- Author  : Kapil.              
-- Company  : Angler Technologies              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
--    : 07-May-2014 Created Intial Version               
/******************************************************************************/              
BEGIN              
 IF @RefID = 0 SET @RefID = null                  
               
               
  IF @RefID is not null                
               
  BEGIN              
                 
   SELECT top 1 fv.FleetId,refasgn.vehicleid, ref.RefgId,RefgMake,RefgName,[Year],ModelNo,ModeOfPurchase, CONVERT(VARCHAR(11), AssessedDate, 106) AS AssessedDate,AssessedValue,CONVERT(VARCHAR(11), DateOfPurchase, 106) AS DateOfPurchase,PurchaseValue,     
  
    
   TechDetails,EngineNo,CompressorNo,AvgFuel,ref.IsActive, CASE WHEN ref.IsActive = 1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus        
   FROM rvlfRefrigeration as ref        
   left join rvlfrefrigeratorassignmt as refasgn on ref.RefgId=refasgn.RefgId and refasgn.unassigndate is null        
   left join rvlfFleetVehicles as fv on refasgn.vehicleid=fv.VehicleId        
   where ref.RefgId  = @RefID AND IsDelete =0 and OrganizationId = @bigOrganizationId    
                  
END              
              
ELSE              
              
BEGIN              
              
   SELECT ref.RefgId,RefgMake,RefgName,[Year],ISNULL(ModelNo,'-')as ModelNo,isnull(ModeOfPurchase,'-') as ModeOfPurchase,isnull(CONVERT(VARCHAR(11), AssessedDate, 106) ,'-')AS AssessedDate,      
   isnull(AssessedValue,'-') as AssessedValue,isnull(CONVERT(VARCHAR(11), DateOfPurchase, 106),'-')AS DateOfPurchase,isnull(PurchaseValue,'-') as PurchaseValue,      
   TechDetails,EngineNo,CompressorNo,isnull(AvgFuel,0) as AvgFuel,isnull(V.VehicleDescription,'-') as VehicleDescription, CASE WHEN ref.IsActive = 1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus       
   ,ref.OrganizationId FROM rvlfRefrigeration ref    
   left join rvlfrefrigeratorassignmt as refasgn on ref.RefgId=refasgn.RefgId and UnAssignDate is null       
   --left join rvlfFleetVehicles as fv on refasgn.vehicleid=fv.VehicleId     
   left join rvlfVehicle V on refasgn.VehicleId=V.VehicleId    
   WHERE IsDelete =0 and ref.OrganizationId = @bigOrganizationId   
                 
   SELECT CONVERT(VARCHAR(11), GETDATE(), 106) AS [DD MON YYYY]               
               
END              
              
              
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetRemovedTyreDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
CREATE PROCEDURE [dbo].[rvlf_sp_GetRemovedTyreDetails]  
      
--@FleetID BIGINT = null,   
--@TyreMapId int = Null,                        
@bigOrganizationId bigint = Null,                        
@bigUserId bigint = Null
          
AS          
-- =============================================          
-- Name   : rvlf_sp_GetRemovedTyreDetails 6,18			
-- Author  : Kapil          
-- Create date : 27-Jun-2014          
-- Description : Get Tyre Mapped Details          
-- Company  : TRINETRA 
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
-- =============================================          
BEGIN          
 -- SET NOCOUNT ON added to prevent extra result sets from          
 -- interfering with SELECT statements.          
 SET NOCOUNT ON;    

select TyreName,LifeTimeKM,AvailLifeTime,RemoveComments,
RemovedDate,RemovedOdometer,
ISNULL(VT.VehicleDescription, V.VehicleDescription) as VehicleDescription,
ISNULL(AT.AxleName,A.AxleName) as AxleName,
ISNULL(lT.TyreLocation,L.TyreLocation) as TyreLocation,
ISNULL(Vm.ToVehicleOdometer,Vm.Odometer) as Odometer,
Make.BrandName,
CASE WHEN ISNULL(IsRethread,0) <> 0 THEN ISNULL(ReVen.VendorName,Ven.VendorName) ELSE Ven.VendorName END as VendorName
from rvlfTyreVehicleMapping VM 
LEFT OUTER JOIN rvlfVehicle V on V.VehicleId = VM.VehicleID
LEFT  JOIN rvlfVehicle VT ON VT.VehicleId = VM.ToVehicleId 
LEFT  JOIN rvlfTyreAxleMaster A on A.AxleId = VM.AxleID
LEFT  JOIN rvlfTyreAxleMaster AT on At.AxleId = VM.ToAxleId
LEFT  JOIN rvlfTyreLocationMaster L on L.TyreLocationID = VM.TyreLocationID
LEFT  JOIN rvlfTyreLocationMaster Lt on Lt.TyreLocationID = VM.ToLocationID
	--LEFT  JOIN rvlfTyreMaster T on T.BrandID = VM.BrandID
left JOIN rvlfTyreModel Model on Model.ModelID = VM.ModelID 
left  JOIN rvlfTyreMake Make on Make.BrandID = Model.BrandID	
LEFT  JOIN rvlfTyreVendorMaster Ven  on Ven.VendorId = Vm.VendorId
LEFT  JOIN rvlfTyreVendorMaster ReVen  on ReVen.VendorId = Vm.RetreadVendorId
where VM.Category = 2 and VM.IsDelete=0 and VM.OrganizationId = @bigOrganizationId and IsRethread <> 2 and VM.IsActive = 1
  
set Nocount off;        
END 




GO
/****** Object:  StoredProcedure [dbo].[rvlf_Sp_GetReport_Param]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_Sp_GetReport_Param] 
	@VehicleTypeId int = NULL,
	@UserId bigint = NULL,
	@OrganizationId INT = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    SELECT ParamId,ParamName,ParamDescription FROM rvlf_Rpt_ParamMst WHERE ParamId  NOT IN(4) AND VehicleTypeId=@VehicleTypeId


END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetReportCategoryTypes]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetReportCategoryTypes]  
 @bigUserID bigint =null,  
 @bigOrganizationID bigint=null  
   
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetReportCategoryTypes  
-- Description : To get the Report Category tyoes  
-- Author  : V.Muthukumaravadivel  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 02-March-2011  Created Intial Version   
  
/******************************************************************************/  
BEGIN  
 declare @Lang varchar(50)           
 select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigUserID
SET NOCOUNT ON   
   
  BEGIN  
  SELECT DISTINCT RC.CategoryTypesId,case When  @Lang='LanguageArNew' then ISNULL(CategoryTypesName_Ar,CategoryTypesName) else CategoryTypesName end as CategoryTypesName          
   --SELECT DISTINCT RC.CategoryTypesId,CategoryTypesName       
   FROM RvlfReportCategoryTypes RC  
    INNER JOIN rvlfReportTypes RT ON RT.CategoryTypesId=RC.CategoryTypesId   
    INNER JOIN rvlfOperationType OT ON OT.OperationTypeId = RT.OperationTypeId  
    INNER JOIN rvlfModule M ON OT.ModuleID = M.ModuleID     
    INNER JOIN rvlfUserGroupSecurity UP ON UP.OperationTypeId = OT.OperationTypeId AND UP.UserGroupId =  
    (SELECT distinct UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = CASE WHEN @bigUserID IS NULL THEN 1 ELSE @bigUserID END )  
   WHERE OT.ModuleID = 11  
      
   ORDER BY CategoryTypesId ASC   
  END  
   
SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetReportingIntDur_Live]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetReportingIntDur_Live]
@nOrgId INT = NULL,
@nUserId INT = NULL
AS
/*************************************************************************************      
Procedure Name		: rvlf_sp_GetReportingIntDur_Live 6,94
Purpose				: Get the Reporting interval & duration for live tracking
Created by			: Sakthi Gopinath S
Created date		: 2016-08-12
**************************************************************************************/    
BEGIN
SET NOCOUNT ON
	SELECT Sno,IntInMin,IntInSec FROM rvlfRptDuration_LT WHERE ((IsDefault=1 AND IsDelete=0 AND OrgId=1) OR (OrgId=@nOrgId AND CreatedBy=@nUserId AND IsDelete=0))
	SELECT Sno,IntInMeter FROM rvlfRptInterval_LT  WHERE ((IsDefault=1 AND IsDelete=0 AND OrgId=1) OR (OrgId=@nOrgId AND CreatedBy=@nUserId AND IsDelete=0))
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetReportTypes]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--SELECT * FROM rvlfReportTypes WHERE ReportTypesId  IN (7,8,9,10,15)     
    
CREATE Procedure [dbo].[rvlf_sp_GetReportTypes]        
 @bigReportType bigint = null,        
 @bigUserID AS bigint = null,        
 @bigModuleID as bigint = 11,        
 @bitIsNonAnglerAdmin AS bit = 0,        
 @bigOrganizationID AS bigint = NULL,        
 @bigCategoryTypesID as bigint = NULL        
AS        
/******************************************************************************/        
-- Name  : rvlf_sp_GetReportTypes 1,303,11,0,138,1        
-- Description : To get the report tyoes        
-- Author  : M. Jebamalai Jaya Chitra.        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--    : 12-Sep-2009 MJJC Created Intial Version         
--    : 28-Sep-09 Christopher S  Getting Report type id, name from        
--    :        rvlfOperationType for report module(8)         
--    : 05-MAY-2011 MK INCLUDE THE REPORT CATEGORY TYPE.        
--    : 05-MAY-2011 VN CHECK THE NULL VALUE IN THE REPORT CATEGORY     
--   : 02-Aug-2011 Sakthi Restrict the fuel drain, high, low, and driver activity           
/******************************************************************************/        
BEGIN   
declare @Lang varchar(50)             
select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigUserID            
SET NOCOUNT ON         
 IF @bigOrganizationID is NULL OR @bitIsNonAnglerAdmin = 1        
  BEGIN        
 SELECT ReportTypesId,
 case When  @Lang='LanguageArNew' then ISNULL(ReportTypesName_Ar,ReportTypesName) 
	  When 	@Lang='LanguageHindi' then ISNULL(ReportTypesName_Hin,ReportTypesName) 
 else ReportTypesName end as ReportTypesName ,
 GuiId,GuiName,OperationTypeId,CategoryTypesId FROM rvlfReportTypes WHERE ReportTypesId NOT IN (7,8,9,10,15)
 AND (@bigCategoryTypesID IS NULL OR @bigCategoryTypesID='' OR CategoryTypesID=@bigCategoryTypesID)order by ReportTypesId asc  
--   SELECT * FROM rvlfReportTypes WHERE ReportTypesId NOT IN (7,8,9,10,15) AND (@bigCategoryTypesID IS NULL OR @bigCategoryTypesID='' OR CategoryTypesID=@bigCategoryTypesID)order by ReportTypesId asc         
   SELECT COUNT(*) as NoOfVehicles FROM rvlfVehicle WHERE OrganizationId = @bigOrganizationID        
  END        
 ELSE IF(@bitIsNonAnglerAdmin = 0)        
    BEGIN        
   SELECT RT.ReportTypesId,
   --case When  @Lang='LanguageArNew' then ISNULL(RT.ReportTypesName_Ar,RT.ReportTypesName) else RT.ReportTypesName end as ReportTypesName,
   case When  @Lang='LanguageArNew' then ISNULL(ReportTypesName_Ar,ReportTypesName) 
	  When 	@Lang='LanguageHindi' then ISNULL(ReportTypesName_Hin,ReportTypesName) 
	else ReportTypesName end as ReportTypesName ,
   
   RT.GuiId,RT.GuiName,RT.OperationTypeId,RT.CategoryTypesId           
   FROM rvlfReportTypes RT        
   INNER JOIN rvlfOperationType OT ON OT.OperationTypeId = RT.OperationTypeId        
   INNER JOIN rvlfModule M ON OT.ModuleID = M.ModuleID           
   INNER JOIN rvlfUserGroupSecurity UP ON UP.OperationTypeId = OT.OperationTypeId AND UP.UserGroupId =        
    (SELECT distinct UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigUserID)        
   WHERE RT.ReportTypesId NOT IN (7,8,9,10,15) AND OT.ModuleID = 11 and (@bigCategoryTypesID IS NULL OR @bigCategoryTypesID='' OR CategoryTypesID=@bigCategoryTypesID)        
   SELECT COUNT(*) as NoOfVehicles FROM rvlfVehicle WHERE OrganizationId = @bigOrganizationID        
    END        
SET NOCOUNT OFF        
END        
        

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetRFIDActivity]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[rvlf_sp_GetRFIDActivity]  
@bigFleetID bigint = NULL,  
@intBoxID int = NULL,  
@dtStartDate datetime = NULL,  
@dtEndDate datetime =NULL,  
@bigOrganizationID bigint = NULL,  
@key int =NULL,  
@bigQueryingUser bigint = NULL  
AS  
/*******************************************************************************************************/                    
-- Name  : rvlf_sp_GetRFIDActivity 581,NULL,'2016-07-14 08:04:00.000','2016-07-14 20:04:00.000',292,null,292
-- Description : To get the RFID Activities                   
-- Created date : 21-Feb-2012                  
-- Created by : Sakthi Gopinath S
/*******************************************************************************************************/    
BEGIN  
SET NOCOUNT ON  
 
 DECLARE @dtFDate datetime =@dtStartDate    
 DECLARE @dtEDate datetime =@dtEndDate    
 DECLARE @HoursToBeAdded INT = 0    
 DECLARE @MinsToBeAdded INT = 0     
 DECLARE @DefaultDateFormat INT = 0  
 DECLARE @Lang varchar(50),  @LangSetting varchar(20)     
    
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,  
 @DefaultDateFormat=(case when ISNULL(up.DefaultDateFormat,0)=0 then 106 else up.DefaultDateFormat end),
@Lang= isnull(up.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  
 
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))           
   

 SELECT h.BoxId,v.VehicleId,v.VehicleDescription,v.DisplayName,v.Vin,v.LicensePlate,o.OrganizationId,  
 o.OrganizationDisplayName,  
 CONVERT(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,h.OriginDateTime)),@DefaultDateFormat) + ' ' + CONVERT(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,h.OriginDateTime)) as time),22) AS OriginDateTime,  

 DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,h.OriginDateTime)) AS OriginDateTimeSort,  
 dbo.rvlf_fn_GetAlarmDetails_New(h.CustomProp,100,h.BoxId,h.MessageInId,h.OriginDateTime,@Lang) AS [Messages],  
 ISNULL(h.StreetAddress,'-') AS StreetAddress,
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,
 Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,
 Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate   
 FROM dbo.rvlfMsgInHst h INNER JOIN dbo.rvlfVehicleAssignment va ON va.BoxId=h.BoxId  
 INNER JOIN dbo.rvlfVehicle v ON v.VehicleId=va.VehicleId INNER JOIN dbo.rvlfFleetVehicles fv  
 ON fv.VehicleId=v.VehicleId INNER JOIN dbo.rvlfFleet f ON f.FleetId=fv.FleetId  
 INNER JOIN dbo.rvlfOrganization o ON o.OrganizationId=v.OrganizationId  
 WHERE BoxMsgInTypeId=100 AND h.CustomProp LIKE '%RF_ID=%' AND   
 (@key IS NULL OR @key='' OR h.CustomProp like   
 (SELECT '%'+IButtonKey+'%' FROM dbo.rvlfIButtonMapping WHERE OrganizationId=@bigOrganizationID   
  AND KeyType=3 AND IButtonId=@key)) AND  
 (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId=@bigFleetID) AND   
 (@intBoxID IS NULL OR @intBoxID='' OR h.BoxId=@intBoxID) AND  
 (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR o.OrganizationId=@bigOrganizationID) AND  
 h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate  
 ORDER BY OriginDateTime DESC  
  
SET NOCOUNT OFF  
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetRFIDActivitySummary]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
CREATE PROC [dbo].[rvlf_sp_GetRFIDActivitySummary]              
@bigFleetID bigint = NULL,              
@intBoxID varchar(max) = NULL,              
@dtStartDate datetime = NULL,              
@dtEndDate datetime =NULL,              
@bigOrganizationID bigint = NULL,              
@key int =NULL,              
@bigQueryingUser bigint = NULL              
AS              
/*******************************************************************************************************/                                
-- Name  : rvlf_sp_GetRFIDActivitySummary 8,null,'2014-11-12 10:27:01.000','2014-11-14 11:23:00.000',6,null,94              
-- Description : To get the RFID Activities User based IN and OUT          
-- Created date : 10-Nov-2014                              
-- Created by : Gopalakrishnan.R         
/*******************************************************************************************************/                
BEGIN              
SET NOCOUNT ON              
             
 DECLARE @dtFDate datetime =@dtStartDate                
 DECLARE @dtEDate datetime =@dtEndDate                
 DECLARE @HoursToBeAdded INT = 0                
 DECLARE @MinsToBeAdded INT = 0                 
 DECLARE @DefaultDateFormat INT = 0              
                
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,              
 @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(@bigQueryingUser IS NULL OR @bigQueryingUser='' OR up.UserId = @bigQueryingUser)                
           
            
DECLARE @tblMessageForProcessingTrip TABLE ( sno int identity(1,1),Boxid bigint,        
 MessageInID uniqueidentifier, [OriginDateTime] [datetime] NOT NULL,[BoxMsgInTypeId] [tinyint] NULL,[CustomProp] [varchar](600) NULL,            
 [Speed] int NULL,[Ignition] bit null,[Address] nvarchar(300) null,[OdoMeter] bigint null, Lat numeric(10,6), Long numeric(10,6) )         
DECLARE @tmptbl table (Sno int,Boxid bigint,RFID varchar(200),MessageInIDIN uniqueidentifier,OriginDateTimeIN datetime,        
 AddressIN varchar(250),MessageInIDOut uniqueidentifier,OriginDateTimeOUT datetime)        
DECLARE @tmptblinout table (Sno int,Boxid bigint,RFID varchar(200),Unauthorized int,MessageInIDIN uniqueidentifier,OriginDateTimeIN datetime,AddressIN   varchar(250),AddressOut varchar(250),OriginDateTimeOUT datetime)        
DECLARE @RFIDDetails table (Boxid bigint,RFID varchar(50), OriginDateTimeIN datetime,OriginDateTimeOUT datetime, IButtonKeyName varchar(100),Speed bigint,MaxOdo bigint,MinOdo bigint)      
      
INSERT INTO @tblMessageForProcessingTrip(Boxid,MessageInID,OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,OdoMeter,Lat,Long)                    
SELECT h.BoxId, H.MessageInID,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  H.StreetAddress 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 dbo.rvlfLandmark L ON L.LandmarkID=H.LandMarkID      
WHERE(@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR  h.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))               
 AND OriginDateTime BETWEEN @dtStartDate AND @dtEndDate  and BoxMsgInTypeId not in (35)    
      
INSERT into @tmptbl (sno,Boxid,RFID,MessageInIDIN,OriginDateTimeIN,AddressIN)      
select sno,Boxid,dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';'),MessageInID,OriginDateTime,[Address]        
from @tblMessageForProcessingTrip      
where BoxMsgInTypeId=100 and CHARINDEX('IN;RF_ID=',CustomProp,0)!=0      
      
--select MAX(OriginDateTimeIN),MessageInIDOut as msg from @tmptbl group by MessageInIDOut      
      
INSERT into @tmptblinout      
select a.Sno ,a.Boxid,a.RFID,Unauthorized,a.MessageInIDIN,a.OriginDateTimeIN,AddressIN,[Address],min(b.OriginDateTime) as OutTime from @tmptbl a       
LEFT JOIN       
(select dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RF_ID=',';') as RFID ,CHARINDEX('Unauthorized',CustomProp,0)as Unauthorized,* from @tblMessageForProcessingTrip where BoxMsgInTypeId=100 and CHARINDEX('OUT;RF_ID=',CustomProp,0)!=0) as b   
on a.RFID=b.RFID and a.OriginDateTimeIN<b.OriginDateTime      
group by a.Sno ,a.Boxid,a.RFID,a.MessageInIDIN,a.OriginDateTimeIN,b.RFID,AddressIN,[Address],Unauthorized      
      
INSERT into @RFIDDetails      
select tbl.Boxid,tbl.RFID,MAX(tbl.OriginDateTimeIN),tbl.OriginDateTimeOUT,BM.IButtonKeyName,MAX(trp.Speed) ,MAX(trp.OdoMeter),    
MIN(trp.OdoMeter)      
from @tmptblinout tbl INNER JOIN rvlfIButtonMapping BM on tbl.RFID=BM.IButtonKey and BM.KeyType=3      
INNER JOIN @tblMessageForProcessingTrip trp on tbl.Boxid=trp.Boxid and trp.OriginDateTime between tbl.OriginDateTimeIN and OriginDateTimeOUT group by tbl.BoxID,tbl.RFID,tbl.OriginDateTimeOUT,BM.IButtonKey,BM.IButtonKeyName      
        
select RD.Boxid ,V.VehicleId,V.VehicleDescription,V.Vin,V.LicensePlate,RD.RFID,Unauthorized, RD.OriginDateTimeIN as OriginDateTimeINsort,    CONVERT(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,RD.OriginDateTimeIN)),@DefaultDateFormat) + ' ' + 
CONVERT(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,RD.OriginDateTimeIN)) as time),22) AS OriginDateTimeIN,    
 CONVERT(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,RD.OriginDateTimeOUT)),@DefaultDateFormat) + ' ' + CONVERT(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,RD.OriginDateTimeOUT)) as time),22) AS OriginDateTimeOUT        
,RD.OriginDateTimeOUT as OriginDateTimeOUTsort,isnull(AddressIN,'N/A') as AddressIN,isnull(AddressOut,'N/A') as AddressOut,        
dbo.rvlf_fn_GetTimeFromSeconds(datediff(second,RD.OriginDateTimeIN,RD.OriginDateTimeOUT)) as Duration,        
IButtonKeyName as keyname,Speed as maxspeed,(MaxOdo-MinOdo) Distance ,        
Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,            
 Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,            
 Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,    
 tblsum.DistanceSum, dbo.rvlf_fn_GetTimeFromSeconds(tblsum.DurationSum) as DurationSum,tblsum.MAXSpdsmry        
 from @RFIDDetails RD       
 INNER JOIN @tmptblinout Tb on RD.Boxid=Tb.Boxid and RD.RFID=Tb.RFID and RD.OriginDateTimeIN=Tb.OriginDateTimeIN and      
(RD.OriginDateTimeOUT=tb.OriginDateTimeOUT or RD.OriginDateTimeOUT is null)    
INNER JOIN rvlfVehicleAssignment VA on RD.Boxid=VA.BoxId        
INNER JOIN rvlfVehicle V on VA.VehicleId=V.VehicleId        
INNER JOIN dbo.rvlfFleetVehicles fv              
 ON fv.VehicleId=v.VehicleId INNER JOIN dbo.rvlfFleet f ON f.FleetId=fv.FleetId              
 INNER JOIN dbo.rvlfOrganization o ON o.OrganizationId=v.OrganizationId     
 INNER JOIN (select Boxid, sum(datediff(second,OriginDateTimeIN,OriginDateTimeOUT)) DurationSum,SUM(MaxOdo-MinOdo)as DistanceSum,MAX(Speed)MAXSpdsmry from @RFIDDetails    
group by Boxid) as tblsum on RD.Boxid=tblsum.Boxid             
 WHERE          
 (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId=@bigFleetID) AND               
 --(@intBoxID IS NULL OR @intBoxID='' OR RD.BoxId=@intBoxID) AND              
  --(@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR  h.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND         
  (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR o.OrganizationId=@bigOrganizationID)               
 --AND RD.OriginDateTimeIN BETWEEN @dtStartDate AND @dtEndDate              
 ORDER BY RD.OriginDateTimeIN DESC              
         
--select Boxid, datediff(second,MAX(OriginDateTimeIN),MAX(OriginDateTimeOUT)) from @RFIDDetails    
         
SET NOCOUNT OFF              
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetROIAnalysis]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetROIAnalysis]  
@bigFleetID bigint = null,
@intBoxID VARCHAR(MAX) = null,
@dtStartDate datetime = null,
@dtEndDate datetime = null,
@cbFootPrint decimal(6,2)=0.33,
@km bigint = 30000,
@fcPerLtr decimal(6,2) = 48.0,
@distPerLtr decimal(6,2) = 5,
@fcPerLtrHV decimal(6,2)=30.0,
@distPerLtrHV decimal(6,2) = 10,
@fcsPerHr int = 4,
@fcsPerHrHV int = 8,
@CurrId tinyint = 1,
@currRate decimal(8,2) = 1.00,
@bigOrganizationID bigint = null,
@bigQueryingUser bigint = 0
/*********************************************************************************************************************************************/          
-- Procedure Name	: rvlf_sp_GetROIAnalysis 222,NULL,'07/01/2012 8:00:00 AM','08/31/2012 8:00:00 PM',0.33,30000,
--								  65.75,30,25.5,15,10,4,1,1.00,138,303  
-- Description		: To get the ROI Details  
-- Author			: Sakthi  
-- Company			: Angler Technologies          
-- History			: <<Date(dd-MON-yyyy)>> Initial Reason          
--					: 17-Jun-2013 Sakthi    
/*********************************************************************************************************************************************/         
AS  
BEGIN  
SET NOCOUNT ON  
 
	Declare @dtFDate datetime =@dtStartDate
	Declare @dtEDate datetime =@dtEndDate
	Declare @fleetName varchar(25)
	DECLARE @HoursToBeAdded INT = 0    
	DECLARE @MinsToBeAdded INT = 0    
	DECLARE @ConversionFactor numeric (10,2) = 1.0    
	DECLARE @DistanceCaptionPrefix varchar(15)    
	DECLARE @fuelConversionFactor numeric(10,2)=1.0
	DECLARE @FuelCaptionPrefix varchar(15)
	DECLARE @SpeedCaptionPrefix varchar(15)  
	DECLARE @DefaultDateFormat INT = 0;
	DECLARE @DefCurrName varchar(6) = null
	DECLARE @CtCurrName varchar(6) = null
	
    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 '(mi)' ELSE '(kms)' END,    
    @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(mph)' ELSE '(kmph)' END,
    @fuelConversionFactor = CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 END,
    @FuelCaptionPrefix = CASE WHEN up.Fuel = 0 THEN '(gal)' ELSE '(ltr)' END,
    @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end),
    @DefCurrName='('+ct.CurrencyName+')'
    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
    INNER JOIN rvlfCurrencyType ct ON ct.CurrencyTypeId=o.CurrencyTypeId
    WHERE up.UserId = @bigQueryingUser
     
	SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))    
	SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))    
	SELECT @CtCurrName='('+CurrencyName+')' FROM dbo.rvlfCurrencyType WHERE CurrencyTypeId=@CurrId
	
	SELECT @fcsPerHr = @fcsPerHr * @fuelConversionFactor,@fcsPerHrHV = @fcsPerHrHV * @fuelConversionFactor,
	@fcPerLtr = @fcPerLtr / @fuelConversionFactor , @fcPerLtrHV = @fcPerLtrHV / @fuelConversionFactor 
	
	IF EXISTS(SELECT 1 FROM dbo.rvlfOrganization WHERE CurrencyTypeId=@CurrId)
	BEGIN
		SET @currRate=1.00
	END

	IF @bigFleetID IS NULL          
	BEGIN          
		SELECT @bigFleetID=FleetID from dbo.rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1          
	END
	
	SELECT @fleetName = FleetName FROM rvlfFleet WHERE FleetId=@bigFleetID
	
   
	DECLARE @tblBoxes TABLE (BoxID bigint,VehicleType tinyint,OdoStart bigint,OdoEnd bigint,Distance bigint,Idling bigint,Running bigint,NoOfDays tinyint,  
	InsDate datetime,FMEndDate datetime,OperatingCost decimal(16,2) null,OwnershipCost decimal(16,2) null,OtherCost decimal(16,2) null,
	CostPerKm decimal(16,2))  
	INSERT INTO @tblBoxes(BoxID,VehicleType,OdoStart,OdoEnd,Distance,Idling,Running,NoOfDays,InsDate,FMEndDate)
	SELECT RI.BoxId,ISNULL(v.VehicleTypeId,1),RI.OdoStart,RI.OdoEnd,RI.Distance,RI.Idling/3600,RI.Running,RI.NoOfDays,
	v.InstalledDate,RI.StartDate--,RI.IsMonthStart  
	FROM rvlfTripDetails_ROI RI INNER JOIN rvlfBoxId b ON b.BoxId=RI.BoxId  
	INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId  
	INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=va.VehicleId  
	INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId
	WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or b.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))   
	AND b.OrganizationId=@bigOrganizationID AND RI.IsMonthStart=1  
   
	--SELECT va.BoxId, SUM(CASE WHEN RC.CostType=1 AND RC.Id > 1 THEN (@km*vc.Cost) ELSE 0 END) AS OpC,
	--SUM(CASE WHEN RC.CostType=2 THEN (@km*vc.Cost) ELSE 0 END) AS OwC,
	--SUM(CASE WHEN RC.CostType=3 THEN (8*vc.Cost) ELSE 0 END) AS OtC
	--FROM rvlfVehicleCost vc INNER JOIN rvlfROICost RC ON RC.Id=vc.CostType
	--INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=vc.VehicleId 
	--INNER JOIN @tblBoxes b ON b.BoxID=va.BoxId
	--GROUP BY va.BoxId
	
	--SELECT ROI.BoxId,(ROI.OpC+ROI.OwC+ROI.OtC)/@km AS CostPerKm FROM
	UPDATE boxes SET boxes.CostPerKm=(CASE WHEN ROI.Distance <= 0 OR ISNULL(boxes.OdoEnd,0) = 0  THEN 0.00 ELSE (ROI.OpC+ROI.OwC+ROI.OtC)/(ROI.Distance * @ConversionFactor) END) 
	FROM @tblBoxes boxes INNER JOIN(SELECT va.BoxId,td.Distance,SUM(CASE WHEN RC.CostType=1 AND RC.Id > 1 THEN (td.Distance*@ConversionFactor*vc.Cost) ELSE 0 END) AS OpC,
	SUM(CASE WHEN RC.CostType=2 THEN (td.Distance*@ConversionFactor*vc.Cost) ELSE 0 END) AS OwC,
	SUM(CASE WHEN RC.CostType=3 THEN (8*vc.Cost) ELSE 0 END) AS OtC
	FROM rvlfVehicleCost vc INNER JOIN (SELECT VehicleId,CostType,MAX(CreatedDate) AS CreatedDate FROM rvlfVehicleCost GROUP BY VehicleId,CostType) ab 
	ON vc.VehicleId=ab.VehicleId AND vc.CostType=ab.CostType AND vc.CreatedDate=ab.CreatedDate
	INNER JOIN rvlfROICost RC on RC.Id=vc.CostType
	INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=vc.VehicleId
	INNER JOIN @tblBoxes b ON b.BoxID=va.BoxId
	INNER JOIN (SELECT BoxId,(SUM(ISNULL(Distance,0))) AS Distance FROM rvlfTripDetails_ROI GROUP BY BoxId) td ON td.BoxId=b.BoxID
	WHERE RC.OrgId=@bigOrganizationID
	GROUP BY va.BoxId,td.Distance
	--FROM rvlfVehicleCost vc INNER JOIN rvlfROICost RC ON RC.Id=vc.CostType
	--INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=vc.VehicleId 
	--INNER JOIN @tblBoxes b ON b.BoxID=va.BoxId GROUP BY va.BoxId
	) ROI ON ROI.BoxId=boxes.BoxID
   
	SELECT Res.*,v.VehicleId,v.VehicleDescription,v.LicensePlate,v.Vin,@fleetName FleetName,CAST(DATENAME(MONTH,Res.StartDate) AS VARCHAR) +' '+CAST(DATEPART(YEAR,Res.StartDate) AS VARCHAR) AS Years,
	CAST(DATENAME(MONTH,Res.StartDate) AS VARCHAR) AS Months,
	--'Month '+CAST(DATEDIFF(MONTH,Res.InsDate,Res.StartDate) AS VARCHAR) AS Months,
	CASE WHEN Res.IsMonthStart=1 THEN '0.00' ELSE 
	CAST((CAST(Res.CostReductionKms AS DECIMAL(16,2))+CAST(Res.CostReductionIdling AS DECIMAL(16,2))) AS DECIMAL(16,2)) END AS TotalCostSavings ,
	Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,
    Convert(varchar,@dtEDate,@DefaultDateFormat)+' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,
    PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())  
	FROM
	(
	SELECT RI.Sno,RI.BoxId,RI.OdoStart,RI.OdoEnd,(RI.Distance * @ConversionFactor) AS Distance,(RI.Idling/3600) AS Idling,RI.Running,
	RI.NoOfDays,RI.StartDate,RI.IsMonthStart,RI.InstalledDate,
	bx.InsDate,vt.VehicleTypeName,NULL AS MaxOdo,--h.Odometer AS MaxOdo,
	(RI.Idling/3600)*@cbFootPrint AS CbFootPrint,
	CAST(((RI.Distance * @ConversionFactor * bx.CostPerKm) / @currRate) AS DECIMAL(16,2))AS CostDistTravelled,
	(CAST((CASE WHEN bx.VehicleType > 1 THEN (@fcPerLtrHV * @fcsPerHrHV) ELSE (@fcPerLtr * @fcsPerHr) END) / @currRate AS DECIMAL(16,2)) ) AS FuelCostPerIdling,
	(CAST(((CASE WHEN bx.VehicleType > 1 THEN (@fcPerLtrHV / @distPerLtrHV) ELSE (@fcPerLtr / @distPerLtr) END))/ @currRate AS DECIMAL(16,2))) AS TotFuelCostPerKm,
	(CAST((RI.Idling/3600)*(CASE WHEN bx.VehicleType > 1 THEN (@fcPerLtrHV*@fcsPerHrHV)  ELSE (@fcPerLtr *@fcsPerHr) END)/ @currRate AS DECIMAL(16,2))) AS CostIncurredIdling,
	CASE WHEN RI.IsMonthStart=1 THEN '-' ELSE CAST((CAST(((RI.Distance - (SELECT ISNULL((SELECT Distance FROM @tblBoxes WHERE BoxId=RI.BoxId),0)))* @ConversionFactor * bx.CostPerKm)/ @currRate AS DECIMAL(16,2))) AS VARCHAR) END AS CostReductionKms,
	CASE WHEN RI.IsMonthStart=1 THEN '-' ELSE CAST((CAST((((RI.Idling/3600) - (SELECT ISNULL((SELECT Idling FROM @tblBoxes WHERE BoxId=RI.BoxId),0)))*
	(CASE WHEN bx.VehicleType > 1 THEN (@fcPerLtrHV*@fcsPerHrHV) ELSE (@fcPerLtr*@fcsPerHr) END))/ @currRate AS DECIMAL(16,2))) AS VARCHAR) END AS CostReductionIdling,
	--CASE WHEN RI.IsMonthStart=1 THEN '-' ELSE CAST((CAST((((RI.Idling/3600) - (SELECT ISNULL((SELECT Idling FROM @tblBoxes WHERE BoxId=RI.BoxId),0))))*(@fcPerLtr*@fcsPerHr)/ @currRate AS DECIMAL(8,2))) AS VARCHAR) END AS CostReductionIdling,
	@DefCurrName AS DefaultCurrencyName,@CtCurrName AS ConvertedCurrencyName,
	CASE WHEN @DefCurrName=@CtCurrName THEN '-' ELSE CAST(@currRate AS VARCHAR) +' per '+@CtCurrName END AS CurrencyRate,
	@DistanceCaptionPrefix AS DistancePrefix,@FuelCaptionPrefix AS FuelPrefix,
	CAST((@fcPerLtr / @currRate) AS DECIMAL(16,2)) AS FuelCostPerLtrLV,
	CAST((@fcPerLtrHV / @currRate) AS DECIMAL(16,2)) AS FuelCostPerLtrHV,
	CAST(@distPerLtr * @ConversionFactor AS DECIMAL(16,2)) AS MileageLV,
	CAST(@distPerLtrHV  * @ConversionFactor AS DECIMAL(16,2)) AS MileageHV,
	CAST(@fcsPerHr AS DECIMAL(16,2)) AS FuelConsumedPerHrLV,
	CAST(@fcsPerHrHV AS DECIMAL(16,2)) AS FuelConsumedPerHrHV
	FROM rvlfTripDetails_ROI RI INNER JOIN rvlfBoxId b ON b.BoxId=RI.BoxId  
	INNER JOIN rvlfMsgInHst h ON h.MessageInID=b.MessageInId  
	INNER JOIN @tblBoxes bx ON bx.BoxID=RI.BoxId
	INNER JOIN rvlfVehicleType vt ON vt.VehicleTypeId=bx.VehicleType
	WHERE bx.CostPerKm IS NOT NULL AND DATEPART(MONTH,RI.StartDate) BETWEEN DATEPART(MONTH,@dtFDate) AND DATEPART(MONTH,@dtEDate)   
	) Res INNER JOIN rvlfVehicleAssignment va ON Res.BoxId=va.BoxId
	INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId
	--WHERE CONVERT(DATE,Res.StartDate) BETWEEN CONVERT(DATE,@dtStartDate) AND CONVERT(DATE,@dtEndDate)
	ORDER BY Res.BoxId,Res.StartDate ASC,Res.IsMonthStart DESC
	
SET NOCOUNT OFF  
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_getRoute_TimeDeviation_ORS]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
                                                    
-- =============================================                                                    
-- EXEC rvlf_sp_getRoute_TimeDeviation_ORS 504,'06/10/2012 8:30:00 AM',NULL,19,107,181,'Trip 1',1                    
-- Procedure Name : rvlf_sp_getRoute_TimeDeviation_ORS          
-- Author:  Vijay N                                 
-- Create date: 28-Jul-2012                                
-- Description: To get the Deviation for Time And Distance.        
-- =============================================                                
CREATE PROCEDURE [dbo].[rvlf_sp_getRoute_TimeDeviation_ORS]      
-- Add the parameters for the stored procedure here                                
@intBoxID VARCHAR (MAX)=NULL,              
@dtStartDate DATETIME = NULL,               
@dtEndDate DATETIME = NULL,               
@bigQueryingUser BIGINT=0,               
@bigOrganizationID BIGINT=107,               
@bigFleetID BIGINT=NULL,               
@varTripNo VARCHAR (50)=NULL,               
@varTripType INT=NULL              
AS              
BEGIN              
   -- SET NOCOUNT ON added to prevent extra result sets from                      
-- interfering with SELECT statements.                      
SET NOCOUNT ON;            
---------------------------------------------------------------------        
DECLARE @FleetName NVARCHAR(300) = (SELECT FleetName FROM rvlfFleet WHERE FleetId = @bigFleetID)      
      
      
SET @dtStartDate = DATEADD(DAY,DATEDIFF(DAY,0,@dtStartDate),0);        
SET @dtEndDate = @dtStartDate;        
-----------------Get the users preference details--------------------              
DECLARE @HoursToBeAdded AS INT = 0;              
DECLARE @MinsToBeAdded AS INT = 0;              
DECLARE @Distance AS VARCHAR (20);              
DECLARE @DefaultDateFormat AS INT = 0;              
DECLARE @ConversionFactor AS 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 AS up            
       INNER JOIN            
       rvlfTimeZones AS tz            
       ON up.TimeZoneId = tz.TimeZoneId            
          AND up.UserId = @bigQueryingUser            
       INNER JOIN            
       rvlfUser AS u            
       ON u.UserId = up.UserId;            
            
----------------Get the User language------------------------              
DECLARE @Lang AS VARCHAR (50);            
            
SELECT @Lang = isnull(Lang, 'LanguageEn')            
FROM   rvlfUserPreferences            
WHERE  UserId = @bigQueryingUser;            
            
DECLARE @tblTempRouteDetails AS TABLE (            
    BoxID                BIGINT         ,            
    latitude             DECIMAL (10, 6),            
    longitude            DECIMAL (10, 6),            
    timestamp            DATETIME       ,            
    --datetimereceived     DATETIME       ,            
    --timestampdisp        DATETIME       ,            
    LandMarkId           BIGINT         ,            
    LndID                BIGINT         ,            
    SeqID                INT            ,            
    LandmarkName         NVARCHAR (MAX) ,            
    StreetAddress        NVARCHAR (500) ,            
    ActualStreetAddress  NVARCHAR (500) ,            
    Odometer             BIGINT         ,            
    Route_Name           NVARCHAR (250) ,            
    VehicleName          NVARCHAR (250) ,            
    startdate            DATETIME       ,            
    Enddate              DATETIME       ,            
    ISLandmarkSkipped    NVARCHAR (10)  ,            
    LandCount            INT            ,            
    GeneratedDate        DATETIME       ,            
    Distance    INT            ,            
    DriverName           NVARCHAR (250) ,        
    DriverContact        VARCHAR (13)   ,      
    InterNo              VARCHAR (250)  ,            
PlannedTotalDistance DECIMAL (6, 2) ,            
    ActualTotalDistance  VARCHAR (10)   ,            
    PlannedTotalTime     VARCHAR (10)  ,            
    ActualTotalTime      VARCHAR (100)  ,            
    PlannedPickUpTime    TIME(0)        ,            
    ActualPickUpTime     VARCHAR (100)  ,            
    StudentName          NVARCHAR (250) ,      
    SchoolName          NVARCHAR (250)  ,  
    DeviatedTime        VARCHAR(100)     );            
            
DECLARE @tblTempBoxid AS TABLE (            
    [INDEX] INT    IDENTITY PRIMARY KEY,            
    BOXID   BIGINT);            
            
IF (@intBoxID IS NULL            
    OR @intBoxID = '')            
    BEGIN            
        INSERT INTO @tblTempBoxid            
        SELECT VA.BoxId            
        FROM   rvlfVehicleAssignment AS VA            
               INNER JOIN            
               rvlfVehicle AS V            
               ON V.VehicleId = VA.VehicleId            
               INNER JOIN            
               rvlfFleetVehicles AS FV            
               ON v.VehicleId = FV.VehicleId            
  WHERE  FV.FleetId IN (select ParentChildId from dbo.rvlf_fn_GetParentChild(@bigFleetID)) --= @bigFleetID;            
    END            
ELSE            
    IF @intBoxID IS NOT NULL            
        BEGIN            
            INSERT INTO @tblTempBoxid            
            SELECT *            
            FROM   rvlf_fn_ConvertArrayToTable (@intBoxID, ',');            
        END            
            
DECLARE @Flag AS INT = 1;            
            
--------------------Loop Through to get the details of all multiple vehicles-------------------                    
WHILE @Flag <= (SELECT COUNT([INDEX])            
                FROM   @tblTempBoxid)            
    BEGIN            
        DECLARE @BOXIDS AS INT;            
        SELECT @BOXIDS = BOXID            
        FROM   @tblTempBoxid            
        WHERE  [INDEX] = @Flag;            
        DECLARE @ResourceId AS VARCHAR (100);            
        DECLARE @DriverContact AS VARCHAR (13);            
              
        SET @ResourceId = (SELECT RRM.ORS_Resource_ID      
                           FROM   RvlfRouteResourceMapping AS RRM            
                                  INNER JOIN            
                                  rvlfVehicle AS V            
                                  ON RRM.Vehicle_Internal_Number = V.InternalNo            
                                  INNER JOIN            
                                  rvlfVehicleAssignment AS VA            
                                  ON VA.VehicleId = V.VehicleId            
                           WHERE  VA.BoxId IN (@BOXIDS))      
       SET @DriverContact =  (SELECT RRM.Driver_Mobile_Number      
                           FROM   RvlfRouteResourceMapping AS RRM            
                                  INNER JOIN            
                                  rvlfVehicle AS V            
                                  ON RRM.Vehicle_Internal_Number = V.InternalNo            
                                  INNER JOIN            
                                  rvlfVehicleAssignment AS VA            
                                  ON VA.VehicleId = V.VehicleId            
                           WHERE  VA.BoxId IN (@BOXIDS))      
        IF (@REsourceId IS NOT NULL            
            OR @ResourceId <> '')            
            BEGIN            
                DECLARE @DistanceCovered AS BIGINT;                            
                DECLARE @ActualTotalTime AS TIME;            
                ----------------------------------------------------------------------------------------------        
                DECLARE @DriverName AS NVARCHAR (MAX);            
                DECLARE @VehInterNo AS VARCHAR (250);            
                DECLARE @SchoolName AS NVARCHAR (MAX);            
                      
                       
                SELECT @VehInterNo = InternalNo            
                FROM   rvlfVehicleAssignment AS VA            
                       INNER JOIN            
                       rvlfVehicle AS V            
                       ON V.VehicleId = VA.VehicleId            
                WHERE  BoxId = @BOXIDS;            
                -------------------------------------Get the trip start and end time------------------------------------                        
                        
            SET @dtStartDate = DATEADD(DAY,DATEDIFF(DAY,0,@dtStartDate),0);        
    SET @dtEndDate = @dtStartDate;            
            
                SELECT @dtStartDate = DATEADD(MINUTE,CAST(RIGHT(STARTS_FRM_STATION,2) AS INT) - 5,DATEADD(HOUR,CAST(LEFT(STARTS_FRM_STATION,CASE WHEN LEFT(STARTS_FRM_STATION,2) LIKE '%.'THEN 1 ELSE 2 END)AS INT),@dtStartDate)),        
        @dtEndDate = DATEADD(MINUTE,CAST(RIGHT(SCOOL_ARRIVAL_TIME,2) AS INT) + 5,DATEADD(HOUR,CAST(LEFT(SCOOL_ARRIVAL_TIME,CASE WHEN LEFT(SCOOL_ARRIVAL_TIME,2) LIKE '%.'THEN 1 ELSE 2 END)AS INT),@dtEndDate))                               
                FROM   rvlfORSRouteMaster            
                WHERE  VEH_INT_NO = @VehInterNo            
                       AND Trip_No = @varTripNo;            
                           
                SET @dtStartDate = DATEADD(HOUR,-4,@dtStartDate);    
                SET @dtEndDate = DATEADD(HOUR,-4,@dtEndDate);      
                               
                    
                --select @dtStartDate,@dtEndDate,@VehInterNo        
                -------------------------------------------------------------------------------------------------------        
                SELECT @DriverName = (CASE WHEN @Lang = 'LanguageArNew' THEN isnull(DriverName_Ar, DriverName_En) ELSE DriverName_En END),            
                       @SchoolName = (CASE WHEN @Lang = 'LanguageArNew' THEN isnull(SchoolName_Ar, SchoolName_En) ELSE SchoolName_En END)                                                      
                FROM   rvlfORSRouteMaster            
                WHERE  VEH_INT_NO = @VehInterNo            
                       AND Trip_No = @varTripNo;            
                                          
                --------------------------Total Distance covered by the Vehicle--------------------------------                    
                DECLARE @StartIgnion DATETIME;    
                SET @StartIgnion = (SELECT TOP 1 Origindatetime FROM rvlfMsgInHst AS M            
                       --INNER JOIN            
                       --rvlfVehicleAssignment AS VA            
                       --ON VA.BoxId = m.BoxId            
                       --INNER JOIN            
                       --rvlfVehicle AS V            
                       --ON V.VehicleId = VA.VehicleId            
                WHERE  m.BoxId IN (@BOXIDS)            
                       --AND DATEADD(HOUR, (@HoursToBeAdded * 1), DATEADD(MINUTE, (@MinsToBeAdded * 1), OriginDateTime)) BETWEEN @dtStartDate AND @dtEndDate      
                       AND  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate      
                       AND M.BoxMsgInTypeId = 2 ORDER BY origindatetime ASC)     
    
    IF(@StartIgnion IS NULL)    
    BEGIN     
     SET @StartIgnion = (SELECT TOP 1 OriginDateTime FROM rvlfMsgInHst AS M WHERE BoxId IN(@BOXIDS)    
     AND OriginDateTime BETWEEN    
     DATEADD(MINUTE,-20,@dtStartDate ) AND @dtStartDate     
     AND M.BoxMsgInTypeId = 2 ORDER BY OriginDateTime DESC    
     )    
    END    
    
                SELECT @DistanceCovered = MAX(m.odometer) - MIN(m.odometer),            
                       --@ActualTotalTime = MAX(origindatetime) - Min(origindatetime)     
                       @ActualTotalTime = MAX(origindatetime) - @StartIgnion    
                FROM   rvlfmsginhst AS M            
                       INNER JOIN            
                       rvlfVehicleAssignment AS VA            
                       ON VA.BoxId = m.BoxId            
                       INNER JOIN            
                       rvlfVehicle AS V            
                       ON V.VehicleId = VA.VehicleId            
                WHERE  m.BoxId IN (@BOXIDS)            
                    --AND DATEADD(HOUR, (@HoursToBeAdded * 1), DATEADD(MINUTE, (@MinsToBeAdded * 1), OriginDateTime)) BETWEEN @dtStartDate AND @dtEndDate      
                       AND  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate      
                       AND Odometer <> 0;            
                ----------------Total Distance and Time of the Trip---------------------------                    
                DECLARE @TotalTime AS VARCHAR(10)            
                DECLARE @TotalDistance AS DECIMAL (6, 3) = NULL;            
                DECLARE @SchoolNo AS VARCHAR (50) = NULL;        
                                        
                SELECT @TotalDistance = (CASE @varTripNo             
WHEN 'Trip 1' THEN ISNULL(ORM.Distance_Bw_station_first_pickup, 0) + ISNULL(ORM.Distance_Bw_First_Last_PickUp, 0) + ISNULL(ORM.Distance_Bw_Last_pickUp_School, 0)             
WHEN 'Trip 2' THEN +ISNULL(ORM.Distance_Bw_First_Last_PickUp, 0) + ISNULL(ORM.Distance_Bw_Last_pickUp_School, 0) + (SELECT ISNULL(Distance_Return_From_FirstSchool_Or_First_Second_School, 0)            
FROM rvlfORSRouteMaster AS ORM           
WHERE  VEH_INT_NO = @VehInterNo  AND Trip_No = 'Trip 1')          
WHEN 'Trip 3' THEN +ISNULL(ORM.Distance_Bw_First_Last_PickUp, 0) + ISNULL(ORM.Distance_Bw_Last_pickUp_School, 0) + (SELECT ISNULL(Distance_Return_From_FirstSchool_Or_First_Second_School, 0)           
FROM rvlfORSRouteMaster AS ORM WHERE  VEH_INT_NO = @VehInterNo AND Trip_No = 'Trip 2')END),            
                       @TotalTime = REPLACE((CASE @varTripNo             
WHEN 'Trip 1' THEN (ISNULL(SCOOL_ARRIVAL_TIME, 0) - ISNULL(STARTS_FRM_STATION, 0))             
WHEN 'Trip 2' THEN ISNULL(SCOOL_ARRIVAL_TIME, 0) - (SELECT ISNULL(SCHOOL_LEAVING_TIME_SecondTrip, 0)            
FROM rvlfORSRouteMaster AS ORM WHERE VEH_INT_NO = @VehInterNo AND Trip_No = 'Trip 1')           
WHEN 'Trip 3' THEN ISNULL(SCOOL_ARRIVAL_TIME, 0) - (SELECT ISNULL(SCHOOL_LEAVING_TIME_SecondTrip, 0)           
FROM   rvlfORSRouteMaster AS ORM WHERE VEH_INT_NO = @VehInterNo AND Trip_No = 'Trip 2')END),'.',':'),            
@SchoolNo = SchoolCode  FROM   rvlfORSRouteMaster AS ORM WHERE  VEH_INT_NO = @VehInterNo AND Trip_No = @varTripNo;            
                --------------------------------------------------------------------------------                    
                --------------Insert the Route value in the temp table to get the Route sequence-----------------                    
                  
                CREATE TABLE #tblTempORS   
(  
 ORS_DriverId VARCHAR(120),  
 [TYPE] INT,  
[Depot] VARCHAR(24),  
landmark_Id INT,  
Latitude DECIMAL(11,6),  
Longitude DECIMAL(11,6),   
Start_Time TIME(7),  
"INDEX" INT IDENTITY PRIMARY KEY  
)  
  
  
                INSERT INTO #tblTempORS              
    SELECT  ORS.ORS_DriverId,"Type",Depot,ORS.Landmark_ID,ORS.Latitude,ORS.Longitude,ORS.Start_Time  
                FROM     rvlf_ORSJobDetails AS ORS            
                         INNER JOIN            
                         RvlfRouteResourceMapping AS RRM            
                         ON ORS.ORS_DriverId = RRM.ORS_Resource_ID            
                WHERE    "Status" <> 1    
                         AND ORS.ORS_DriverId = @ResourceId            
                         AND Depot = @SchoolNo            
                         AND Type = @varTripType            
                ORDER BY ORS.Start_Time;           
                  
                  
       --SELECT   *,            
                --         row_number() OVER ( ORDER BY Start_Time) AS "INDEX"            
                --INTO     #tblTempORS            
                --FROM     rvlf_ORSJobDetails AS ORS            
                --         INNER JOIN            
                --         RvlfRouteResourceMapping AS RRM            
                --         ON ORS.ORS_DriverId = RRM.ORS_Resource_ID            
                --WHERE    "Status" <> 1    
                --         AND ORS.ORS_DriverId = @ResourceId            
                --         AND Depot = @SchoolNo            
                --         AND Type = @varTripType            
                --ORDER BY ORS.Start_Time;           
                   
                --SELECT *,row_number()OVER(ORDER BY Start_Time) AS "INDEX"                   
                --FROM rvlf_ORSJobDetails ORS INNER JOIN RvlfRouteResourceMapping RRM ON ORS.ORS_DriverId = RRM.ORS_Resource_ID                        
                --WHERE "Status" <> 1 AND ORS.ORS_DriverId = @ResourceId  AND Depot = @SchoolNo AND Type = @varTripType                    
                --ORDER BY ORS.Start_Time                   
                -------------------------------------------------------------------------------------------------                    
                -------------------------Calculation of Route / Time Deviation-----------------------------------                    
                INSERT INTO @tblTempRouteDetails            
                SELECT   *            
                FROM     (SELECT DISTINCT RD.deviceid,            
                    RD.latitude,            
                                          RD.longitude,            
                                          RD.[timestamp],            
                                          --RD.datetimereceived,            
                                          --RD.timestampdisp,            
                                          RD.LandMarkId,            
                                          L.LandmarkID AS LndId,            
                                          OJD.[INDEX] AS SeqID,            
                                          (CASE WHEN @Lang = 'LanguageArNew' THEN isnull(L.LandmarkName_Ar, L.LandmarkName) ELSE L.LandmarkName END),                                          
                                          (CASE WHEN @Lang = 'LanguageArNew' THEN isnull(L.StreetAddress_Ar, L.StreetAddress) ELSE L.StreetAddress END),
										  --L.LandmarkName,            
										  --L.StreetAddress,            
                                          RD.StreetAddress AS ActualStreetAddress,            
                                          RD.odometer AS Odometer,            
                                          ISNULL(@SchoolName, '') + ' - ' + ISNULL(@varTripNo, '') AS Route_Name,            
                                          (SELECT VehicleDescription            
                                           FROM   rvlfVehicle AS V            
                                                  INNER JOIN            
                               rvlfVehicleAssignment AS VA            
                                                  ON V.VehicleId = VA.VehicleId            
                                           WHERE  BoxId IN (@BOXIDS)) AS VehicleName,            
                                          @dtStartDate AS startdate,            
                                          @dtEndDate AS Enddate,            
                                          (CASE             
WHEN RD.LandMarkId IS NULL THEN 'YES' ELSE 'NO'             
END) AS ISLandmarkSkipped,            
                                          (CASE             
WHEN RD.LandMarkId IS NULL THEN 1 ELSE 0             
END) AS LandCount,            
                                          DATEADD(HOUR, (@HoursToBeAdded * 1), DATEADD(MINUTE, (@MinsToBeAdded * 1), GETUTCDATE())) AS GeneratedDate,            
                                          ISNULL(@DistanceCovered, ' - ') AS Distance,            
                                          ISNULL(@DriverName, ' - ') AS DriverName,        
                                          ISNULL(@DriverContact,' - ') AS DriverContact,      
     @VehInterNo AS InternalNo,            
                                          (@TotalDistance * @ConversionFactor) AS TotalDistance,            
                                          ISNULL(CAST ((@DistanceCovered * @ConversionFactor) AS VARCHAR (10)), '-') AS ActualDistance,            
                                          CAST(CAST((RIGHT(@TotalTime,2)/60) AS VARCHAR(2)) +':'+  CAST((RIGHT(@TotalTime,2)%60) AS VARCHAR(2)) AS TIME(0)) AS PlannedTotalTime,            
                                          ISNULL(CAST(CAST(@ActualTotalTime AS TIME(0)) AS VARCHAR(100)),'-') AS ActualTotalTime,            
                                          CAST(DATEADD(HOUR,-4,DATEADD(HOUR, (@HoursToBeAdded * 1), DATEADD(MINUTE, (@MinsToBeAdded * 1), OJD.Start_Time))) AS TIME(0)) AS PlannedPickUpTime,            
                                          --CAST(OJD.Start_Time AS TIME(0)) AS PlannedPickUpTime,                                                      
                                          ISNULL(CAST (CAST (      
                                          DATEADD(HOUR, (@HoursToBeAdded * 1), DATEADD(MINUTE, (@MinsToBeAdded * 1), "timestamp"))      
                                          AS TIME(0)) AS VARCHAR (100)), '-') AS ActualPickUpTime,            
                                          (SELECT (ISNULL(StudentFirstName, '') + ' ' + ISNULL(StudentMiddleName, '') + ' ' + ISNULL(StudentLastName, '')) + ','            
                                           FROM   rvlfstudentMaster AS SM            
                                           WHERE  SM.BusInternalNo = @VehInterNo            
                                                  AND SM.latitude = CAST (l.Latitude AS VARCHAR (10))            
                                                  AND SM.longitude = CAST (l.longitude AS VARCHAR (10))            
                                                  AND Active = 1            
                                           FOR    XML PATH ('')) AS StudentNames ,@SchoolName AS SchoolName,  
                                           CASE WHEN  OJD.Start_Time < CAST("timestamp" AS TIME(0)) THEN   
                                            CAST(DATEDIFF(MINUTE,OJD.Start_Time,CAST("timestamp" AS TIME(0)))AS VARCHAR(20))  
                                            WHEN OJD.Start_Time > CAST("timestamp" AS TIME(0)) THEN   
                                           '-'+CAST(DATEDIFF(MINUTE,CAST("timestamp" AS TIME(0)),OJD.Start_Time) AS VARCHAR(20))  
                                           ELSE '-' END  AS DeviatedTime  
                                           --CAST(DATEDIFF(MINUTE,OJD.Start_Time,CAST("timestamp" AS TIME(0))) AS VARCHAR(20)) AS DeviatedTime  
                                           --CAST(OJD.Start_Time AS VARCHAR(20)) +'-'+ CAST (CAST("timestamp" AS TIME(0)) AS Varchar(20)) AS DeviatedTime  
                          FROM   [dbo].[rvlf_fn_GetRouteDetails] (@BOXIDS, @dtStartDate, @dtEndDate, @bigQueryingUser, 'T') AS RD            
                                 INNER JOIN            
                                 rvlfVehicle AS V            
                                 ON V.VehicleId = RD.VehicleId            
                                 INNER JOIN            
                                 RvlfRouteResourceMapping AS RRM            
                                 ON RRM.Vehicle_Internal_Number = V.InternalNo            
                                 RIGHT OUTER JOIN            
                                 #tblTempORS AS OJD            
                                 ON OJD.ORS_DriverId = RRM.ORS_Resource_ID            
                                    AND [TYPE] = @varTripType            
                                    AND [Depot] = @SchoolNo            
                                    AND OJD.landmark_Id = RD.LandMarkId            
                                 INNER JOIN            
                                 rvlfLandmark AS L            
                                ON L.Latitude = OJD.Latitude            
                                    AND L.Longitude = OJD.Longitude            
                          WHERE  OJD.ORS_DriverId = @ResourceId) AS TBL            
                ORDER BY SeqID ASC;            
                DROP TABLE #tblTempORS;            
            END            
        SET @Flag = @Flag + 1;            
    END            
            
----------------------------------Select The Deviation details----------------------------------------              
SELECT *,SUBSTRING(StudentName, 0, LEN(StudentName)) AS LandMarkStudentNames,      
@FleetName AS FleetName, @varTripNo AS TripNo,      
CASE @varTripType WHEN '1' THEN 'Collect' ELSE 'Drop' END AS TripType,      
CAST (CAST(@dtStartDate AS DATE) AS VARCHAR(10))AS "DATE"       
FROM   @tblTempRouteDetails;            
            
SET NOCOUNT OFF;            
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_getRouteDeviation]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================          
-- 7/6/2012 8:00:00 PM}          
-- EXEC rvlf_sp_getRouteDeviation NULL,'5/28/2012 8:30:00 AM','5/28/2012 9:00:00 AM',409,107,181           
-- Author:  Vijay N           
-- Create date: 6-Jul-2012          
-- Description: To get the Deviation for Landmark.          
-- =============================================          
CREATE PROCEDURE [dbo].[rvlf_sp_getRouteDeviation]          
 -- Add the parameters for the stored procedure here          
@intBoxID varchar(MAX) = NULL,          
@dtStartDate as datetime,                
@dtEndDate datetime,                
@bigQueryingUser bigint = 0,          
@bigOrganizationID BIGINT = 107,          
@bigFleetID BIGINT= NULL          
          
--,@RouteId INT          
AS          
BEGIN          
 -- SET NOCOUNT ON added to prevent extra result sets from          
 -- interfering with SELECT statements.          
 SET NOCOUNT ON;          
        
          
DECLARE @HoursToBeAdded INT = 0                
DECLARE @MinsToBeAdded INT = 0                
DECLARE @Distance varchar(20)                 
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                
          
  DECLARE @tblTempRouteDetails AS TABLE        
  (        
 BoxID BIGINT,         
 latitude DECIMAL(10,6),        
 longitude DECIMAL(10,6),        
 timestamp DATETIME,        
 --datetimereceived DATETIME,        
 --timestampdisp DATETIME,        
 LandMarkId BIGINT,           
 LndID BIGINT,        
 SeqID INT,        
 LandmarkName NVARCHAR(MAX),        
 StreetAddress NVARCHAR(500),        
 ActualStreetAddress NVARCHAR(500),        
 Odometer BIGINT,          
 Route_Name NVARCHAR(250),        
 Route_Description NVARCHAR(250),        
 VehicleName NVARCHAR(250),        
 startdate DATETIME,        
 Enddate DATETIME,        
 ISLandmarkSkipped NVARCHAR(10),        
 LandCount INT,        
 GeneratedDate DATETIME,        
 Distance INT,        
 DriverName NVARCHAR(250),  
 StudentName NVARCHAR(MAX),  
 NoOfSkippedStud INT  
  )        
          
          
  DECLARE @tblTempBoxid AS TABLE         
  (        
 [INDEX] INT  IDENTITY PRIMARY KEY,         
 BOXID BIGINT          
  )        
          
  --SELECT ISNULL(@intBoxID,'NUll')        
          
  IF(@intBoxID IS NULL OR @intBoxID = '')        
  BEGIN        
 INSERT INTO @tblTempBoxid         
 SELECT VA.BoxId FROM rvlfVehicleAssignment VA        
 INNER JOIN rvlfVehicle V ON V.VehicleId = VA.VehicleId        
 INNER JOIN rvlfFleetVehicles FV ON v.VehicleId =  FV.VehicleId        
 WHERE FV.FleetId = @bigFleetID          
  END        
  ELSE IF @intBoxID IS NOT NULL         
  BEGIN        
   INSERT INTO @tblTempBoxid         
   SELECT * FROM rvlf_fn_ConvertArrayToTable(@intBoxID,',')          
  END        
          
  DECLARE @Flag INT = 1         
          
          
  WHILE @Flag <= (SELECT COUNT([INDEX]) FROM @tblTempBoxid)        
  BEGIN        
          
  DECLARE @BOXIDS INT         
          
  SELECT @BOXIDS = BOXID FROM @tblTempBoxid WHERE [INDEX] = @Flag        
          
          
 DECLARE @RouteId INT           
 SET @RouteId  = (SELECT DISTINCT TOP 1 RouteId FROM rvlfVehicleAssignment VA INNER JOIN rvlfVehicle V ON V.VehicleId = VA.VehicleId           
 INNER JOIN rvlfRouteVehicleAssignment RVA ON RVA.VehicleId = VA.VehicleId WHERE VA.BoxId IN (@BOXIDS)          
 )          
        
  IF(@RouteId IS NOT NULL OR @RouteId <> '')      
BEGIN      
        
DECLARE @DistanceCovered BIGINT         
         
SELECT @DistanceCovered = MAX(m.odometer) - MIN(m.odometer)        
FROM rvlfmsginhst M            
INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId = m.BoxId            
INNER JOIN rvlfVehicle V ON V.VehicleId = VA.VehicleId            
WHERE m.BoxId IN(@BOXIDS) AND             
DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),OriginDateTime))           
BETWEEN @dtStartDate AND  @dtEndDate        
        
DECLARE @DriverName AS NVARCHAR(MAX)        
        
SELECT @DriverName = DriverName FROM rvlfDriverAssignment DA         
INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId = DA.BoxId  INNER JOIN rvlfVehicle V ON V.VehicleId = VA.VehicleId         
INNER JOIN rvlfDriverMaster DM ON DM.DriverId = DA.DriverId        
WHERE DA.BoxId IN (@BOXIDS)        
        
DECLARE @VehInterNo VARCHAR(250)
SELECT @VehInterNo = InternalNo FROM rvlfVehicleAssignment VA INNER JOIN rvlfVehicle V ON V.VehicleId = VA.VehicleId
WHERE BoxId = @BOXIDS
        
--Insert statements for procedure here          
        
INSERT INTO @tblTempRouteDetails        
SELECT * FROM (          
SELECT DISTINCT         
RD.deviceid,        
RD.latitude,        
RD.longitude,        
RD.[timestamp],        
--RD.datetimereceived,          
--RD.timestampdisp,        
RD.LandMarkId,           
R.LndID,        
R.SeqID,        
L.LandmarkName,        
L.StreetAddress,        
RD.StreetAddress AS ActualStreetAddress,        
RD.odometer AS Odometer,          
(SELECT RM.RouteName FROM rvlfRouteMaster RM WHERE RM.RouteID = @RouteId) AS Route_Name,          
(SELECT RM.RouteDescription FROM rvlfRouteMaster RM WHERE RM.RouteID = @RouteId) AS Route_Description,          
(SELECT VehicleDescription FROM rvlfVehicle V           
INNER JOIN rvlfVehicleAssignment VA ON V.VehicleId = VA.VehicleId WHERE BoxId IN(@BOXIDS)) AS VehicleName,          
@dtStartDate AS startdate,         
@dtEndDate AS Enddate,         
(CASE WHEN RD.LandMarkId IS NULL THEN 'YES' ELSE 'NO' END) AS ISLandmarkSkipped,          
(CASE WHEN RD.LandMarkId IS NULL THEN 1 ELSE 0 END) AS LandCount,          
DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),GETUTCDATE()))  AS GeneratedDate,        
ISNULL(@DistanceCovered,' - ') AS Distance,         
ISNULL(@DriverName,' - ') AS DriverName,    
  
(SELECT (ISNULL(StudentFirstName,' ') + ' ' +ISNULL(StudentMiddleName,' ')+ ' ' + ISNULL(StudentLastName,' ')) +','  
FROM rvlfstudentMaster SM WHERE
SM.BusInternalNo = @VehInterNo AND  
l.latitude = CAST(l.Latitude AS VARCHAR(10))  
AND l.longitude = CAST(l.longitude AS VARCHAR(10))
AND Active = 1
 FOR XML PATH(''))  AS StudentNames,  

  
(SELECT COUNT(ISNULL(StudentFirstName,''))  
FROM rvlfstudentMaster SM WHERE   
SM.BusInternalNo = @VehInterNo AND
l.latitude = CAST(l.Latitude AS VARCHAR(10))  
AND l.longitude = CAST(l.longitude AS VARCHAR(10))
AND Active = 1
 ) AS NoOfSkippedStud  
           
 FROM [dbo].[rvlf_fn_GetRouteDetails](@BOXIDS,@dtStartDate,@dtEndDate,@bigQueryingUser,'L') RD           
 INNER JOIN rvlfRouteVehicleAssignment VA ON VA.VehicleId = RD.vehicleId           
 INNER JOIN rvlfRouteMaster RM ON RM.RouteID = VA.RouteId          
 RIGHT OUTER JOIN rvlfRouteDetails R ON R.RouteID = RM.RouteID AND R.LndID = RD.LandMarkId          
 INNER JOIN rvlfLandmark L ON L.LandmarkID = R.LndID
 
 --RIGHT OUTER JOIN rvlfDriverAssignment DA ON DA.BoxId = RD.deviceid        
 --RIGHT OUTER JOIN rvlfDriverMaster DM ON DM.DriverId = DA.DriverId        
 WHERE R.RouteID = @RouteId ) AS TBL ORDER BY SeqID ASC          
         
 END         
  SET @Flag = @Flag + 1           
  END         
          
  SELECT *,SUBSTRING(StudentName,0,LEN(StudentName))AS StudentNames  
  --,  
  --CASE WHEN LandCount = 0 THEN (SELECT COUNT(*) FROM rvlfStudentMaster SM WHERE SM.Latitude = CAST(TR.latitude AS VARCHAR(10)) AND SM.Longitude = CAST(TR.longitude AS VARCHAR(250)) AND SM.BusInternalNo =   
  --(SELECT V.InternalNo FROM rvlfVehicleAssignment VA INNER JOIN rvlfVehicle V ON VA.VehicleId = V.VehicleId  
  --WHERE VA.BoxId = TR.BoxID))   
  --ELSE 0 END AS NoOfSkippedStud  
  FROM @tblTempRouteDetails AS TR       
           
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_getRouteDeviation_ORS]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================                              
-- EXEC rvlf_sp_getRouteDeviation_ORS 589,'5/28/2012 8:30:00 AM','5/28/2012 9:00:00 AM',19,107,181,'Trip 1',1    
-- Author:  Vijay N                               
-- Create date: 6-Jul-2012                              
-- Description: To get the Deviation for Landmark.                              
-- =============================================                              
CREATE PROCEDURE [dbo].[rvlf_sp_getRouteDeviation_ORS]                      
 -- Add the parameters for the stored procedure here                              
@intBoxID varchar(MAX) = NULL,                              
@dtStartDate as datetime = NULL,                    
@dtEndDate datetime= NULL,        
@bigQueryingUser bigint = 0,                              
@bigOrganizationID BIGINT = 107,                              
@bigFleetID BIGINT= NULL,                
@varTripNo Varchar(50) = NULL,              
@varTripType INT = NULL,    
@IsSkipped INT = NULL    
AS                              
BEGIN                              
 -- SET NOCOUNT ON added to prevent extra result sets from                              
-- interfering with SELECT statements.                              
SET NOCOUNT ON;              
---------------------------------------------------------------------        
DECLARE @Lang AS VARCHAR (50);              
              
SELECT @Lang = isnull(Lang, 'LanguageEn')              
FROM   rvlfUserPreferences              
WHERE  UserId = @bigQueryingUser;        
      
DECLARE @FleetName NVARCHAR(300) = (SELECT FleetName FROM rvlfFleet WHERE FleetId = @bigFleetID)        
DECLARE @GeneratedBy NVARCHAR(200)= (SELECT UserName FROM rvlfuser WHERE userID = @bigQueryingUser)          
        
SET @dtStartDate = DATEADD(DAY,DATEDIFF(DAY,0,@dtStartDate),0);          
SET @dtEndDate = @dtStartDate;          
-----------------Get the users preference details--------------------              
DECLARE @HoursToBeAdded AS INT = 0;              
DECLARE @MinsToBeAdded AS INT = 0;              
DECLARE @Distance AS VARCHAR (20);              
DECLARE @DefaultDateFormat AS INT = 0;              
DECLARE @ConversionFactor AS 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 AS up              
       INNER JOIN              
       rvlfTimeZones AS tz              
       ON up.TimeZoneId = tz.TimeZoneId              
          AND up.UserId = @bigQueryingUser              
       INNER JOIN              
       rvlfUser AS u              
       ON u.UserId = up.UserId;    
----------------Get the User language------------------------              
            
              
DECLARE @tblTempRouteDetails AS TABLE (              
    BoxID               BIGINT         ,              
    LandMarkId          BIGINT         ,              
    LndID               BIGINT         ,              
    SeqID               INT            ,              
    LandmarkName        NVARCHAR (MAX) ,              
    StreetAddress       NVARCHAR (500) ,              
    ActualStreetAddress NVARCHAR (500) ,              
    Route_Name          NVARCHAR (250) ,              
    VehicleName         NVARCHAR (250) ,              
    startdate           DATETIME       ,              
    Enddate             DATETIME       ,              
    ISLandmarkSkipped   NVARCHAR (10)  ,              
    LandCount           INT            ,              
    GeneratedDate       VARCHAR(200)   ,              
    Distance            INT            ,              
    DriverName          NVARCHAR (250) ,           
    DriverContact        VARCHAR (13)  ,           
    StudentName         NVARCHAR (MAX) ,              
    NoOfSkippedStud     INT            ,        
  SchoolName          NVARCHAR (250) );              
              
DECLARE @tblTempBoxid AS TABLE (              
    [INDEX] INT    IDENTITY PRIMARY KEY,              
    BOXID   BIGINT);              
              
IF (@intBoxID IS NULL              
    OR @intBoxID = '')              
    BEGIN              
        INSERT INTO @tblTempBoxid              
        SELECT VA.BoxId              
        FROM   rvlfVehicleAssignment AS VA              
               INNER JOIN              
               rvlfVehicle AS V              
               ON V.VehicleId = VA.VehicleId            
               INNER JOIN              
               rvlfFleetVehicles AS FV              
               ON v.VehicleId = FV.VehicleId              
        WHERE  V.OrganizationId = @bigOrganizationID AND FV.FleetId IN (select ParentChildId from dbo.rvlf_fn_GetParentChild(@bigFleetID))--= @bigFleetID;              
    END              
ELSE              
    IF @intBoxID IS NOT NULL              
        BEGIN              
            INSERT INTO @tblTempBoxid              
            SELECT *              
            FROM   rvlf_fn_ConvertArrayToTable (@intBoxID, ',');              
        END              
              
DECLARE @Flag AS INT = 1;              
--------------------Loop Through to get the details of all multiple vehicles-------------------  
WHILE @Flag <= (SELECT COUNT([INDEX])              
                FROM   @tblTempBoxid)              
    BEGIN              
        DECLARE @BOXIDS AS INT;              
        SELECT @BOXIDS = BOXID FROM @tblTempBoxid WHERE  [INDEX] = @Flag;              
        DECLARE @ResourceId AS VARCHAR (100);              
        DECLARE @DriverContact AS NVARCHAR (300);        
        SET @ResourceId = (SELECT RRM.ORS_Resource_ID              
                           FROM   RvlfRouteResourceMapping AS RRM              
                                  INNER JOIN              
                                  rvlfVehicle AS V              
                                  ON RRM.Vehicle_Internal_Number = V.InternalNo              
                                  INNER JOIN              
                                  rvlfVehicleAssignment AS VA              
                                  ON VA.VehicleId = V.VehicleId              
                           WHERE  VA.BoxId IN (@BOXIDS));            
          
       SET @DriverContact =  (SELECT RRM.Driver_Mobile_Number        
       FROM   RvlfRouteResourceMapping AS RRM              
              INNER JOIN              
              rvlfVehicle AS V              
              ON RRM.Vehicle_Internal_Number = V.InternalNo              
              INNER JOIN              
              rvlfVehicleAssignment AS VA              
              ON VA.VehicleId = V.VehicleId              
       WHERE  VA.BoxId IN (@BOXIDS))        
----------------------------------------------------------------------------------------------------        
        IF (@ResourceId IS NOT NULL              
            OR @ResourceId <> '')              
            BEGIN              
             DECLARE @DriverName AS NVARCHAR (MAX);              
                DECLARE @VehInterNo AS VARCHAR (250);              
                DECLARE @SchoolName AS NVARCHAR (MAX);              
                                     
                SELECT @VehInterNo = InternalNo              
                FROM   rvlfVehicleAssignment AS VA              
                       INNER JOIN              
                       rvlfVehicle AS V              
                       ON V.VehicleId = VA.VehicleId              
                WHERE  BoxId = @BOXIDS;            
-------------------------------------Get the trip start and end time------------------------------------                                                    
                SET @dtStartDate = DATEADD(DAY,DATEDIFF(DAY,0,@dtStartDate),0);          
    SET @dtEndDate = @dtStartDate;  
              
                SELECT @dtStartDate = DATEADD(MINUTE,CAST(RIGHT(STARTS_FRM_STATION,2) AS INT) - 5,DATEADD(HOUR,CAST(LEFT(STARTS_FRM_STATION,CASE WHEN LEFT(STARTS_FRM_STATION,2) LIKE '%.'THEN 1 ELSE 2 END)AS INT),@dtStartDate)),          
    @dtEndDate = DATEADD(MINUTE,CAST(RIGHT(SCOOL_ARRIVAL_TIME,2) AS INT) + 5,DATEADD(HOUR,CAST(LEFT(SCOOL_ARRIVAL_TIME,CASE WHEN LEFT(SCOOL_ARRIVAL_TIME,2) LIKE '%.'THEN 1 ELSE 2 END)AS INT),@dtEndDate))                                 
                FROM   rvlfORSRouteMaster              
                WHERE  VEH_INT_NO = @VehInterNo  
                       AND Trip_No = @varTripNo;  
                         
                SET @dtStartDate = DATEADD(HOUR,-4,@dtStartDate);  
                SET @dtEndDate = DATEADD(HOUR,-4,@dtEndDate);                  
                  
                --SELECT @dtStartDate,@dtEndDate                  
                --SET @dtStartDate = '2012-05-28 02:35:00.000'  
                --SET @dtEndDate = '2012-05-28 03:30:00.000'  
                --SELECT @dtStartDate,@dtEndDate                  
                  
------------------------------------------------------------------------------------------------------        
                DECLARE @DistanceCovered AS BIGINT;              
                SELECT @DistanceCovered = MAX(m.odometer) - MIN(m.odometer)              
                FROM   rvlfmsginhst AS M              
                       INNER JOIN              
                       rvlfVehicleAssignment AS VA              
                       ON VA.BoxId = m.BoxId              
                       INNER JOIN              
                       rvlfVehicle AS V              
                       ON V.VehicleId = VA.VehicleId              
                WHERE  m.BoxId IN (@BOXIDS)              
                       AND DATEADD(HOUR, (@HoursToBeAdded * 1), DATEADD(MINUTE, (@MinsToBeAdded * 1), OriginDateTime)) BETWEEN @dtStartDate AND @dtEndDate        
                       AND Odometer <> 0;              
                                     
--------------------------------------------------------------------------------------------------------------------        
                              
SELECT @DriverName = (CASE WHEN @Lang = 'LanguageArNew' THEN isnull(DriverName_Ar, DriverName_En) ELSE DriverName_En END),              
@SchoolName = (CASE WHEN @Lang = 'LanguageArNew' THEN isnull(SchoolName_Ar, SchoolName_En) ELSE SchoolName_En END)              
FROM   rvlfORSRouteMaster              
WHERE  VEH_INT_NO = @VehInterNo              
AND Trip_No = @varTripNo;              
DECLARE @SchoolNo AS VARCHAR (50) = NULL;              
-------------------------------------Total School Number--------------------------------------                  
                SELECT @SchoolNo = SchoolCode              
                FROM   rvlfORSRouteMaster AS ORM              
                WHERE  VEH_INT_NO = @VehInterNo              
                       AND Trip_No = @varTripNo;              
------------------------------------------------------------------------------------------------              
--------------Insert the Route value in the temp table to get the Route sequence-----------------                    
  
CREATE TABLE #tblTempORS   
(  
 ORS_DriverId VARCHAR(120),  
 [TYPE] INT,  
[Depot] VARCHAR(24),  
landmark_Id INT,  
Latitude DECIMAL(11,6),  
Longitude DECIMAL(11,6),   
"INDEX" INT IDENTITY PRIMARY KEY  
)  
  
INSERT INTO #tblTempORS              
 SELECT  ORS.ORS_DriverId,"Type",Depot,ORS.Landmark_ID,ORS.Latitude,ORS.Longitude  
 --row_number() OVER ( ORDER BY Start_Time) AS "INDEX"                              
                FROM     rvlf_ORSJobDetails AS ORS              
                         INNER JOIN              
                         RvlfRouteResourceMapping AS RRM              
                   ON ORS.ORS_DriverId = RRM.ORS_Resource_ID              
                WHERE    "Status" <> 1              
                         AND ORS.ORS_DriverId = @ResourceId              
                         AND Depot = @SchoolNo              
         AND Type = @varTripType              
                ORDER BY ORS.Start_Time;      
  
  
         --       SELECT  ORS.*,              
         --                row_number() OVER ( ORDER BY Start_Time) AS "INDEX"              
         --       INTO     #tblTempORS              
         --       FROM     rvlf_ORSJobDetails AS ORS              
         --                INNER JOIN              
         --                RvlfRouteResourceMapping AS RRM              
         --                ON ORS.ORS_DriverId = RRM.ORS_Resource_ID              
         --       WHERE    "Status" <> 1              
         --                AND ORS.ORS_DriverId = @ResourceId              
         --                AND Depot = @SchoolNo              
         --AND Type = @varTripType              
         --       ORDER BY ORS.Start_Time;              
---------------------------------------Insert the Deviation details-----------------------------------------              
                INSERT INTO @tblTempRouteDetails              
                SELECT   *              
                FROM     (SELECT DISTINCT RD.deviceid,                                                               
            RD.LandMarkId,              
                                          L.LandmarkID AS LndId,              
                                          OJD.[INDEX] AS SeqID,        
                                          (CASE WHEN @Lang = 'LanguageArNew' THEN isnull(L.LandmarkName_Ar, L.LandmarkName) ELSE L.LandmarkName END),                                          
                                          (CASE WHEN @Lang = 'LanguageArNew' THEN isnull(L.StreetAddress_Ar, L.StreetAddress) ELSE L.StreetAddress END),                                          
                                          RD.StreetAddress AS ActualStreetAddress,
                                          ISNULL(@SchoolName, '') + ' - ' + ISNULL(@varTripNo, '') AS Route_Name,              
                                          (SELECT VehicleDescription              
                                           FROM   rvlfVehicle AS V              
                                                  INNER JOIN              
                                                  rvlfVehicleAssignment AS VA              
                                                  ON V.VehicleId = VA.VehicleId              
                                           WHERE  BoxId IN (@BOXIDS)) AS VehicleName,              
                                          @dtStartDate AS startdate,              
                                          @dtEndDate AS Enddate,              
                                          (CASE               
WHEN RD.LandMarkId IS NULL THEN 'YES' ELSE 'NO'               
END) AS ISLandmarkSkipped,              
                                          (CASE               
WHEN RD.LandMarkId IS NULL THEN 1 ELSE 0               
END) AS LandCount,              
                                          (@GeneratedBy + ' - '+       
                                          CAST(DATEADD(HOUR, (@HoursToBeAdded * 1), DATEADD(MINUTE, (@MinsToBeAdded * 1), GETUTCDATE()))AS NVARCHAR(20))) AS GeneratedDate,      
                                          ISNULL(@DistanceCovered, ' - ') AS Distance,              
                                          ISNULL(@DriverName, ' - ') AS DriverName,          
                                          ISNULL(@DriverContact,' - ') AS DriverContact,        
                                          (SELECT (ISNULL(StudentFirstName, '') + ' ' + ISNULL(StudentMiddleName, '') + ' ' + ISNULL(StudentLastName, '')) + ','              
                                           FROM   rvlfstudentMaster AS SM              
                                           WHERE  SM.BusInternalNo = @VehInterNo              
                                                  AND latitude = CAST (l.Latitude AS VARCHAR (10))              
                                                  AND SM.longitude = CAST (l.longitude AS VARCHAR (10))              
                                                  AND Active = 1              
                                           FOR    XML PATH ('')) AS StudName,              
                                          (SELECT (CASE               
WHEN RD.deviceid IS NULL THEN COUNT(ISNULL(StudentFirstName, '')) ELSE 0               
END)              
                                           FROM   rvlfstudentMaster AS SM              
                                           WHERE  SM.BusInternalNo = @VehInterNo              
                                                  AND latitude = CAST (l.Latitude AS VARCHAR (10))              
                                                  AND SM.longitude = CAST (l.longitude AS VARCHAR (10))              
           AND Active = 1) AS NoOfSkippedStud,        
           @SchoolName AS SchoolName        
                          FROM   [dbo].[rvlf_fn_GetRouteDetails] (@BOXIDS, @dtStartDate, @dtEndDate, @bigQueryingUser, 'L') AS RD                                                                        
                                 INNER JOIN              
                                 rvlfVehicle AS V              
                                 ON V.VehicleId = RD.VehicleId              
         INNER JOIN              
                                 RvlfRouteResourceMapping AS RRM              
                                 ON RRM.Vehicle_Internal_Number = V.InternalNo              
                                 RIGHT OUTER JOIN              
                                 #tblTempORS AS OJD              
                                 ON OJD.ORS_DriverId = RRM.ORS_Resource_ID              
                                    AND [TYPE] = @varTripType              
                                    AND [Depot] = @SchoolNo              
                                    AND OJD.landmark_Id = RD.LandMarkId              
                                 INNER JOIN              
                                 rvlfLandmark AS L              
                                 ON L.Latitude = OJD.Latitude              
                                    AND L.Longitude = OJD.Longitude              
                          WHERE  OJD.ORS_DriverId = @ResourceId) AS TBL              
                ORDER BY SeqID ASC;              
                DROP TABLE #tblTempORS;              
            END              
        SET @Flag = @Flag + 1;              
    END              
----------------------------------Select The Deviation details----------------------------------------              
SELECT *,SUBSTRING(StudentName, 0, LEN(StudentName) - 1) AS StudentNames,        
@FleetName AS FleetName, @varTripNo AS TripNo,        
CASE @varTripType WHEN '1' THEN 'Collect' ELSE 'Drop' END AS TripType,        
CAST (CAST(@dtStartDate AS DATE) AS VARCHAR(10))AS "DATE"         
FROM   @tblTempRouteDetails     
WHERE (@IsSkipped IS NULL OR @IsSkipped = '' OR LandCount = CAST(@IsSkipped AS INT))    
              
SET NOCOUNT OFF;                          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetRouteDriverorVehicleInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetRouteDriverorVehicleInfo]                            
 @sintRouteId smallint = Null,                             
 @dtFromDate datetime=null,                             
 @dtTodate datetime=null,                             
 @bigOrganizationID bigint = null,                             
 @bitIsDriverInfo bit=nulL,                            
 @intHoursToBeAdded INT = 0,                            
 @intMinsToBeAdded INT = 0,                            
 @bigQueryingUser bigint = null              
AS                            
/******************************************************************************/                            
-- Name  : [rvlf_sp_GetRouteDriverorVehicleInfo] NULL,'01-May-15 12:00:00 AM','30-May-15 12:00:00 AM',6,0,5,30                            
-- Description : To get the route wise driver/vehicle schedule details                            
-- Author  : V.Narayanasamy                            
-- Company  : Angler Technologies                            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                            
--    : 27-Sep-2010 VN Created Intial Version                             
--    : 31-Jan-2012 Vijay Rounded date format to Zero for time and minutes And Inner Join Condition Route ID for Route Assignemnt tables                        
--    : 28-Feb-2012 Vijay Removed the Route Driver Table from the Query              
/******************************************************************************/                            
BEGIN                            
 declare @Lang varchar(50)                 
 select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser              
                             
 IF(@bitIsDriverInfo =1)                            
  BEGIN                            
   SELECT distinct(RM.RouteId),RM.RouteName,RM.RouteDescription FROM rvlfRouteDriverAssignment RDA                             
     --INNER JOIN rvlfRouteMaster RM ON RM.RouteID=RDA.RouteId                             
     --SELECT * FROM rvlfRouteDriverAssignment DA                       
     INNER JOIN rvlfRouteMaster RM ON RDA.RouteId = RM.RouteId                       
     INNER JOIN rvlfRouteVehicleAssignment VA ON RDA.RouteId = VA.RouteId                       
     AND RDA.FromDateTime = VA.FromDateTime AND RDA.ToDateTime = vA.ToDateTime                      
     WHERE (@sintRouteId IS NULL OR @sintRouteId='' OR RDA.RouteID=@sintRouteId)                            
     AND (@dtFromDate IS NULL OR @dtTodate IS NULL OR                             
     DATEADD(Day, DATEDIFF(Day, 0, RDA.FromDateTime), 0) BETWEEN DATEADD(Day, DATEDIFF(Day, 0, @dtFromDate), 0) AND DATEADD(Day, DATEDIFF(Day, 0, @dtTodate), 0))                        
     --FromDateTime BETWEEN @dtFromDate AND @dtTodate)                            
     AND(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR RM.OrgID=@bigOrganizationID)                              
                               
   SELECT RDA.RouteId ,RDA.ASSIGNMENTID,                            
    CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.FromDateTime))) AS FromTime,                            
    CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.ToDateTime)))as ToTime,                            
    CONVERT(varchar,CONVERT(DATE,DATEADD(HOUR,5,DATEADD(MINUTE,30,RDA.FromDateTime))),106)as ScheduleDate,          
    CONVERT(varchar,CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.ToDateTime))),106)as EffectiveDate,           
    (case when @Lang='LanguageArNew' then isnull(dm.DisplayNameAr,dm.DisplayName) else DM.DisplayName end)as DisplayName,(case when @Lang='LanguageArNew' then isnull(v.VehicleDescription,v.VehicleDescription) else v.VehicleDescription end) AS VehName, 

	 
     CASE           
 WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.FromDateTime)))>CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))) THEN 'Scheduled'             
                                 
    WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.FromDateTime)))<CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))) THEN 'Completed'               
                                
     WHEN (CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))))>=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,RDA.FromDateTime)))                              
       AND CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))))<=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,RDA.ToDateTime))))                                 
       AND CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.FromDateTime)))=CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))) THEN 'Engaged' 
     
     WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.FromDateTime)))= CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE())))                            
       AND CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.ToDateTime)))< CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE())))) THEN 'Completed'                       

	    
     ELSE 'Scheduled'                            
    END AS DriverStatus,RDA.DriverId                               
   FROM rvlfRouteDriverAssignment RDA                             
     INNER JOIN rvlfRouteVehicleAssignment RVA ON RVA.FromDateTime=RDA.FromDateTime AND RVA.ToDateTime=RDA.ToDateTime AND RDA.RouteId = RVA.RouteId AND RDA.AssignedDate = RVA.AssignedDate                      
     INNER JOIN rvlfVehicle V ON V.VehicleId=RVA.VehicleId                             
     INNER JOIN rvlfRouteMaster RM ON RM.RouteID=RDA.RouteId                             
     INNER JOIN rvlfDriverMaster DM ON DM.DriverId=RDA.DriverId                     
                 
    WHERE (@sintRouteId IS NULL OR @sintRouteId='' OR RM.RouteID=@sintRouteId)                            
     AND (@dtFromDate IS NULL OR @dtTodate IS NULL OR                             
    DATEADD(Day, DATEDIFF(Day, 0, RDA.FromDateTime), 0)  BETWEEN  DATEADD(Day, DATEDIFF(Day, 0, @dtFromDate), 0)   AND   DATEADD(Day, DATEDIFF(Day, 0, @dtTodate), 0) )                            
   --RDA.FromDateTime BETWEEN @dtFromDate AND @dtTodate)                            
     AND(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR RM.OrgID=@bigOrganizationID)                            
    ORDER BY DriverStatus                              
  END                            
 ELSE                            
  BEGIN                              
  SELECT distinct(RM.RouteId),RM.RouteName,RM.RouteDescription FROM rvlfRouteVehicleAssignment RVA                             
     INNER JOIN rvlfRouteMaster RM ON RM.RouteID=RVA.RouteId                        
      --INNER JOIN rvlfRouteDriverAssignment RDA ON  RDA.RouteId = RVA.RouteId                       
    WHERE (@sintRouteId IS NULL OR @sintRouteId='' OR RVA.RouteID=@sintRouteId)                            
     AND (@dtFromDate IS NULL OR @dtTodate IS NULL OR                             
     DATEADD(Day, DATEDIFF(Day, 0, RVA.FromDateTime), 0) BETWEEN DATEADD(Day, DATEDIFF(Day, 0, @dtFromDate), 0) AND DATEADD(Day, DATEDIFF(Day, 0, @dtTodate), 0))     AND(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR RM.OrgID=@bigOrganizationID) and rva.Isdelete is null
     
   SELECT distinct RVA.RouteId,RVA.ASSIGNMENTID,      
   CONVERT(VARCHAR(9),RIGHT(DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime)),8),108) as FromTime,      
   CONVERT(VARCHAR(9),RIGHT(DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.ToDateTime)),8),108) as ToTime,      
    CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime))) AS FromTime1,                            
    CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.ToDateTime)))as ToTime1,                            
    CONVERT(varchar,CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime))),106)as ScheduleDate,          
    CONVERT(varchar,CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.ToDateTime))),106)as EffectiveDate, (case when @Lang='LanguageArNew' then isnull(v.VehicleDescription,v.VehicleDescription) else v.VehicleDescription 
end)as DisplayName,   
	 CASE                             
     WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime)))>CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))) THEN case when CL.ResponseMsg like '%successfully%'
        
      then 'Assigned to device' else isnull(CL.ResponseMsg,'Scheduled') end            
     WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime)))<CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))) THEN case when CL.ResponseMsg like '%successfully%'
        
      then 'Assigned to device' else isnull(cl.ResponseMsg,'Failed') end                          
        
     WHEN (CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))))>=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,RVA.FromDateTime)))                              
       AND CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))))<=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,RVA.ToDateTime))))                                 
        THEN case when CL.ResponseMsg like '%successfully%' Then 'Engaged' else isnull(CL.ResponseMsg,'Assign Failed') end             
    
     WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime)))<= CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE())))                            
       AND CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.ToDateTime)))< CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE())))) THEN             
       case when CL.ResponseMsg like '%successfully%' then 'Completed' else isnull(CL.ResponseMsg,'Assign Failed') end                                 
       WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime)))= CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE())))                            
       AND CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime)))> CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE())))) THEN             
       case when CL.ResponseMsg like '%successfully%' then 'Assigned To Device' else isnull(CL.ResponseMsg,'Assign Failed') end         
           
       ELSE 'Scheduled' END AS VehicleStatus,          
    CASE WHEN RVA.FromDateTime BETWEEN FromTime AND ToTime THEN        
     (case when @Lang='LanguageArNew' then isnull(dm.DisplayNameAr,dm.DisplayName) else DM.DisplayName end) 
    ELSE '-'  END AS DriName,DA.DriverId,RVA.FromDateTime,CM.ScheduleId,
	case when RVA.Frequency = 0 then 'Daily' when RVA.Frequency=1 then 'Weekly' when RVA.Frequency=2 then 'Monthly' end as Frequency
                                
  FROM rvlfVehicleAssignment VA                   
      INNER JOIN rvlfDriverAssignment DA ON DA.BoxId = VA.BoxId              
      INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId AND DATEADD(Day, DATEDIFF(Day, 0,DA.FromTime), 0)  BETWEEN  DATEADD(Day, DATEDIFF(Day, 0, @dtFromDate), 0)   AND   DATEADD(Day, DATEDIFF(Day, 0, @dtTodate), 0)                             
      RIGHT OUTER JOIN rvlfRouteVehicleAssignment RVA ON RVA.FromDateTime between FromTime AND ToTime AND VA.VehicleId = RVA.VehicleId             
      INNER JOIN rvlfRouteMaster RM ON RM.RouteID=RVA.RouteId                             
      INNER JOIN rvlfVehicle V ON V.VehicleId=RVA.VehicleId             
      inner join rvlfScheduleOfCommandsMaster CM on RVA.ScheduleId=CM.ScheduleId            
     left join rvlfSchedulingOfCommandsLog CL on CM.ScheduleId=CL.ScheduleId              
    WHERE (@sintRouteId IS NULL OR @sintRouteId='' OR RM.RouteID=@sintRouteId)               
     AND (@dtFromDate IS NULL OR @dtTodate IS NULL OR                             
    DATEADD(Day, DATEDIFF(Day, 0, RVA.FromDateTime), 0)  BETWEEN  DATEADD(Day, DATEDIFF(Day, 0, @dtFromDate), 0)   AND   DATEADD(Day, DATEDIFF(Day, 0, @dtTodate), 0))                                 
     AND(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR RM.OrgID=@bigOrganizationID)   and rva.Isdelete is null                                 
    ORDER BY RVA.FromDateTime,VehicleStatus                             
  END                             
END 


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetRouteDriverorVehicleInfo1]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetRouteDriverorVehicleInfo1]                            
 @sintRouteId smallint = Null,                             
 @dtFromDate datetime=null,                             
 @dtTodate datetime=null,                             
 @bigOrganizationID bigint = null,                             
 @bitIsDriverInfo bit=nulL,                            
 @intHoursToBeAdded INT = 0,                            
 @intMinsToBeAdded INT = 0,                            
 @bigQueryingUser bigint = null              
AS                            
/******************************************************************************/                            
-- Name  : [rvlf_sp_GetRouteDriverorVehicleInfo1] 39,'07-Jan-16 12:00:00 AM','10-Jan-16 12:00:00 AM',6,0,5,30                            
-- Description : To get the route wise driver/vehicle schedule details                            
-- Author  : V.Narayanasamy                            
-- Company  : Angler Technologies                            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                            
--    : 27-Sep-2010 VN Created Intial Version                             
--    : 31-Jan-2012 Vijay Rounded date format to Zero for time and minutes And Inner Join Condition Route ID for Route Assignemnt tables                        
--    : 28-Feb-2012 Vijay Removed the Route Driver Table from the Query              
/******************************************************************************/                            
BEGIN                            
 declare @Lang varchar(50)                 
 select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser              
                             
 IF(@bitIsDriverInfo =1)                            
  BEGIN                            
   SELECT distinct(RM.RouteId),RM.RouteName,RM.RouteDescription FROM rvlfRouteDriverAssignment RDA                             
     --INNER JOIN rvlfRouteMaster RM ON RM.RouteID=RDA.RouteId                             
     --SELECT * FROM rvlfRouteDriverAssignment DA                       
     INNER JOIN rvlfRouteMaster RM ON RDA.RouteId = RM.RouteId                       
     INNER JOIN rvlfRouteVehicleAssignment VA ON RDA.RouteId = VA.RouteId                       
     AND RDA.FromDateTime = VA.FromDateTime AND RDA.ToDateTime = vA.ToDateTime                      
     WHERE (@sintRouteId IS NULL OR @sintRouteId='' OR RDA.RouteID=@sintRouteId)                            
     AND (@dtFromDate IS NULL OR @dtTodate IS NULL OR                             
     DATEADD(Day, DATEDIFF(Day, 0, RDA.FromDateTime), 0) BETWEEN DATEADD(Day, DATEDIFF(Day, 0, @dtFromDate), 0) AND DATEADD(Day, DATEDIFF(Day, 0, @dtTodate), 0))                        
     --FromDateTime BETWEEN @dtFromDate AND @dtTodate)                            
     AND(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR RM.OrgID=@bigOrganizationID)                              
                               
   SELECT RDA.RouteId ,RDA.ASSIGNMENTID,                            
    CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.FromDateTime))) AS FromTime,                            
    CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.ToDateTime)))as ToTime,                            
    CONVERT(varchar,CONVERT(DATE,DATEADD(HOUR,5,DATEADD(MINUTE,30,RDA.FromDateTime))),106)as ScheduleDate,          
    CONVERT(varchar,CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.ToDateTime))),106)as EffectiveDate,           
    (case when @Lang='LanguageArNew' then isnull(dm.DisplayNameAr,dm.DisplayName) else DM.DisplayName end)as DisplayName,(case when @Lang='LanguageArNew' then isnull(v.VehicleDescription,v.VehicleDescription) else v.VehicleDescription end) AS VehName,
     
     CASE           
     WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.FromDateTime)))>CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))) THEN 'Scheduled'             
                                 
    WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.FromDateTime)))<CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))) THEN 'Completed'               
                                
     WHEN (CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))))>=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,RDA.FromDateTime)))                              
       AND CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))))<=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,RDA.ToDateTime))))                                 
       AND CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.FromDateTime)))=CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))) THEN 'Engaged'  
     
     WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.FromDateTime)))= CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE())))                            
       AND CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RDA.ToDateTime)))< CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE())))) THEN 'Completed'
        
     ELSE 'Scheduled'                            
    END AS DriverStatus,RDA.DriverId                               
   FROM rvlfRouteDriverAssignment RDA                             
     INNER JOIN rvlfRouteVehicleAssignment RVA ON RVA.FromDateTime=RDA.FromDateTime AND RVA.ToDateTime=RDA.ToDateTime AND RDA.RouteId = RVA.RouteId AND RDA.AssignedDate = RVA.AssignedDate                      
     INNER JOIN rvlfVehicle V ON V.VehicleId=RVA.VehicleId                             
     INNER JOIN rvlfRouteMaster RM ON RM.RouteID=RDA.RouteId                             
     INNER JOIN rvlfDriverMaster DM ON DM.DriverId=RDA.DriverId                     
                 
    WHERE (@sintRouteId IS NULL OR @sintRouteId='' OR RM.RouteID=@sintRouteId)                            
     AND (@dtFromDate IS NULL OR @dtTodate IS NULL OR                             
    DATEADD(Day, DATEDIFF(Day, 0, RDA.FromDateTime), 0)  BETWEEN  DATEADD(Day, DATEDIFF(Day, 0, @dtFromDate), 0)   AND   DATEADD(Day, DATEDIFF(Day, 0, @dtTodate), 0) )                            
   --RDA.FromDateTime BETWEEN @dtFromDate AND @dtTodate)                            
     AND(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR RM.OrgID=@bigOrganizationID)                            
    ORDER BY DriverStatus                              
  END                            
 ELSE                            
  BEGIN                              
  SELECT distinct(RM.RouteId),RM.RouteName,RM.RouteDescription FROM rvlfRouteVehicleAssignment RVA                             
     INNER JOIN rvlfRouteMaster RM ON RM.RouteID=RVA.RouteId                        
      --INNER JOIN rvlfRouteDriverAssignment RDA ON  RDA.RouteId = RVA.RouteId                       
    WHERE (@sintRouteId IS NULL OR @sintRouteId='' OR RVA.RouteID=@sintRouteId)                            
     AND (@dtFromDate IS NULL OR @dtTodate IS NULL OR                             
     DATEADD(Day, DATEDIFF(Day, 0, RVA.FromDateTime), 0) BETWEEN DATEADD(Day, DATEDIFF(Day, 0, @dtFromDate), 0) AND DATEADD(Day, DATEDIFF(Day, 0, @dtTodate), 0))     AND(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR RM.OrgID=@bigOrganizationID)  
 and rva.Isdelete is null
                
   SELECT distinct RVA.RouteId,RVA.ASSIGNMENTID,      
   CONVERT(VARCHAR(9),RIGHT(DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime)),8),108) as FromTime,      
   CONVERT(VARCHAR(9),RIGHT(DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.ToDateTime)),8),108) as ToTime,      
    CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime))) AS FromTime1,                            
    CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.ToDateTime)))as ToTime1,                            
    CONVERT(varchar,CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime))),106)as ScheduleDate,          
    CONVERT(varchar,CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.ToDateTime))),106)as EffectiveDate,    (case when @Lang='LanguageArNew' then isnull(v.VehicleDescription,v.VehicleDescription) else v.VehicleDescription end)as DisplayName,    CASE                             
     WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime)))>CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))) THEN case when CL.ResponseMsg like '%successfully%'
        
      then 'Assigned to device' else isnull(CL.ResponseMsg,'Scheduled') end            
     WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime)))<CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))) THEN case when CL.ResponseMsg like '%successfully%' 
      then 'Assigned to device' else isnull(cl.ResponseMsg,'Failed') end                          
        
     WHEN (CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))))>=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,RVA.FromDateTime)))                              
       AND CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE()))))<=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,RVA.ToDateTime))))                                 
        THEN case when CL.ResponseMsg like '%successfully%' Then 'Engaged' else isnull(CL.ResponseMsg,'Assign Failed') end             
    
     WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime)))<= CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE())))                            
       AND CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.ToDateTime)))< CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE())))) THEN             
       case when CL.ResponseMsg like '%successfully%' then 'Completed' else isnull(CL.ResponseMsg,'Assign Failed') end                                 
       WHEN CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime)))= CONVERT(DATE,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE())))                            
       AND CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,RVA.FromDateTime)))> CONVERT(TIME,CONVERT(TIME,DATEADD(HOUR,@intHoursToBeAdded,DATEADD(MINUTE,@intMinsToBeAdded,GETUTCDATE())))) THEN             
       case when CL.ResponseMsg like '%successfully%' then 'Assigned To Device' else isnull(CL.ResponseMsg,'Assign Failed') end         
           
       ELSE 'Scheduled' END AS VehicleStatus,          
    CASE WHEN RVA.FromDateTime BETWEEN FromTime AND ToTime THEN        
     (case when @Lang='LanguageArNew' then isnull(dm.DisplayNameAr,dm.DisplayName) else DM.DisplayName end)              
    ELSE '-'  END AS DriName,DA.DriverId,RVA.FromDateTime        
                                
  FROM rvlfVehicleAssignment VA                   
     --INNER JOIN rvlfRouteDriverAssignment RDA ON RVA.FromDateTime=RDA.FromDateTime AND RVA.ToDateTime=RDA.ToDateTime AND RDA.RouteId = RVA.RouteId AND RDA.AssignedDate = RVA.AssignedDate         
      left JOIN rvlfDriverAssignment DA ON DA.BoxId = VA.BoxId              
      left JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId AND DATEADD(Day, DATEDIFF(Day, 0,DA.FromTime), 0)  BETWEEN  DATEADD(Day, DATEDIFF(Day, 0, @dtFromDate), 0)   AND   DATEADD(Day, DATEDIFF(Day, 0, @dtTodate), 0)                             
      RIGHT OUTER JOIN rvlfRouteVehicleAssignment RVA ON RVA.FromDateTime between FromTime AND ToTime AND VA.VehicleId = RVA.VehicleId             
      INNER JOIN rvlfRouteMaster RM ON RM.RouteID=RVA.RouteId                             
      INNER JOIN rvlfVehicle V ON V.VehicleId=RVA.VehicleId             
      inner join rvlfScheduleOfCommandsMaster CM on RVA.ScheduleId=CM.ScheduleId            
     left join rvlfSchedulingOfCommandsLog CL on CM.ScheduleId=CL.ScheduleId              
    WHERE (@sintRouteId IS NULL OR @sintRouteId='' OR RM.RouteID=@sintRouteId)               
     AND (@dtFromDate IS NULL OR @dtTodate IS NULL OR                             
    DATEADD(Day, DATEDIFF(Day, 0, RVA.FromDateTime), 0)  BETWEEN  DATEADD(Day, DATEDIFF(Day, 0, @dtFromDate), 0)   AND   DATEADD(Day, DATEDIFF(Day, 0, @dtTodate), 0) )                            
    --AND DATEADD(Day, DATEDIFF(Day, 0, DA.FromTime), 0)  BETWEEN  DATEADD(Day, DATEDIFF(Day, 0, @dtFromDate), 0)   AND   DATEADD(Day, DATEDIFF(Day, 0, @dtTodate), 0)                             
     AND(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR RM.OrgID=@bigOrganizationID)   and rva.Isdelete is null                              
    -- AND RVA.FromDateTime BETWEEN DA.FromTime AND DA.ToTime               
    -- AND RVA.ToDateTime BETWEEN DA.FromTime AND DA.ToTime              
    ORDER BY RVA.FromDateTime,VehicleStatus                             
  END                             
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetRouteInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetRouteInfo]             
 @sintRouteId smallint = Null,             
 @bigOrganizationID bigint = null,      
 @bigQueryingUser bigint = null             
AS            
/******************************************************************************/            
-- Name  : [rvlf_sp_GetRouteInfo] null,6
-- Description : To get the Route Info            
-- Author  : S.Jeyanthi            
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--    : 26-Sep-2010 SJ Created Intial Version             
--    : 26-sEP-2010 VN added the aditional parameter routeid            
--    : 28-Jan-2012 Vijay Added Row number.          
--    : 30-Jan-2012 Vijay - Added Is Deleted  Column to the Route Master Query.        
/******************************************************************************/            
BEGIN            
             
 --DECLARE @LAND VARCHAR(1000)=NULL            
             
 --SELECT @LAND=COALESCE(@LAND,'')+L.LandmarkName+',' FROM rvlfRouteMaster RM            
 -- INNER JOIN rvlfRouteDetails RD ON RM.RouteID=RD.RouteID             
 -- INNER JOIN rvlfLandmark L ON L.LandmarkID=RD.LndID             
              
        DECLARE @HoursToBeAdded INT = 0              
 DECLARE @MinsToBeAdded INT = 0              
               
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded              
 FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz              
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser    
      
  --SELECT DISTINCT (RM.RouteID),RM.RouteName,RM.RouteDescription,RM.TravelDuration,RM.TravelDistance,RM.TrafficDuration,     
  --CASE WHEN EXISTS (SELECT AssignmentId FROM rvlfRouteVehicleAssignment WHERE  GETDATE() < DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),ToDateTime)) AND RouteId=RM.RouteID)        
  --THEN 0         
  --ELSE 1 END AS IsAbleToDelete,RM.GRouteID        
  --FROM rvlfRouteMaster RM        
  ----LEFT OUTER JOIN rvlfRouteVehicleAssignment RVA ON RM.RouteID = RVA.RouteId        
  --WHERE (@sintRouteId IS NULL OR RM.RouteID=@sintRouteId)             
  --AND(@bigOrganizationID IS NULL or @bigOrganizationID = '' OR RM.OrgID=@bigOrganizationID)               
               
  --SELECT *,ROW_NUMBER() OVER(ORDER BY RouteName) AS [Index] FROM rvlfRouteMaster RM            
  --INNER JOIN rvlfRouteDetails RD ON RM.RouteID=RD.RouteID             
  --INNER JOIN rvlfLandmark L ON L.LandmarkID=RD.LndID             
  --WHERE (@sintRouteId IS NULL or @sintRouteId ='' OR RM.RouteID=@sintRouteId)             
                     
  SELECT DISTINCT (RM.RouteID),RM.RouteName,RM.RouteDescription,RM.TravelDuration,RM.TravelDistance,RM.TrafficDuration, 
  CASE WHEN EXISTS (SELECT AssignmentId FROM rvlfRouteVehicleAssignment WHERE  GETDATE() < DATEADD(HOUR,(@HoursToBeAdded),  
  DATEADD(MINUTE,(@MinsToBeAdded),ToDateTime)) AND RouteId=RM.RouteID)                          
  THEN 0 ELSE 1 END AS IsAbleToDelete,RM.GRouteID,CASE(RM.IsCircularTrip) When 1 Then 1 Else 0 End as IsCircularTrip                          
  FROM rvlfRouteMaster RM                          
  --LEFT OUTER JOIN rvlfRouteVehicleAssignment RVA ON RM.RouteID = RVA.RouteId                          
  WHERE (@sintRouteId IS NULL OR RM.RouteID=@sintRouteId)                               
  AND(@bigOrganizationID IS NULL or @bigOrganizationID = '' OR RM.OrgID=@bigOrganizationID)                                 
                  
SELECT RouteDetailsId,rd.RouteID,LndID,SeqID,Duration,Distance,rd.TrafficDuration,rd.HaltTime as HaltTimeSec,rd.BufferTime as BufferTimeSec,   rm.RouteID,RouteName,RouteDescription,TravelDuration,TravelDistance,OrgID,GRouteId,rm.TrafficDuration, L.*,G.*,          
  CAST(G.Latitude AS VARCHAR)+','+CAST(G.Longitude AS VARCHAR) AS LatLng,NULL AS OptOrder,
  (cast(((HaltTime /3600)%24) as varchar(5))+'.'+ Case when HaltTime< 600 then '0' else '' end + cast(((HaltTime/60)%60) as varchar(5))) as HaltTime,          
  (cast(((BufferTime /3600)%24) as varchar(5))+'.'+ Case when BufferTime< 600 then '0' else '' end+cast(((BufferTime/60)%60) as varchar(5))) as BufferTime, DurationSec, ROW_NUMBER() OVER(ORDER BY RouteName) AS [Index] FROM rvlfRouteMaster RM   
  INNER JOIN rvlfRouteDetails RD ON RM.RouteID=RD.RouteID   
  INNER JOIN rvlfOrganizationGeozone L ON L.GeozoneId=RD.LndID   
  inner join rvlfGeozoneSet G on L.GeozoneNo=g.GeozoneNo   
  WHERE (@sintRouteId IS NULL or @sintRouteId ='' OR RM.RouteID=@sintRouteId) and l.GeozoneType=3   
  and (@bigOrganizationID IS NULL or @bigOrganizationID ='' OR L.OrganizationId=@bigOrganizationID) order by SeqID   
            
select cast(LndID as varchar(10)) + ',' +               
RIGHT('0' + CONVERT(varchar(max), round(((cast(DurationSec as FLOat)+BufferTime) / 60),0)), 2)+','      
+cast(cast(ROUND(case when cast(Distance as float) >1 then cast(Distance as float) else case when cast(Distance as float)='' then 0 else 1 end end,0)as int) as varchar)+','+ cast((HaltTime / 60) as varchar) as ParamFrame          
from rvlfRouteDetails where (@sintRouteId IS NULL or @sintRouteId ='' OR RouteID=@sintRouteId)
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetRouteOptimization4]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[rvlf_sp_GetRouteOptimization4]
	@dtShiftin TIME=null,
	@dtShiftout TIME=null,
	@dtShiftdate DATETIME=null,
	@vcTripMode VARCHAR(7)=null,
	@bigBranchId bigint=null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_GetRouteOptimization4] '8:00:00','17:00:00','08/04/2014','pickup',30
--	Description	:	To get the route optimization details
--	Author		:	V. Narayanasamy.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	1-Feb-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN

--Employee wise distance 

	DECLARE @tblEmployeeList TABLE
	(
		EmployeeID bigint,
		EmployeeName varchar(50),
		FromLatitude numeric(10,6),
		FromLongitude numeric(10,6),
		ToLatitude numeric(10,6),
		ToLongitude numeric(10,6),
		Distance numeric(10,6),
		EmpDistance numeric(10,6),
		PlotOrder int,
		NoOfEmps int,
		LocalityId bigint,
		ServiceType varchar(7),
		Assign int,
		AssignedVehicle bigint,
		Cost numeric(7,2),
		sequenceNo int,
		FromAddress varchar(200),
		PickupTimeForIntimation time(7),
		PickupTime time(7),
		VehicleStartTime time(7)	
	)
	INSERT INTO @tblEmployeeList (EmployeeID,EmployeeName,FromLatitude,FromLongitude,ToLatitude,ToLongitude,NoOfEmps,LocalityId,ServiceType,FromAddress)
	SELECT E.EmployeeID,E.DisplayName,OA.Latitude,OA.Longitude,sv.Latitude,sv.Longitude,COUNT(lm.LocalityId),LM.LocalityId,SV.RequisitionService,SV.FromAddress   
	FROM rvlfEmployee E 		
		INNER JOIN rvlfScheduledVehicleRequisition SV ON SV.EmployeeId=E.EmployeeID 
		INNER JOIN rvlfLocalityMaster LM ON LM.LocalityId=SV.LocalityId 
		INNER JOIN rvlfEmployeeShifts ES ON ES.EmployeeId=SV.EmployeeId 
		INNER JOIN rvlfOfficeAddress OA ON OA.AddressId=E.OrgId  
		
	WHERE (@dtShiftin IS NULL OR ES.ShiftIn=CONVERT(TIME,@dtShiftin))
		AND (@dtShiftout IS NULL OR ES.ShiftOut=CONVERT(TIME,@dtShiftout))
		AND (ES.ShiftDate=CASE WHEN @dtShiftdate IS NULL THEN SV.RequisitionFromDate ELSE @dtShiftdate END)
		AND (SV.Closed=0)
		AND(ES.Leave=0)
		AND (ES.ShiftDate>=SV.RequisitionFromDate)
		AND(ES.ShiftDate<=SV.RequisitionToDate)
		AND(@vcTripMode IS NULL OR sv.RequisitionService=@vcTripMode OR sv.RequisitionService='Both')
		AND LM.ALLOCATED=0
		AND(@bigBranchId IS NULL OR E.OrgId=@bigBranchId)
		AND (ISDELETED=0)
		AND (Available=1)
		AND (Approval !='R')
	GROUP BY LM.LocalityId,E.EmployeeID,E.DisplayName,OA.Latitude,OA.Longitude,sv.Latitude,sv.Longitude,SV.RequisitionService,SV.FromAddress     

	DECLARE @tblcount int=0
	DECLARE @fromLat numeric(10,6)
	DECLARE @fromLng numeric(10,6)
	DECLARE @toLat numeric(10,6)
	DECLARE @toLng numeric(10,6)
	DECLARE @LocId bigint
	DECLARE @dist numeric(15,6)

	WHILE EXISTS(SELECT * FROM @tblEmployeeList WHERE PlotOrder IS NULL)
		BEGIN
			SELECT TOP 1 @LocId=LocalityId , @fromLat=FromLatitude,@fromLng =FromLongitude ,@toLat =ToLatitude ,@toLng=ToLongitude  
				FROM @tblEmployeeList WHERE PlotOrder IS NULL
				
			SET @dist  = (MIN(DEGREES(ACOS((SIN(RADIANS(@fromLat)) * 
				  SIN(RADIANS(@toLat)) +
				  COS(RADIANS(@fromLat)) *
				  COS(RADIANS(@toLat)) *
				  COS(RADIANS(@fromLng - @toLng)))))) * 69.09 * 1.609344)
				  
			UPDATE @tblEmployeeList SET Distance=@dist,PlotOrder=@tblcount WHERE LocalityId =@LocId 
			
			SET @tblcount =@tblcount+1
		END

--ROUTE ASSIGNMENT

DECLARE @tblRouteAssignment TABLE
(
	RouteId bigint,
	LocalityId bigint,
	NoOfEmps int,
	PickedEmps int,
	DuplicateTotEmps int,
	Distance numeric(10,6),
	RouteStatus varchar(30),
	TripCost NUMERIC(8),
	LowRoute bigint
)

DECLARE @ASSIGNMENT INT=0
DECLARE @LOCALITYID BIGINT
DECLARE @ROUTEID BIGINT
DECLARE @NOOFEMPS INT

WHILE EXISTS(SELECT EmployeeID  FROM @tblEmployeeList WHERE Assign IS NULL)
	BEGIN
		SELECT TOP 1 @LOCALITYID=LocalityId,@NOOFEMPS=COUNT(EmployeeID),@dist=Distance FROM @tblEmployeeList WHERE Assign IS NULL GROUP BY LocalityId,Distance  
		SELECT TOP 1 @ROUTEID=RM.RouteId FROM rvlfRouteMastercsc RM INNER JOIN rvlfRouteDetails1 RD ON RD.RouteId=RM.RouteId WHERE RD.LocalityId=@LOCALITYID 
		INSERT INTO @tblRouteAssignment (RouteId,LocalityId,NoOfEmps,DuplicateTotEmps,Distance)VALUES(@ROUTEID,@LOCALITYID,@NOOFEMPS,@NOOFEMPS,@dist)		
		UPDATE @tblEmployeeList SET Assign=@ASSIGNMENT WHERE Assign IS NULL AND LocalityId=@LOCALITYID   
		SET @ASSIGNMENT=@ASSIGNMENT+1
	END

DECLARE @tblVehicleAssignment table
(
	RouteId bigint,
	LocalityId bigint,
	VehicleId bigint,
	Occupancy numeric(6,2),
	Distance varchar(5),
	TripCost numeric(6,2),
	TripTime varchar(20)
)

DECLARE @VEHICLEID BIGINT
DECLARE @LOCALTYNOEMPS INT
DECLARE @CAPACITY INT
DECLARE @ROUTE2LONGLOC BIGINT
DECLARE @ROUTE2LONGLOCEMPS INT
DECLARE @LOWROUTEEMPS INT=0
DECLARE @LOWROUTE INT=1

--UPDATE THE NULL DISTANCE IN THE EMPLOYEE LIST

UPDATE @tblRouteAssignment SET RouteStatus='PROBLEMINDISTANCE',TripCost=0,Distance=0 WHERE Distance IS NULL
UPDATE @tblEmployeeList SET AssignedVehicle=0,Cost=0,Distance=0 WHERE Distance IS NULL


--CASE1:-THE NO OF EMPLOYEES IS GREATER THAN 75% AND LESS THAN OR EQUAL TO 100%

WHILE EXISTS(SELECT RouteId FROM @tblRouteAssignment WHERE RouteStatus IS NULL)
BEGIN

	SET @ROUTEID=NULL
	SET @CAPACITY=NULL
	SET @VEHICLEID =NULL 
	SET @LOCALITYID =NULL
	SET @NOOFEMPS=NULL
	SET @LOCALTYNOEMPS=NULL	
	SET @ROUTE2LONGLOC=NULL
	SET @ROUTE2LONGLOCEMPS=NULL
	
--LESS THEN 75% ROUTE EMPLOYEES ARE ASSIGNED 

	WHILE EXISTS(SELECT RouteId FROM @tblRouteAssignment WHERE LowRoute IS NULL AND RouteStatus IS NULL )
		BEGIN 		
			SELECT TOP 1 @ROUTEID=RouteId FROM @tblRouteAssignment WHERE LowRoute IS NULL AND Distance IN(SELECT MAX(Distance) FROM @tblRouteAssignment WHERE LowRoute IS NULL)
			SELECT @NOOFEMPS=SUM(NoOfEmps)FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND LowRoute IS NULL GROUP BY RouteId								
	
			IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@NOOFEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0 AND Capacity>0
					AND Capacity=(SELECT MIN(Capacity) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
				BEGIN	
																
					--SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE Capacity=(SELECT MIN(Capacity) FROM rvlfVehicleMaster WHERE Allocated=0)AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0	AND Capacity>0					
					SET @LOWROUTEEMPS=@LOWROUTEEMPS+@NOOFEMPS 	
										
					UPDATE @tblRouteAssignment SET LowRoute=@LOWROUTE,RouteStatus='LowRoute' WHERE LowRoute IS NULL AND RouteId=@ROUTEID AND (RouteStatus IS NULL OR RouteStatus='CLOSED')		
				END
			ELSE 
				BEGIN				
					UPDATE @tblRouteAssignment SET LowRoute=0 WHERE LowRoute IS NULL AND RouteId=@ROUTEID 
				END
		END
		
	UPDATE @tblRouteAssignment SET RouteStatus=NULL WHERE LowRoute !=0 AND RouteStatus!='LowRoute' AND RouteStatus !='CLOSED'			
	SET @ROUTEID=NULL
	SET @LOWROUTEEMPS=0
	SET @NOOFEMPS=NULL
	SET @LOCALITYID=NULL 
				
	SELECT TOP 1 @ROUTEID=RouteId FROM @tblRouteAssignment WHERE RouteStatus IS NULL AND Distance IN(SELECT MAX(Distance) FROM @tblRouteAssignment WHERE RouteStatus IS NULL)
	SELECT @NOOFEMPS=SUM(NoOfEmps)FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND RouteStatus IS NULL GROUP BY RouteId
	SELECT @LOCALITYID=LocalityId FROM @tblRouteAssignment WHERE RouteStatus IS NULL AND RouteId=@ROUTEID 								
	

	--UPDATE @tblRouteAssignment SET LowRoute=NULL WHERE RouteStatus IS NULL AND LowRoute =0

	IF NOT EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE Allocated=0 AND  InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
		BEGIN
			UPDATE @tblRouteAssignment SET RouteStatus='NO VEHICLE' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID 
		END
	ELSE
		BEGIN	
			IF(@NOOFEMPS<=(SELECT MAX(Capacity) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0))
				BEGIN								
					IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE Capacity=@NOOFEMPS AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
						BEGIN
							SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE Capacity=@NOOFEMPS AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
							INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@NOOFEMPS/(@CAPACITY*1.00)*100))
							UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
							UPDATE @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId IN (SELECT LocalityId  FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND RouteStatus IS NULL) AND AssignedVehicle IS NULL
							UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID 							
						END
					ELSE IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@NOOFEMPS /(Capacity*1.00))*100)>=75 AND ((@NOOFEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
						BEGIN
							SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@NOOFEMPS /(Capacity*1.00))*100)>=75 AND ((@NOOFEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
							INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@NOOFEMPS/(@CAPACITY*1.00)*100))
							UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
							UPDATE @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId IN (SELECT LocalityId  FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND RouteStatus IS NULL) AND AssignedVehicle IS NULL
							UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID 							
						END
					ELSE IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@NOOFEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0) 
						BEGIN
							SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@NOOFEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0 order by Capacity 					
							IF(@VEHICLEID IS NULL)
								BEGIN
									UPDATE @tblRouteAssignment SET RouteStatus='NOVEHICLE' WHERE RouteId=@ROUTEID 	
								END
							ELSE
								BEGIN
									IF(@NOOFEMPS>@CAPACITY)
										BEGIN
											UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=(SELECT MAX(Capacity) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0								
										END
									ELSE
										BEGIN
											--INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@NOOFEMPS/(@CAPACITY*1.00)*100))
											--UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
											--UPDATE @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId IN (SELECT LocalityId  FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND RouteStatus IS NULL) AND AssignedVehicle IS NULL
											--UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID 
											UPDATE @tblRouteAssignment SET LowRoute=@LOWROUTE,RouteStatus='LowRoute' WHERE  RouteId=@ROUTEID AND (RouteStatus IS NULL OR RouteStatus='CLOSED') 																																		
										END
									
								END
						END
				END
		
--CASE2:-THE NUMBER OF EMPLOYEES GREATER THAN AVAILABLE VEHICLE CAPACITY
--		 SO FIND THE LONGEST LOCALITY FROM THE OFFICE AND ASSIGN THE VEHICLE TO THAT LOCALITY.	

--		 LOCALITY WISE TOTAL NUMBER OF EMPLOYEES = AVAILABLE VEHICLE CAPACITY
		
			IF(@NOOFEMPS>(SELECT MAX(Capacity) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0))
				BEGIN			
					SET @LOCALITYID=NULL
					SET @LOCALTYNOEMPS=NULL
					SELECT TOP 1 @LOCALITYID=LocalityId,@LOCALTYNOEMPS=NoOfEmps FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND RouteStatus IS NULL ORDER BY Distance DESC 
							
					IF EXISTS(SELECT * FROM rvlfVehicleMaster WHERE Capacity=@LOCALTYNOEMPS AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
					BEGIN						
						SET @VEHICLEID=NULL
						SET @CAPACITY=NULL										
						SELECT @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE Capacity=@LOCALTYNOEMPS AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
						INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@CAPACITY/(@CAPACITY*1.00)*100))
						UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
						UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
						UPDATE TOP(@CAPACITY) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL

					END
--CASE 3:
--		 LOCALITY WISE TOTAL NUMBER OF EMPLOYEES > AVAILABLE VEHICLE CAPACITY

				ELSE IF(@LOCALTYNOEMPS>(SELECT MAX(CAPACITY) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0))
					BEGIN	
										
						SET @VEHICLEID =NULL
						SET @CAPACITY=NULL
						SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster 
							WHERE Allocated=0 AND Capacity IN(SELECT MAX(CAPACITY) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0) AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
																									
						INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy) 
							VALUES(@ROUTEID,@LOCALITYID,@VEHICLEID,(@CAPACITY/(@CAPACITY*1.00)*100)) 
						UPDATE @tblRouteAssignment SET NoOfEmps=(@LOCALTYNOEMPS-@CAPACITY),PickedEmps=@CAPACITY WHERE  RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
						UPDATE rvlfVehicleMaster SET Allocated=1 WHERE VehicleId=@VEHICLEID AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
						UPDATE TOP(@CAPACITY) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL													
						SELECT @LOCALTYNOEMPS=NoOfEmps FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID   
						SET @VEHICLEID =NULL
						SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster 
							WHERE Allocated=0 AND Capacity IN(SELECT MAX(CAPACITY) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0) AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
					
			 		

--REMAINING EMPLOYEES GREATER THAN AVAILABLE VEHICLE CAPACITY		
						
						IF(@VEHICLEID IS NULL)
							BEGIN
								UPDATE @tblRouteAssignment SET  RouteStatus='VEHICLENOTAVAILABLE' WHERE  RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
							END
						ELSE IF((SELECT SUM(NoOfEmps) FROM @tblRouteAssignment WHERE RouteId=@ROUTEID)>(SELECT MAX(Capacity) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0))  
							BEGIN
									
								IF(@LOCALTYNOEMPS>=@CAPACITY)
									BEGIN	
																
										INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy) VALUES(@ROUTEID,@LOCALITYID,@VEHICLEID,(@CAPACITY/(@CAPACITY*1.00)*100)) 
										UPDATE @tblRouteAssignment SET NoOfEmps=(@LOCALTYNOEMPS-@CAPACITY),PickedEmps=@CAPACITY WHERE  RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
										UPDATE rvlfVehicleMaster SET Allocated=1 WHERE VehicleId=@VEHICLEID AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0									
										UPDATE TOP(@CAPACITY) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL																															
									END
									
--REMAINING EMPLOYEES LESS THAN AVAILABLE VEHICLE CAPACITY	
								ELSE
									BEGIN
										SET @ROUTE2LONGLOC=NULL
										SET @ROUTE2LONGLOCEMPS=NULL 										
										SELECT TOP 1  @ROUTE2LONGLOC=LocalityId,@ROUTE2LONGLOCEMPS=NoOfEmps FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND LocalityId !=@LOCALITYID AND RouteStatus IS NULL ORDER BY  Distance DESC											
								
									IF(@ROUTE2LONGLOC IS NOT NULL)
										BEGIN
	
--NUMBER OF EMPS IN FIRST LOCALITY+NUMBER OF EMPS IN SECOND LOCALITY >=AVAILABLE VEHICLE CAPACITY		
				
												IF((@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)>=@CAPACITY)
													BEGIN																																			
														INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy) VALUES(@ROUTEID,@ROUTE2LONGLOC,@VEHICLEID,(@CAPACITY/(@CAPACITY*1.00)*100)) 
														UPDATE @tblRouteAssignment SET NoOfEmps=0,PickedEmps=@LOCALTYNOEMPS WHERE  RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
														UPDATE @tblRouteAssignment SET NoOfEmps=(@ROUTE2LONGLOCEMPS-(@CAPACITY-@LOCALTYNOEMPS)),PickedEmps=(@CAPACITY-@LOCALTYNOEMPS) WHERE  RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC   
														UPDATE rvlfVehicleMaster SET Allocated=1 WHERE VehicleId=@VEHICLEID AND Allocated=0	AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0																	
														UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
														UPDATE TOP(@CAPACITY-@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL														
														
														IF((@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)=@CAPACITY)
															BEGIN
																UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus IS NULL				
																UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus IS NULL				
															END
														ELSE
															BEGIN
																UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus IS NULL								
															END		
													END
											
--NUMBER OF EMPS IN FIRST LOCALITY+NUMBER OF EMPS IN SECOND LOCALITY< AVAILABLE VEHICLE CAPACITY					
							
										ELSE IF((@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)<@CAPACITY)
											BEGIN											
												DECLARE @TOTREMAININGEMPS INT
												SET @TOTREMAININGEMPS=(@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)												
												IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)>=75 AND ((@TOTREMAININGEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
													BEGIN														
														SET @VEHICLEID =NULL									
														SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)>=75 AND ((@TOTREMAININGEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
														INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@TOTREMAININGEMPS/(@CAPACITY*1.00)*100))
														UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0													
														UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
														UPDATE TOP(@ROUTE2LONGLOCEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
														UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus IS NULL
														UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus IS NULL
													END
												ELSE IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
													BEGIN
														--SET @VEHICLEID =NULL
														
														--SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE Capacity=(SELECT MIN(Capacity) FROM rvlfVehicleMaster WHERE Allocated=0)AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
														--IF(@VEHICLEID IS NULL)
														--	BEGIN
														--		UPDATE @tblRouteAssignment SET RouteStatus='NOVEHICLE' WHERE RouteId=@ROUTEID 	
														--	END
														--ELSE
														--	BEGIN														
														--		INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@TOTREMAININGEMPS/(@CAPACITY*1.00)*100))
														--		UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID  AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0															
														--		UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL																
														--		UPDATE TOP(@ROUTE2LONGLOCEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
														--		UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus IS NULL
														--		UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus IS NULL
														UPDATE @tblRouteAssignment SET LowRoute=@LOWROUTE,RouteStatus='LowRoute' WHERE  RouteId=@ROUTEID AND (RouteStatus IS NULL OR RouteStatus='CLOSED') AND LocalityId=@ROUTE2LONGLOC	
														UPDATE @tblRouteAssignment SET LowRoute=@LOWROUTE,RouteStatus='LowRoute' WHERE  RouteId=@ROUTEID AND (RouteStatus IS NULL OR RouteStatus='CLOSED') AND LocalityId=@LOCALITYID 
												
														--	END
													END
											END
											END
									ELSE
										BEGIN
											IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)>=75 AND ((@LOCALTYNOEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
												BEGIN
													SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)>=75 AND ((@LOCALTYNOEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
													INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy)VALUES(@ROUTEID,@LOCALITYID,@VEHICLEID,(@LOCALTYNOEMPS/(@CAPACITY*1.00)*100))
													UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
													UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
													UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
												END
											ELSE IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0) 
												BEGIN
													SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0 order by Capacity 		
												
													IF(@VEHICLEID IS NULL)
														BEGIN
															UPDATE @tblRouteAssignment SET RouteStatus='NOVEHICLE' WHERE RouteId=@ROUTEID 	
														END
													ELSE
														BEGIN
															INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy)VALUES(@ROUTEID,@LOCALITYID,@VEHICLEID,(@LOCALTYNOEMPS/(@CAPACITY*1.00)*100))
															UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
															UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
															UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
														END
												END
										END	
									END
							END
					END
--CASE 4					
--THE FIRST LOCALITY TOTAL NUMBER OF EMPLOYEES ARE LESS THE AVAILABLE VEHICLE CAPACITY
					
				ELSE IF(@LOCALTYNOEMPS<(SELECT MAX(CAPACITY) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0))
					BEGIN	
								
						SET @ROUTE2LONGLOC=NULL
						SET @ROUTE2LONGLOCEMPS=NULL 
						SELECT TOP 1 @ROUTE2LONGLOC=LocalityId,@ROUTE2LONGLOCEMPS=NoOfEmps FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND RouteStatus IS NULL AND LocalityId !=@LOCALITYID ORDER BY  Distance DESC																								

							IF(@ROUTE2LONGLOC IS NOT NULL)
								BEGIN
									SET @VEHICLEID =NULL
									SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster 
							WHERE Allocated=0 AND Capacity IN(SELECT MAX(CAPACITY) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0) 				
											
--NUMBER OF EMPS IN FIRST LOCALITY+NUMBER OF EMPS IN SECOND LOCALITY >=AVAILABLE VEHICLE CAPACITY	
				 
							IF((@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)>=@CAPACITY)
							BEGIN			
								INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy) VALUES(@ROUTEID,@ROUTE2LONGLOC,@VEHICLEID,(@CAPACITY/(@CAPACITY*1.00)*100)) 
								UPDATE @tblRouteAssignment SET NoOfEmps=0,PickedEmps=@LOCALTYNOEMPS WHERE  RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
								UPDATE @tblRouteAssignment SET NoOfEmps=(@ROUTE2LONGLOCEMPS-(@CAPACITY-@LOCALTYNOEMPS)),PickedEmps=(@CAPACITY-@LOCALTYNOEMPS) WHERE  RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC   
								UPDATE rvlfVehicleMaster SET Allocated=1 WHERE VehicleId=@VEHICLEID AND Allocated=0	AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0										
								UPDATE TOP(@CAPACITY) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
								UPDATE TOP(@CAPACITY-@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
								IF((@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)=@CAPACITY)
									BEGIN
										UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus IS NULL				
										UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus IS NULL				
									END
								ELSE
									BEGIN
										UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus IS NULL								
									END								
							END
											
--NUMBER OF EMPS IN FIRST LOCALITY+NUMBER OF EMPS IN SECOND LOCALITY< AVAILABLE VEHICLE CAPACITY					
							
						ELSE IF((@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)<@CAPACITY)							
							BEGIN
								SET @TOTREMAININGEMPS=(@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)
								IF EXISTS(SELECT * FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)>=75 AND ((@TOTREMAININGEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
									BEGIN		
										SET @VEHICLEID =NULL								
										SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)>=75 AND ((@TOTREMAININGEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
										INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@TOTREMAININGEMPS/(@CAPACITY*1.00)*100))
										UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
										UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
										UPDATE TOP(@ROUTE2LONGLOCEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
										UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus IS NULL
										UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus IS NULL
									END
								ELSE IF EXISTS(SELECT * FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
									BEGIN
										SET @VEHICLEID =NULL
										--SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
										--SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE Capacity=(SELECT MIN(Capacity) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0 )AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0																					
										--IF(@VEHICLEID IS NULL)
										--	BEGIN
										--		UPDATE @tblRouteAssignment SET RouteStatus='NOVEHICLE' WHERE RouteId=@ROUTEID 	
										--	END
										--ELSE
										--	BEGIN											
												--INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@TOTREMAININGEMPS/(@CAPACITY*1.00)*100))
												--UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
												--UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
												--UPDATE TOP(@ROUTE2LONGLOCEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
												--UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus IS NULL
												--UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus IS NULL																							
												UPDATE @tblRouteAssignment SET LowRoute=@LOWROUTE,RouteStatus='LowRoute' WHERE  RouteId=@ROUTEID AND (RouteStatus IS NULL OR RouteStatus='CLOSED') AND LocalityId=@ROUTE2LONGLOC	
												UPDATE @tblRouteAssignment SET LowRoute=@LOWROUTE,RouteStatus='LowRoute' WHERE  RouteId=@ROUTEID AND (RouteStatus IS NULL OR RouteStatus='CLOSED') AND LocalityId=@LOCALITYID 
												
											--END
									END							
							END
								END	
							ELSE
								BEGIN
									IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)>=75 AND ((@LOCALTYNOEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
										BEGIN
											SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)>=75 AND ((@LOCALTYNOEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
											INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy)VALUES(@ROUTEID,@LOCALITYID,@VEHICLEID,(@LOCALTYNOEMPS/(@CAPACITY*1.00)*100))
											UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
											UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
											UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
										END
									ELSE IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0) 
										BEGIN
											SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0 order by Capacity 		
										
											IF(@VEHICLEID IS NULL)
												BEGIN
													UPDATE @tblRouteAssignment SET RouteStatus='NOVEHICLE' WHERE RouteId=@ROUTEID 	
												END
											ELSE
												BEGIN
													INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy)VALUES(@ROUTEID,@LOCALITYID,@VEHICLEID,(@LOCALTYNOEMPS/(@CAPACITY*1.00)*100))
													UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
													UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
													UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
												END
										END
								END
					END	
				END
		END	

END

UPDATE @tblRouteAssignment SET RouteStatus='LowRoute' WHERE LowRoute=1
UPDATE @tblRouteAssignment SET RouteId=34 where (RouteStatus='LowRoute') AND LowRoute =1

---------------------------ASSIGN VEHICLES TO LOW ROUTE EMPLOYEES-------------------------------------------------	

	WHILE EXISTS(SELECT * FROM @tblRouteAssignment WHERE RouteStatus='LowRoute' AND LowRoute !=0)
		BEGIN	


			SET @ROUTEID=NULL
			SET @CAPACITY=NULL
			SET @VEHICLEID =NULL 
			SET @LOCALITYID =NULL
			SET @NOOFEMPS=NULL
			SET @LOCALTYNOEMPS=NULL	
			SET @ROUTE2LONGLOC=NULL
			SET @ROUTE2LONGLOCEMPS=NULL	
																	
			SELECT TOP 1 @ROUTEID=RouteId FROM @tblRouteAssignment WHERE RouteStatus='LowRoute' AND LowRoute =1	 AND Distance IN(SELECT MAX(Distance) FROM @tblRouteAssignment WHERE RouteStatus='LowRoute' AND LowRoute =1	)
			SELECT @NOOFEMPS=SUM(NoOfEmps)FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND RouteStatus='LowRoute' AND LowRoute =1 GROUP BY RouteId
			SELECT TOP 1 @LOCALITYID=LocalityId FROM @tblRouteAssignment WHERE RouteStatus='LowRoute' AND LowRoute =1 AND RouteId=@ROUTEID 
	
		IF NOT EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE Allocated=0 AND  InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
			BEGIN
				UPDATE @tblRouteAssignment SET RouteStatus='NO VEHICLE' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID 
			END
		ELSE
			BEGIN	
	
			IF(@NOOFEMPS<=(SELECT MAX(Capacity) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0))
				BEGIN
					IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE Capacity=@NOOFEMPS AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
						BEGIN
							SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE Capacity=@NOOFEMPS AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
							INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@NOOFEMPS/(@CAPACITY*1.00)*100))
							UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
							UPDATE @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId IN (SELECT LocalityId  FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND RouteStatus='LowRoute' AND LowRoute =1) AND AssignedVehicle IS NULL
							UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID 
						END
					ELSE IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@NOOFEMPS /(Capacity*1.00))*100)>=75 AND ((@NOOFEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
						BEGIN
							
							SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@NOOFEMPS /(Capacity*1.00))*100)>=75 AND ((@NOOFEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
							INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@NOOFEMPS/(@CAPACITY*1.00)*100))
							UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
							UPDATE @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId IN (SELECT LocalityId  FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND RouteStatus='LowRoute' AND LowRoute =1) AND AssignedVehicle IS NULL
							UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID 
						END
					ELSE IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@NOOFEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0) 
						BEGIN
							SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@NOOFEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0 order by Capacity 		
						
							IF(@VEHICLEID IS NULL)
								BEGIN
									UPDATE @tblRouteAssignment SET RouteStatus='NOVEHICLE' WHERE RouteId=@ROUTEID 	
								END
							ELSE
								BEGIN
									INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@NOOFEMPS/(@CAPACITY*1.00)*100))
									UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
									UPDATE @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId IN (SELECT LocalityId  FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND RouteStatus='LowRoute' AND LowRoute =1) AND AssignedVehicle IS NULL
									UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID 
								
								END
						END
				END
		
--CASE2:-THE NUMBER OF EMPLOYEES GREATER THAN AVAILABLE VEHICLE CAPACITY
--		 SO FIND THE LONGEST LOCALITY FROM THE OFFICE AND ASSIGN THE VEHICLE TO THAT LOCALITY.	

--		 LOCALITY WISE TOTAL NUMBER OF EMPLOYEES = AVAILABLE VEHICLE CAPACITY
		
			IF(@NOOFEMPS>(SELECT MAX(Capacity) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0))
				BEGIN
				
					SET @LOCALITYID=NULL
					SET @LOCALTYNOEMPS=NULL
					SELECT TOP 1 @LOCALITYID=LocalityId,@LOCALTYNOEMPS=NoOfEmps FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND RouteStatus='LowRoute' AND LowRoute =1 ORDER BY Distance DESC 
					
					IF EXISTS(SELECT * FROM rvlfVehicleMaster WHERE Capacity=@LOCALTYNOEMPS AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
					BEGIN						
						SET @VEHICLEID=NULL
						SET @CAPACITY=NULL										
						SELECT @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE Capacity=@LOCALTYNOEMPS AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
						INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@CAPACITY/(@CAPACITY*1.00)*100))
						UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
						UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
						UPDATE TOP(@CAPACITY) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
			
					END
--CASE 3:
--		 LOCALITY WISE TOTAL NUMBER OF EMPLOYEES > AVAILABLE VEHICLE CAPACITY

				ELSE IF(@LOCALTYNOEMPS>(SELECT MAX(CAPACITY) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0))
					BEGIN	
										
						SET @VEHICLEID =NULL
						SET @CAPACITY=NULL
						SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster 
							WHERE Allocated=0 AND Capacity IN(SELECT MAX(CAPACITY) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0) AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
																								
						INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy) 
							VALUES(@ROUTEID,@LOCALITYID,@VEHICLEID,(@CAPACITY/(@CAPACITY*1.00)*100)) 
						UPDATE @tblRouteAssignment SET NoOfEmps=(@LOCALTYNOEMPS-@CAPACITY),PickedEmps=@CAPACITY WHERE  RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
						UPDATE rvlfVehicleMaster SET Allocated=1 WHERE VehicleId=@VEHICLEID AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
						UPDATE TOP(@CAPACITY) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL													
						SELECT @LOCALTYNOEMPS=NoOfEmps FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID   
						SET @VEHICLEID =NULL
						SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster 
							WHERE Allocated=0 AND Capacity IN(SELECT MAX(CAPACITY) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0) AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
					
			 		

--REMAINING EMPLOYEES GREATER THAN AVAILABLE VEHICLE CAPACITY		
						
						IF(@VEHICLEID IS NULL)
							BEGIN
								UPDATE @tblRouteAssignment SET  RouteStatus='VEHICLENOTAVAILABLE' WHERE  RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
							END
						ELSE IF((SELECT SUM(NoOfEmps) FROM @tblRouteAssignment WHERE RouteId=@ROUTEID)>(SELECT MAX(Capacity) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0))  
							BEGIN
								
								IF(@LOCALTYNOEMPS>=@CAPACITY)
									BEGIN	
																
										INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy) VALUES(@ROUTEID,@LOCALITYID,@VEHICLEID,(@CAPACITY/(@CAPACITY*1.00)*100)) 
										UPDATE @tblRouteAssignment SET NoOfEmps=(@LOCALTYNOEMPS-@CAPACITY),PickedEmps=@CAPACITY WHERE  RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
										UPDATE rvlfVehicleMaster SET Allocated=1 WHERE VehicleId=@VEHICLEID AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0										
										UPDATE TOP(@CAPACITY) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL																															
									END
									
--REMAINING EMPLOYEES LESS THAN AVAILABLE VEHICLE CAPACITY	
								ELSE
									BEGIN
										SET @ROUTE2LONGLOC=NULL
										SET @ROUTE2LONGLOCEMPS=NULL 										
										SELECT TOP 1 @ROUTE2LONGLOC=LocalityId,@ROUTE2LONGLOCEMPS=NoOfEmps FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND LocalityId !=@LOCALITYID AND RouteStatus ='LowRoute'								
										
									IF(@ROUTE2LONGLOC IS NOT NULL)
										BEGIN
	
--NUMBER OF EMPS IN FIRST LOCALITY+NUMBER OF EMPS IN SECOND LOCALITY >=AVAILABLE VEHICLE CAPACITY		
				
												IF((@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)>=@CAPACITY)
													BEGIN																																			
														INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy) VALUES(@ROUTEID,@ROUTE2LONGLOC,@VEHICLEID,(@CAPACITY/(@CAPACITY*1.00)*100)) 
														UPDATE @tblRouteAssignment SET NoOfEmps=0,PickedEmps=@LOCALTYNOEMPS WHERE  RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
														UPDATE @tblRouteAssignment SET NoOfEmps=(@ROUTE2LONGLOCEMPS-(@CAPACITY-@LOCALTYNOEMPS)),PickedEmps=(@CAPACITY-@LOCALTYNOEMPS) WHERE  RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC   
														UPDATE rvlfVehicleMaster SET Allocated=1 WHERE VehicleId=@VEHICLEID AND Allocated=0	AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0																	
														UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
														UPDATE TOP(@CAPACITY-@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
														IF((@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)=@CAPACITY)
															BEGIN
																UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus='LowRoute'				
																UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus='LowRoute'				
															END
														ELSE
															BEGIN
																UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus IS NULL								
															END		
													END
											
--NUMBER OF EMPS IN FIRST LOCALITY+NUMBER OF EMPS IN SECOND LOCALITY< AVAILABLE VEHICLE CAPACITY					
							
										ELSE IF((@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)<@CAPACITY)
											BEGIN											
												SET @TOTREMAININGEMPS =0
												SET @TOTREMAININGEMPS=(@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)												
												IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)>=75 AND ((@TOTREMAININGEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
													BEGIN														
														SET @VEHICLEID =NULL									
														SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)>=75 AND ((@TOTREMAININGEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
														INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@TOTREMAININGEMPS/(@CAPACITY*1.00)*100))
														UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0											
														UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
														UPDATE TOP(@ROUTE2LONGLOCEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
														UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus='LowRoute' AND LowRoute =1
														UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus='LowRoute' AND LowRoute =1
													END
												ELSE IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
													BEGIN
														SET @VEHICLEID =NULL
														SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0 order by Capacity 		
														IF(@VEHICLEID IS NULL)
															BEGIN
																UPDATE @tblRouteAssignment SET RouteStatus='NOVEHICLE' WHERE RouteId=@ROUTEID 	
															END
														ELSE
															BEGIN														
																--INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@TOTREMAININGEMPS/(@CAPACITY*1.00)*100))
																--UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID  AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0																					
																--UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
																--UPDATE TOP(@ROUTE2LONGLOCEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
																--UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus='LowRoute' AND LowRoute =1
																--UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus='LowRoute' AND LowRoute =1
																UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
																UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
																UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus='LowRoute' AND LowRoute =1
																WHILE EXISTS(SELECT * FROM @tblRouteAssignment WHERE RouteId=@ROUTEID)
																	BEGIN 													
																		UPDATE TOP(@ROUTE2LONGLOCEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
																		UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus='LowRoute' AND LowRoute =1
																		IF((@TOTREMAININGEMPS/(@CAPACITY*1.00)*100)<100)
																			BEGIN
																				SELECT @ROUTE2LONGLOC=LocalityId,@ROUTE2LONGLOCEMPS=NoOfEmps FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND LocalityId !=@LOCALITYID AND RouteStatus ='LowRoute'										
																				SET @TOTREMAININGEMPS=@TOTREMAININGEMPS+@ROUTE2LONGLOCEMPS 	
																				IF((@TOTREMAININGEMPS/(@CAPACITY*1.00)*100)>100)
																					BEGIN
																						SET @TOTREMAININGEMPS=@TOTREMAININGEMPS-@ROUTE2LONGLOCEMPS 
																						BREAK																														
																					END
																			END
																		ELSE
																			BEGIN
																				UPDATE TOP(@ROUTE2LONGLOCEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
																				UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus='LowRoute' AND LowRoute =1
																				BREAK
																			END															
																	END																																				
																INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@TOTREMAININGEMPS/(@CAPACITY*1.00)*100))
															END
													END
											END
											END
									ELSE
										BEGIN
											IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)>=75 AND ((@LOCALTYNOEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
												BEGIN
													SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)>=75 AND ((@LOCALTYNOEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
													INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy)VALUES(@ROUTEID,@LOCALITYID,@VEHICLEID,(@LOCALTYNOEMPS/(@CAPACITY*1.00)*100))
													UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
													UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
													UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
												END
											ELSE IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0) 
												BEGIN
													SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0 order by Capacity 		
												
													IF(@VEHICLEID IS NULL)
														BEGIN
															UPDATE @tblRouteAssignment SET RouteStatus='NOVEHICLE' WHERE RouteId=@ROUTEID 	
														END
													ELSE
														BEGIN
															INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy)VALUES(@ROUTEID,@LOCALITYID,@VEHICLEID,(@LOCALTYNOEMPS/(@CAPACITY*1.00)*100))
															UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
															UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
															UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
														END
												END
										END	
									END
							END
					END
--CASE 4					
--THE FIRST LOCALITY TOTAL NUMBER OF EMPLOYEES ARE LESS THE AVAILABLE VEHICLE CAPACITY
					
				ELSE IF(@LOCALTYNOEMPS<(SELECT MAX(CAPACITY) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0))
					BEGIN						
						SET @ROUTE2LONGLOC=NULL
						SET @ROUTE2LONGLOCEMPS=NULL 
						SELECT @ROUTE2LONGLOC=LocalityId,@ROUTE2LONGLOCEMPS=NoOfEmps FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND LocalityId !=@LOCALITYID AND RouteStatus ='LowRoute'										
						
							IF(@ROUTE2LONGLOC IS NOT NULL)
								BEGIN
									SET @VEHICLEID =NULL
									SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster 
							WHERE Allocated=0 AND Capacity IN(SELECT MAX(CAPACITY) FROM rvlfVehicleMaster WHERE Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0) 				
						
--NUMBER OF EMPS IN FIRST LOCALITY+NUMBER OF EMPS IN SECOND LOCALITY >=AVAILABLE VEHICLE CAPACITY	
				 
						IF((@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)>=@CAPACITY)
							BEGIN
								INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy) VALUES(@ROUTEID,@ROUTE2LONGLOC,@VEHICLEID,(@CAPACITY/(@CAPACITY*1.00)*100)) 
								UPDATE @tblRouteAssignment SET NoOfEmps=0,PickedEmps=@LOCALTYNOEMPS WHERE  RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
								UPDATE @tblRouteAssignment SET NoOfEmps=(@ROUTE2LONGLOCEMPS-(@CAPACITY-@LOCALTYNOEMPS)),PickedEmps=(@CAPACITY-@LOCALTYNOEMPS) WHERE  RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC   
								UPDATE rvlfVehicleMaster SET Allocated=1 WHERE VehicleId=@VEHICLEID AND Allocated=0	AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0										
								UPDATE TOP(@CAPACITY) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
								UPDATE TOP(@CAPACITY-@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL								
								IF((@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)=@CAPACITY)
									BEGIN
										UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus='LowRoute'				
										UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus='LowRoute'				
									END
								ELSE
									BEGIN
										UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus IS NULL								
									END	
							END
											
--NUMBER OF EMPS IN FIRST LOCALITY+NUMBER OF EMPS IN SECOND LOCALITY< AVAILABLE VEHICLE CAPACITY					
							
						ELSE IF((@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)<@CAPACITY)							
							BEGIN
								SET @TOTREMAININGEMPS=(@LOCALTYNOEMPS+@ROUTE2LONGLOCEMPS)
								IF EXISTS(SELECT * FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)>=75 AND ((@TOTREMAININGEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
									BEGIN		
										SET @VEHICLEID =NULL								
										SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)>=75 AND ((@TOTREMAININGEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
										INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@TOTREMAININGEMPS/(@CAPACITY*1.00)*100))
										UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
										UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
										UPDATE TOP(@ROUTE2LONGLOCEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
										UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus='LowRoute' AND LowRoute =1
										UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus='LowRoute' AND LowRoute =1
									END
								ELSE IF EXISTS(SELECT * FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
									BEGIN
										SET @VEHICLEID =NULL
										SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@TOTREMAININGEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0 order by Capacity 			 								
										IF(@VEHICLEID IS NULL)
											BEGIN
												UPDATE @tblRouteAssignment SET RouteStatus='NOVEHICLE' WHERE RouteId=@ROUTEID 	
											END
										ELSE
											BEGIN																								
												UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
												UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
												UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID AND RouteStatus='LowRoute' AND LowRoute =1
												WHILE EXISTS(SELECT * FROM @tblRouteAssignment WHERE RouteId=@ROUTEID)
													BEGIN 													
														UPDATE TOP(@ROUTE2LONGLOCEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
														UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus='LowRoute' AND LowRoute =1
														IF((@TOTREMAININGEMPS/(@CAPACITY*1.00)*100)<100)
															BEGIN
																SELECT @ROUTE2LONGLOC=LocalityId,@ROUTE2LONGLOCEMPS=NoOfEmps FROM @tblRouteAssignment WHERE RouteId=@ROUTEID AND LocalityId !=@LOCALITYID AND RouteStatus ='LowRoute'										
																SET @TOTREMAININGEMPS=@TOTREMAININGEMPS+@ROUTE2LONGLOCEMPS 	
																IF((@TOTREMAININGEMPS/(@CAPACITY*1.00)*100)>100)
																	BEGIN
																		SET @TOTREMAININGEMPS=@TOTREMAININGEMPS-@ROUTE2LONGLOCEMPS 
																		BREAK																														
																	END
															END
														ELSE
															BEGIN
																UPDATE TOP(@ROUTE2LONGLOCEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@ROUTE2LONGLOC AND AssignedVehicle IS NULL
																UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@ROUTE2LONGLOC AND RouteStatus='LowRoute' AND LowRoute =1
																BREAK
															END															
													END																																				
												INSERT INTO @tblVehicleAssignment(RouteId,VehicleId,Occupancy)VALUES(@ROUTEID,@VEHICLEID,(@TOTREMAININGEMPS/(@CAPACITY*1.00)*100))
											END
									END							
							END
								END	
							ELSE
								BEGIN
									IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)>=75 AND ((@LOCALTYNOEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0)
										BEGIN
											SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)>=75 AND ((@LOCALTYNOEMPS/(Capacity*1.00))*100)<100 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
											INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy)VALUES(@ROUTEID,@LOCALITYID,@VEHICLEID,(@LOCALTYNOEMPS/(@CAPACITY*1.00)*100))
											UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
											UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
											UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
										END
									ELSE IF EXISTS(SELECT VehicleId FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0) 
										BEGIN
											SELECT TOP 1 @VEHICLEID=VehicleId,@CAPACITY=Capacity FROM rvlfVehicleMaster WHERE ((@LOCALTYNOEMPS /(Capacity*1.00))*100)<75 AND Allocated=0 AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0 order by Capacity 		
										
											IF(@VEHICLEID IS NULL)
												BEGIN
													UPDATE @tblRouteAssignment SET RouteStatus='NOVEHICLE' WHERE RouteId=@ROUTEID 	
												END
											ELSE
												BEGIN
													INSERT INTO @tblVehicleAssignment(RouteId,LocalityId,VehicleId,Occupancy)VALUES(@ROUTEID,@LOCALITYID,@VEHICLEID,(@LOCALTYNOEMPS/(@CAPACITY*1.00)*100))
													UPDATE rvlfVehicleMaster SET Allocated=1 WHERE Capacity=@CAPACITY  AND Allocated=0 AND VehicleId=@VEHICLEID AND InsuranceValidityDate >= GETDATE() AND PermitValidityDate >=GETDATE() AND Capacity>0
													UPDATE TOP(@LOCALTYNOEMPS) @tblEmployeeList SET AssignedVehicle=@VEHICLEID WHERE LocalityId =@LOCALITYID AND AssignedVehicle IS NULL
													UPDATE @tblRouteAssignment SET RouteStatus='CLOSED' WHERE RouteId=@ROUTEID AND LocalityId=@LOCALITYID  
												END
										END
								END
					END	
				END
		END	

		END
	
------------------------------------------------------------------------------------------------------------------

DECLARE @EMPID BIGINT=NULL
DECLARE @COST NUMERIC(10,2)=NULL
DECLARE @SECONDEMPID BIGINT=NULL
DECLARE @DUPLICATEEMPID BIGINT=NULL
DECLARE @SEQINC INT=0
DECLARE @DUPVEHICLEID BIGINT=NULL

------------FIND THE DISTANCE BETWEEN EACH EMPLOYEE IN THE VEHICLE AND FIND THE PICKUP TIME------------------------
--WHILE EXISTS(SELECT EmployeeID FROM @tblEmployeeList WHERE EmpDistance IS NULL AND AssignedVehicle IS NOT NULL)
--	BEGIN
--		SET @EMPID=NULL
--		SET @SECONDEMPID=NULL
--		SET @fromLat=NULL
--		SET @fromLng=NULL
--		SET @toLat=NULL
--		SET @toLng=NULL
--		SET @dist=NULL
		
--		SELECT TOP 1 @EMPID=EmployeeID,@fromLat=ToLatitude,@fromLng=ToLongitude,@dist=Distance,@VEHICLEID=AssignedVehicle FROM @tblEmployeeList WHERE EmpDistance IS NULL AND AssignedVehicle IS NOT NULL ORDER BY AssignedVehicle ASC,Distance DESC
--		UPDATE @tblEmployeeList SET EmpDistance=@dist WHERE EmployeeID=@EMPID AND EmpDistance IS NULL AND AssignedVehicle IS NOT NULL
	
--		WHILE EXISTS(SELECT EmployeeID FROM @tblEmployeeList WHERE EmpDistance IS NULL AND AssignedVehicle IS NOT NULL AND AssignedVehicle=@VEHICLEID)
--			BEGIN				
				
--				SELECT TOP 1 @SECONDEMPID=EmployeeID,@toLat=ToLatitude,@toLng=ToLongitude FROM @tblEmployeeList WHERE EmpDistance IS NULL AND AssignedVehicle=@VEHICLEID AND AssignedVehicle IS NOT NULL ORDER BY AssignedVehicle ASC,Distance DESC
				
--				SET @dist  = (MIN(DEGREES(ACOS((SIN(RADIANS(@fromLat)) * 
--				  SIN(RADIANS(@toLat)) +
--				  COS(RADIANS(@fromLat)) *
--				  COS(RADIANS(@toLat)) *
--				  COS(RADIANS(@fromLng - @toLng)))))) * 69.09 * 1.609344)
	
--				IF(@dist IS NULL)
--					SET @dist=0		  
--				 UPDATE @tblEmployeeList SET EmpDistance=@dist WHERE EmployeeID=@SECONDEMPID AND EmpDistance IS NULL AND AssignedVehicle IS NOT NULL
				
--				SET @fromLat=@toLat 
--				SET @fromLng=@toLng 
																 
--			END						
--	END
---------------------------------------------------------------------------------------------------------------------

------------------------------------FIND THE PICKUP TIME ----------------------------------------------------------

DECLARE @PECKTIMEKMSPERHRS NUMERIC(5,2)
DECLARE @NONPECKTIMEKMSPERHRS NUMERIC(5,2)
DECLARE @PECKTIMEMINUTESPERKM NUMERIC(5,2)
DECLARE @NONPECKTIMEMINUTESPERKM NUMERIC(5,2)
DECLARE @MORNINGPEAKFROMTIME TIME(7)
DECLARE @MORNINGPEAKTOTIME TIME(7)
DECLARE @EVENINGPEAKFROMTIME TIME(7)
DECLARE @EVENINGPEAKTOTIME TIME(7)
DECLARE @PICKUPTIME TIME(7)

SELECT @MORNINGPEAKFROMTIME=OL.MorningPeakFromTime,@MORNINGPEAKTOTIME=OL.MorningPeakToTime,
	@EVENINGPEAKFROMTIME=OL.EveningPeakFromTime,@EVENINGPEAKTOTIME=OL.EveningPeakToTime,
	@PECKTIMEMINUTESPERKM=OL.PeakTimeMinutesPerKM,@NONPECKTIMEMINUTESPERKM=OL.NonPeakTimeMinutesPerKM    
   FROM rvlfOfficeAddress OA 
	INNER JOIN rvlfOfficeLocation OL ON OL.LocationId=OA.LocationId 
   WHERE OA.AddressId=@bigBranchId 	

SET @PECKTIMEKMSPERHRS =(60/@PECKTIMEMINUTESPERKM)
SET @NONPECKTIMEKMSPERHRS=(60/@NONPECKTIMEMINUTESPERKM)

--WHILE EXISTS(SELECT EmployeeID FROM @tblEmployeeList WHERE EmpDistance IS NOT NULL AND AssignedVehicle IS NOT NULL AND VehicleStartTime  IS NULL)
--	BEGIN
--		SET @EMPID=NULL
--		SET @dist=NULL		
--		SET @VEHICLEID =NULL	
--		SET @fromLat =NULL
--		SET @fromLng =NULL
--		SET @toLat=NULL
--		SET @toLng=NULL
--		SET @PICKUPTIME=NULL
--		SELECT TOP 1 @VEHICLEID=AssignedVehicle FROM @tblEmployeeList WHERE EmpDistance IS NOT NULL AND AssignedVehicle IS NOT NULL AND VehicleStartTime IS NULL ORDER BY AssignedVehicle ASC,Distance DESC
--		SELECT @dist=SUM(EmpDistance) FROM @tblEmployeeList WHERE AssignedVehicle=@VEHICLEID GROUP BY AssignedVehicle 
--		SELECT @fromLat=ToLatitude,@fromLng=ToLongitude,@toLat=FromLatitude,@toLng=FromLongitude FROM @tblEmployeeList WHERE AssignedVehicle=@VEHICLEID ORDER BY Distance DESC

----FIND THE TOTTAL UP AND DOWN DISTANCE FROM OFFICE AND VEHICLE START TIME

--		SET @dist  =@dist + (MIN(DEGREES(ACOS((SIN(RADIANS(@fromLat)) * 
--				  SIN(RADIANS(@toLat)) +
--				  COS(RADIANS(@fromLat)) *
--				  COS(RADIANS(@toLat)) *
--				  COS(RADIANS(@fromLng - @toLng)))))) * 69.09 * 1.609344)
				  
--		UPDATE @tblEmployeeList SET VehicleStartTime=DATEADD(MI,-CEILING((@dist/@PECKTIMEKMSPERHRS)*60),@dtShiftin)	WHERE AssignedVehicle=@VEHICLEID AND VehicleStartTime IS NULL			  
		
--		SET @PICKUPTIME=DATEADD(MI,-CEILING((@dist/@PECKTIMEKMSPERHRS)*60),@dtShiftin)

----FIND THE PICKUP TIME 		
		
--		WHILE EXISTS(SELECT EmployeeID FROM @tblEmployeeList WHERE PickupTime IS NULL AND AssignedVehicle=@VEHICLEID)
--			BEGIN
--				SET @EMPID=NULL
--				SET @dist=NULL	
			
--				SELECT TOP 1 @EMPID=EmployeeID,@dist=EmpDistance FROM @tblEmployeeList WHERE PickupTime IS NULL AND AssignedVehicle=@VEHICLEID ORDER BY AssignedVehicle ASC,EMPDistance DESC			
--				IF(((@dtShiftin>=@MORNINGPEAKFROMTIME) AND (@dtShiftin<=@MORNINGPEAKTOTIME)) OR ((@dtShiftin>=@EVENINGPEAKFROMTIME) AND (@dtShiftin<=@EVENINGPEAKTOTIME ))) 
--					BEGIN										
--						UPDATE @tblEmployeeList SET PickupTime=DATEADD(MI,+CEILING((@dist/@PECKTIMEKMSPERHRS)*60),@PICKUPTIME) WHERE EmployeeID=@EMPID AND AssignedVehicle=@VEHICLEID AND PickupTime IS NULL
--						SET @PICKUPTIME=DATEADD(MI,+CEILING((@dist/@PECKTIMEKMSPERHRS)*60),@PICKUPTIME)
--					END
--				ELSE
--					BEGIN
--						UPDATE @tblEmployeeList SET PickupTime=DATEADD(MI,+CEILING((@dist/@NONPECKTIMEKMSPERHRS)*60),@PICKUPTIME)WHERE EmployeeID=@EMPID AND AssignedVehicle=@VEHICLEID AND PickupTime IS NULL
--						SET @PICKUPTIME=DATEADD(MI,+CEILING((@dist/@NONPECKTIMEKMSPERHRS)*60),@PICKUPTIME)
--					END
				
--			END	
--	END
---------------------------------------------------------------------------------------------------------------------

--UPDATE SEQUENCE NO

WHILE EXISTS(SELECT * FROM @tblEmployeeList WHERE sequenceNo IS NULL AND AssignedVehicle IS NOT NULL)
BEGIN
	SET @VEHICLEID=NULL
	SET @EMPID=NULL 
	SELECT TOP 1 @VEHICLEID=AssignedVehicle,@EMPID=EmployeeID  FROM @tblEmployeeList WHERE sequenceNo IS NULL AND AssignedVehicle IS NOT NULL ORDER BY AssignedVehicle ASC,PickupTime ASC 	

	IF(@DUPVEHICLEID IS NULL)
		BEGIN
			SET @DUPVEHICLEID=@VEHICLEID 
		END
	ELSE IF(@DUPVEHICLEID=@VEHICLEID)
		BEGIN
			SET @SEQINC=@SEQINC+1
		END
	ELSE
		BEGIN
			SET @SEQINC=0
			SET @DUPVEHICLEID=@VEHICLEID 
		END
	UPDATE @tblEmployeeList SET sequenceNo=@SEQINC WHERE EmployeeID=@EMPID AND AssignedVehicle=@VEHICLEID 		
END

--UPDATE THE LOCALITY MASTER

WHILE EXISTS(SELECT * FROM @tblRouteAssignment WHERE RouteStatus='CLOSED')
	BEGIN
		SET @LOCALITYID=NULL 
		SET @COST=NULL
		SET @ROUTEID=NULL
		SELECT @ROUTEID=RA.RouteId ,@LOCALITYID=RA.LocalityId
			FROM @tblRouteAssignment RA 
				INNER JOIN @tblEmployeeList EL ON EL.LocalityId=RA.LocalityId 
			WHERE RouteStatus='CLOSED' 
			GROUP BY RA.LocalityId,RA.RouteId			
		UPDATE rvlfLocalityMaster SET ALLOCATED=1 WHERE LocalityId=@LOCALITYID 
		UPDATE @tblRouteAssignment SET RouteStatus='ASSIGNED' WHERE LocalityId=@LOCALITYID AND RouteStatus ='CLOSED'
		
	END	

SELECT RS.RouteId,RM.RouteName,COUNT(LocalityId)AS NoOfLocalities,SUM(RS.DuplicateTotEmps)AS NoOfEmps,TripCost AS RouteCost  
	FROM @tblRouteAssignment RS
		LEFT OUTER JOIN rvlfRouteMastercsc RM ON RM.RouteId=RS.RouteId 	
	GROUP BY RS.RouteId,TripCost,RM.RouteName  ORDER BY NoOfEmps  
	
SELECT VA.RouteId,RM.RouteName,VA.LocalityId,VA.VehicleId ,VA.Occupancy,VM.Capacity ,VM.DisplayName AS VehicleName,COUNT(EL.AssignedVehicle)AS NoOfEmps,
	CASE WHEN va.VehicleId=1 THEN	'144' WHEN va.VehicleId=2 THEN '156' ELSE '190' END  AS TripCost,VT.RatePerKM,
	CASE WHEN va.VehicleId=1 THEN	'1 hrs 6 min'  WHEN va.VehicleId=2 THEN '1 hrs 15 min'  ELSE '50 min' END as TripTime,
	CASE WHEN va.VehicleId=1 THEN	'36'  WHEN va.VehicleId=2 THEN '45'  ELSE '30'  END as Distance,EL.VehicleStartTime    
	FROM @tblVehicleAssignment VA 
		INNER JOIN rvlfVehicleMaster VM ON VM.VehicleId=VA.VehicleId  
		INNER JOIN rvlfVehicleTypeMaster VT ON VT.VehicleTypeId=VM.VehicleTypeId 
		INNER JOIN @tblEmployeeList EL ON EL.AssignedVehicle=VA.VehicleId
		LEFT OUTER JOIN rvlfRouteMastercsc RM ON RM.RouteId =VA.RouteId 
GROUP BY EL.AssignedVehicle,VA.RouteId,VA.LocalityId,VA.VehicleId,VA.Occupancy,VM.Capacity,VM.DisplayName,
    VA.TripCost,RM.RouteName,NoOfEmps,VT.RatePerKM,VA.TripTime,VA.Distance,EL.VehicleStartTime     
    

SELECT Va.VehicleId,ROUND(el.Cost,0)as Cost, EL.EmployeeID,E.DisplayName,
	(CASE WHEN E.Sex=1 THEN 'Male' ELSE 'Female' END)AS Sex,REPLACE(el.FromAddress,'+','-') AS StreetAddress,E.MobileNo,EL.LocalityId,
	LM.LocalityName,EL.Assign,EL.AssignedVehicle,Occupancy,(ROW_NUMBER() OVER (ORDER BY StreetAddress))AS RowNo,
	El.ToLatitude as Latitude,El.toLongitude as Longitude,EL.FromLatitude,EL.FromLongitude,sequenceNo,
	VM.DisplayName as VehicleName,EL.PickupTime,EL.VehicleStartTime,'0' as EmpDistance 
	FROM @tblEmployeeList EL 
		INNER JOIN rvlfEmployee E ON E.EmployeeID=EL.EmployeeID 
		--INNER JOIN rvlfScheduledVehicleRequisition SR ON SR.EmployeeId=E.EmployeeID 
		INNER JOIN rvlfLocalityMaster LM ON LM.LocalityId=El.LocalityId 
		INNER JOIN rvlfVehicleMaster VM ON VM.VehicleId=EL.AssignedVehicle 		
		INNER JOIN @tblVehicleAssignment VA ON VA.VehicleId=EL.AssignedVehicle 
	WHERE(@bigBranchId IS NULL OR E.OrgId =@bigBranchId)
		AND (ISDELETED=0)
		AND (Available=1)	AND va.VehicleId IN (1)
	GROUP BY EL.AssignedVehicle,Va.VehicleId,Cost, EL.EmployeeID,E.DisplayName,Sex,E.StreetAddress,E.MobileNo,EL.FromAddress, 
	EL.LocalityId,LM.LocalityName,EL.Assign,EL.AssignedVehicle,Occupancy,El.toLatitude,El.toLongitude,EL.FromLatitude,EL.FromLongitude,
	sequenceNo,VM.DisplayName ,EL.PickupTime,EL.VehicleStartTime,EL.EmpDistance     
	--UNION ALL
	--SELECT 2 ,ROUND(el.Cost,0)as Cost, EL.EmployeeID,E.DisplayName,
	--(CASE WHEN E.Sex=1 THEN 'Male' ELSE 'Female' END)AS Sex,REPLACE(el.FromAddress,'+','-') AS StreetAddress,E.MobileNo,EL.LocalityId,
	--LM.LocalityName,EL.Assign,EL.AssignedVehicle,Occupancy,(ROW_NUMBER() OVER (ORDER BY StreetAddress))AS RowNo,
	--El.ToLatitude as Latitude,El.toLongitude as Longitude,EL.FromLatitude,EL.FromLongitude,sequenceNo,
	--VM.DisplayName as VehicleName,EL.PickupTime,EL.VehicleStartTime,'0' as EmpDistance 
	--FROM @tblEmployeeList EL 
	--	INNER JOIN rvlfEmployee E ON E.EmployeeID=EL.EmployeeID 
	--	--INNER JOIN rvlfScheduledVehicleRequisition SR ON SR.EmployeeId=E.EmployeeID 
	--	INNER JOIN rvlfLocalityMaster LM ON LM.LocalityId=El.LocalityId 
	--	INNER JOIN rvlfVehicleMaster VM ON VM.VehicleId=EL.AssignedVehicle 		
	--	INNER JOIN @tblVehicleAssignment VA ON VA.VehicleId=EL.AssignedVehicle 
	--WHERE(@bigBranchId IS NULL OR E.OrgId =@bigBranchId)
	--	AND (ISDELETED=0)
	--	AND (Available=1)	AND va.VehicleId IN (1)
	--GROUP BY EL.AssignedVehicle,Va.VehicleId,Cost, EL.EmployeeID,E.DisplayName,Sex,E.StreetAddress,E.MobileNo,EL.FromAddress, 
	--EL.LocalityId,LM.LocalityName,EL.Assign,EL.AssignedVehicle,Occupancy,El.toLatitude,El.toLongitude,EL.FromLatitude,EL.FromLongitude,
	--sequenceNo,VM.DisplayName ,EL.PickupTime,EL.VehicleStartTime,EL.EmpDistance     
	ORDER BY AssignedVehicle ASC,PickupTime ASC 
	
SELECT  COUNT(DISTINCT AssignedVehicle)AS TotalVehicles,COUNT(EmployeeID)AS TotalEmployees,
  36 AS TotalDistance,
 144 AS TotalCost,
 '1 hrs 6 min' AS TotalTime,@PECKTIMEKMSPERHRS as PeakSpeed,@NONPECKTIMEKMSPERHRS as NonPeakSpeed,
	@MORNINGPEAKFROMTIME as MorningPeakFrom,@MORNINGPEAKTOTIME as MorningPeakTo,@EVENINGPEAKFROMTIME as EveningPeakFrom,
	@EVENINGPEAKTOTIME as EveningPeakTo 
FROM @tblEmployeeList WHERE AssignedVehicle IS NOT NULL 

update rvlfVehicleMaster set Allocated=0
update rvlfLocalityMaster set allocated=0	
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSalikFare]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_GetSalikFare]         
(        
--@GeozoneId bigint        
@OrgID varchar(10),@bigQueryingUser BIGINT        
)        
as        
-- =============================================                          
-- Name   : rvlf_sp_GetSalikFare 6,64                          
-- Author  : Gopal.R                          
-- Create date : 20-Jan-2014                          
-- Description : Get Tool Gate Geozone and its Salik Fare Details                          
-- Company  : Angler Technologies                          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                          
-- =============================================           
begin     
  
  
DECLARE @HoursToBeAdded INT = 0                                  
 DECLARE @MinsToBeAdded INT = 0                                  
 DECLARE @DefaultDateFormat INT = 0                                  
 DECLARE @ConversionFactor numeric (10,2) = 1.0                                  
 DECLARE @Lang varchar(50),  @LangSetting varchar(20)              
                                             
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                                  
     @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    
     
        
                                                
SELECT @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser  
               
 SELECT geo.OrganizationId,geo.GeozoneNo,geo.GeozoneId,geo.GeozoneName,geo.Description,            
    geo.Email,tz.TimeZoneName AS 'TimeZone',geo.GeozoneType,(case when @Lang='LanguageArNew' then isnull(rs.AlarmLevelName_Ar,rs.AlarmLevelName) when @Lang='LanguageHindi' then isnull(rs.AlarmLevelName_Hin ,rs.AlarmLevelName) ELSE rs.AlarmLevelName END)as
  
  Severity,            
    CASE WHEN EXISTS(SELECT vg.GeozoneNo  FROM rvlfVehicleGeozone vg WHERE vg.GeozoneNo = geo.GeozoneNo)            
  THEN 1 ELSE 0 END AssignedStatus,            
  ISNULL(dbo.rvlf_fn_GetNotificationsList(1, geo.GeozoneNo, 1,1,0),'') as EmailList,             
  ISNULL(dbo.rvlf_fn_GetNotificationsList(1,geo.GeozoneNo, 0,1,0),'') as SMSList,                 
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1, geo.GeozoneNo, 1,0,1),''),',',', ') as EmailUserNameList,            
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1,  geo.GeozoneNo, 0,0,1),''),',',', ') as SMSUserNameList,             
  geo.CategoryId,c.CategoryName            
FROM rvlfOrganizationGeozone geo             
INNER JOIN rvlfTimeZones tz ON geo.TimeZone = tz.TimeZoneID            
INNER JOIN rvlfSeverity rs ON rs.AlarmLevelId = geo.SeverityId            
INNER JOIN rvlfCategory c ON c.CategoryId = geo.CategoryId             
WHERE  geo.OrganizationId = @OrgID and c.CategoryName='Toll Gate' order by Timezone        
        
        
select SNo,GeozoneID,GSF.VehicleTypeId,TollFare, CONVERT(varchar,CAST(ValidFrom as DATE),@DefaultDateFormat) as ValidFrom,  
isnull(cast(convert(varchar,  
(select DATEADD(day, DATEDIFF(day, 0, CAST(min(ValidFrom) as date))-1, '23:59:59')   
from rvlfGeozoneSalikFare where ValidFrom>GSF.ValidFrom and GeozoneID=GSF.GeozoneID and VehicleTypeId=GSF.VehicleTypeId),@DefaultDateFormat)  
 as varchar) ,'-') as ValidTo,Status,VT.VehicleTypeName         
from rvlfGeozoneSalikFare GSF inner join rvlfVehicleType VT on GSF.VehicleTypeId=VT.VehicleTypeId order by gsf.ValidFrom desc       
--where ValidTo is null --and GeozoneID=@GeozoneId        
end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetScheduledHistory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetScheduledHistory]   
 @bigVehicleId bigint=null,  
 @bigFleetId bigint=null,  
 @dtFromdateTime datetime=null,  
 @dtTodateTime datetime=null,  
 @bigOrganizationId bigint=null,  
 @bigQueryingUser bigint=null   
AS  
/********************************************************************************************/  
-- Name  : [rvlf_sp_GetScheduledHistory] null,8,'2016-06-21','2016-06-21',6,303
/*******************************************************************************************/  
  
BEGIN  
 SET NOCOUNT ON    
   
 DECLARE @HoursToBeAdded INT = 0  
 DECLARE @MinsToBeAdded INT = 0   
 DECLARE @DefaultDateFormat INT = 0
 DECLARE @DistanceCaptionPrefix varchar(15)
 	
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,
    @DistanceCaptionPrefix = CASE WHEN up.Distance = 0 THEN 'Miles' ELSE 'Kms' 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(@bigQueryingUser IS NULL OR @bigQueryingUser='' OR up.UserId = @bigQueryingUser)  
   
 --check IF any not executed schedules are avilable or not  
 IF EXISTS(SELECT ScheduleId FROM rvlfScheduleOfCommandsMaster   
  WHERE ScheduleId NOT IN(SELECT ScheduleId FROM rvlfSchedulingOfCommandsLog) AND EffectiveTo < GETUTCDATE())  
  BEGIN  
   INSERT INTO rvlfSchedulingOfCommandsLog (ScheduleId,IsCommandSend,ResponseMsg,[No.ofTries])  
    select ScheduleId,0,'Expired',0  from rvlfScheduleOfCommandsMaster where ScheduleId not in(select ScheduleId  from rvlfSchedulingOfCommandsLog) and EffectiveTo < GETDATE()  
  END  
    
 SELECT SM.ScheduleId,MD.EquipmentName as VehicleDescription,C.BoxCmdOutTypeName,  
  CONVERT(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,SM.EffectiveFrom)),@DefaultDateFormat) + ' ' + CONVERT(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,SM.EffectiveFrom)) as time),22) AS CreatedDateTime,  
  DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,SM.EffectiveFrom)) AS CreatedDateTimeSort,  
  CASE WHEN NS.SMSScheduleID is NULL THEN 0 ELSE 1 END as SMSStatus,
  CASE WHEN L.ExecutionOn IS NOT NULL THEN  
      CASE WHEN L.ResponseMsg='Expired' THEN CONVERT(varchar(20),DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,L.ExecutionOn)),113)   
   ELSE CONVERT(varchar(20),DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,L.ExecutionOn)),113) END  
   ELSE  CONVERT(varchar(20),DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,SM.ActualExecutionDate)),113) END as ExecutionOnSort ,      
   CASE WHEN L.ExecutionOn IS NOT NULL THEN  
      CASE WHEN L.ResponseMsg='Expired' THEN CONVERT(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,L.ExecutionOn)),@DefaultDateFormat)  + ' ' 
	  + CONVERT(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,L.ExecutionOn))AS time),22)
   ELSE CONVERT(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,L.ExecutionOn)),@DefaultDateFormat) + ' ' +
    CONVERT(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,L.ExecutionOn))AS time),22) END  
   ELSE  CONVERT(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,SM.ActualExecutionDate)),@DefaultDateFormat) + ' ' +  CONVERT(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,SM.ActualExecutionDate)) as time),22)
 END as ExecutionOn ,  
  CASE WHEN SM.BoxCmdOutTypeId  = 22 THEN (CASE WHEN L.ResponseMsg IS NULL THEN 'Pending' WHEN L.ResponseMsg = 'Command sent successfully.' THEN 'Inprogress' ELSE L.ResponseMsg END)  
  ELSE (CASE WHEN L.IsCommandSend=1 THEN 'Success' WHEN (L.IsCommandSend=0 AND L.ResponseMsg='Expired') OR (SM.EffectiveTo<GETUTCDATE()) THEN 'Expired' ELSE 'Pending' END) END  
  AS commandStatus,  
  CASE WHEN L.IsCommandSend=1 THEN 3 WHEN (L.IsCommandSend=0 AND L.ResponseMsg='Expired') OR (CONVERT(DATE,SM.EffectiveTo)<CONVERT(DATE,GETUTCDATE())) THEN 2 ELSE 1 END AS StatusOrder,  
  L.ScheduleLogId,  
  CONVERT(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,SM.EffectiveTo)),@DefaultDateFormat) + ' ' + CONVERT(varchar,cast(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,SM.EffectiveTo)) as time),22) AS RetriesPeriod,  DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,SM.EffectiveTo)) AS EffectiveToSort, SM.PacketInfo,
  'Inputs'=CASE WHEN SM.BoxCmdOutTypeId=1 and CHARINDEX(',1;DCLID',PacketInfo,1)=0 THEN  
  dbo.rvlf_fn_GetTimeFromSeconds(CAST(SUBSTRING(PacketInfo,PatIndex('%Param=%',PacketInfo)+6,PatIndex('%;DCLID=%',PacketInfo)-(PatIndex('%Param=%',PacketInfo)+6)) AS int))
   WHEN SM.BoxCmdOutTypeId=1 and CHARINDEX(',1;DCLID',PacketInfo,1)>0 THEN replace(dbo.rvlf_fn_GetParamValueWithIndex(PacketInfo,'Param=',';'),',1',' Meters') 
  WHEN SM.BoxCmdOutTypeId=22 THEN 
	 CASE WHEN PacketInfo LIKE '%TRINETRA_OTA_Repository\%' THEN SUBSTRING(PacketInfo,CHARINDEX('TRINETRA_OTA_Repository\',PacketInfo,0)+24,
	 (CHARINDEX(',',PacketInfo,CHARINDEX('TRINETRA_OTA_Repository\',PacketInfo,0))-(CHARINDEX('TRINETRA_OTA_Repository\',PacketInfo,0)+24)))
	 ELSE SUBSTRING(PacketInfo,CHARINDEX('TRINETRA\OTA\',PacketInfo,0)+13,(CHARINDEX(',',PacketInfo,CHARINDEX('TRINETRA\OTA\',PacketInfo,0))-(CHARINDEX('TRINETRA\OTA\',PacketInfo,0)+13))) END  
   WHEN PatIndex('%Param=%',SM.PacketInfo) <> 0 THEN
	    CASE WHEN SM.BoxCmdOutTypeId = 14 or SM.BoxCmdOutTypeId = 42 THEN SUBSTRING(PacketInfo,PatIndex('%Param=%',PacketInfo)+6,PatIndex('%;DCLID=%',PacketInfo)-(PatIndex('%Param=%',PacketInfo)+6)) 		 
			 WHEN SM.BoxCmdOutTypeId = 28 AND SUBSTRING(PacketInfo,PatIndex('%Param=%',PacketInfo)+6,PatIndex('%;DCLID=%',PacketInfo)-(PatIndex('%Param=%',PacketInfo)+6))='True' THEN 'Enable' --SET KeyFob mode Enable
			 WHEN SM.BoxCmdOutTypeId = 28 AND SUBSTRING(PacketInfo,PatIndex('%Param=%',PacketInfo)+6,PatIndex('%;DCLID=%',PacketInfo)-(PatIndex('%Param=%',PacketInfo)+6))='False' THEN 'Disable' --SET KeyFob mode Disable
			 WHEN SM.BoxCmdOutTypeId = 30 THEN REPLACE(SUBSTRING(PacketInfo,PatIndex('%Param=%',PacketInfo)+6,PatIndex('%;DCLID=%',PacketInfo)-(PatIndex('%Param=%',PacketInfo)+6)),',00,00,',' hrs, ')+' hrs' --Set Device Sleep And WakeTime			 
			 WHEN SM.BoxCmdOutTypeId = 52 THEN  -- Set Keep Alive Frequency
				CASE WHEN PATINDEX('%,1,%',SUBSTRING(PacketInfo,PatIndex('%Param=%',PacketInfo)+6,PatIndex('%;DCLID=%',PacketInfo)-(PatIndex('%Param=%',PacketInfo)+6))) > 0 THEN
						  REPLACE(SUBSTRING(SUBSTRING(PacketInfo,PatIndex('%Param=%',PacketInfo)+6,PatIndex('%;DCLID=%',PacketInfo)-
						  (PatIndex('%Param=%',PacketInfo)+6)),0,LEN(SUBSTRING(PacketInfo,PatIndex('%Param=%',PacketInfo)+6,PatIndex('%;DCLID=%',PacketInfo)-(PatIndex('%Param=%',PacketInfo)+6)))-1),',',' mins, ')+'Ignition On/Off'
					ELSE REPLACE(SUBSTRING(SUBSTRING(PacketInfo,PatIndex('%Param=%',PacketInfo)+6,
					PatIndex('%;DCLID=%',PacketInfo)-(PatIndex('%Param=%',PacketInfo)+6)),0,LEN(SUBSTRING(PacketInfo,PatIndex('%Param=%',PacketInfo)+6,
					PatIndex('%;DCLID=%',PacketInfo)-(PatIndex('%Param=%',PacketInfo)+6)))-1),',',' mins, ')+'Ignition Off'
				END
			 ELSE '-' --SUBSTRING(PacketInfo,PatIndex('%Param=%',PacketInfo)+6,PatIndex('%;DCLID=%',PacketInfo)-(PatIndex('%Param=%',PacketInfo)+6))
		END
   ELSE '-' END
   FROM rvlfScheduleOfCommandsMaster SM  
   INNER JOIN rvlfBoxCmdOutType C ON C.BoxCmdOutTypeId=SM.BoxCmdOutTypeId  --Collate SQL_Latin1_General_CP1_CS_AS   
   --INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=SM.Boxid   
   --INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId   
   inner join rvlfmakdevices MD on md.boxid=sm.boxid
   --LEFT OUTER JOIN rvlfSchedulingOfCommandsLog L ON L.ScheduleId =SM.ScheduleId   
   OUTER APPLY (SELECT TOP 1 * FROM rvlfSchedulingOfCommandsLog lg WHERE lg.ScheduleId= SM.ScheduleId ORDER BY ScheduleLogId DESC) L 
   INNER JOIN rvlfFleetVehicles FV ON FV.VehicleId=MD.VehicleId   
   INNER JOIN rvlfFleet F ON F.FleetId=FV.FleetId   
   --_SendSMSTest
   LEFT JOIN rvlfNotificationLog NS on SM.ScheduleId = NS.SMSScheduleID  
  WHERE (@bigFleetId IS NULL OR @bigFleetId='' OR F.FleetId=@bigFleetId)  
   AND SM.OrganizationId=@bigOrganizationId   
   AND(@bigVehicleId IS NULL OR @bigVehicleId='' OR MD.VehicleId=@bigVehicleId)     
   AND (CASE WHEN SM.ActualExecutionDate IS NULL AND L.ExecutionOn IS NULL THEN CONVERT(DATE,SM.EffectiveFrom)  
     WHEN  L.ExecutionOn IS NULL THEN CONVERT(DATE,SM.EffectiveFrom) ELSE CONVERT(DATE,L.ExecutionOn) END BETWEEN CONVERT(DATE,@dtFromdateTime) AND CONVERT(DATE,@dtTodateTime))  
   AND C.OperationTypeId IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s 
					WHERE s.ModuleId = 22 and s.UserGroupId IN 
					(SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))	
  ORDER BY CreatedDateTime desc  
    
 SET NOCOUNT OFF  
END
--CASE WHEN DATEDIFF(d,EffectiveFrom,EffectiveTo)=1 THEN CAST(DATEDIFF(d,EffectiveFrom,EffectiveTo) AS VARCHAR)+' Day' ELSE CAST(DATEDIFF(d,EffectiveFrom,EffectiveTo) AS VARCHAR)+' Days' END AS RetriesPeriod ,



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetScheduledReportLog]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetScheduledReportLog]  
 @bigReportScheduleID bigint= null,  
 @uiReportRef uniqueidentifier = null,  
 @bigOrganizationID bigint = null  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetScheduledReportLog  
-- Description : To update the scheduled reports log  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 23-Mar-2010 MJJC Created Intial Version   
--              :   22-Apr-2010 MJJC Included the provision for report path  
--              :   21-Aug-2010 LK     Removed the Vehicle Display Name  
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
  SELECT e.ReportGenerationID, e.ReportScheduleId,CASE WHEN e.UserID =0 THEN NULL ELSE e.Email END as EmailID,  
   DATEADD(N ,t.MinToBeAdded, DATEADD(HH,t.HoursToBeAdded,e.ReportStartDate)) as ReportStartDate,  
   DATEADD(N ,t.MinToBeAdded, DATEADD(HH,t.HoursToBeAdded,e.ReportEndDate)) as ReportEndDate,  
   DATEADD(N ,t.MinToBeAdded, DATEADD(HH,t.HoursToBeAdded,e.GeneratedOn)) as GeneratedOn,  
   DATEADD(N ,t.MinToBeAdded, DATEADD(HH,t.HoursToBeAdded,e.ActualGeneration)) as ActualGeneration,  
   CASE WHEN e.IsError = 1 THEN e.ErrorMessage ELSE NULL END as ErrorMessage, e.ReportRef, e.ReportPath,   
   CASE WHEN s.Frequency = 1 THEN 'Daily' WHEN s.Frequency = 1 THEN 'Weekly' ELSE 'Monthly' END,  
   f.FleetName, ISNULL(v.VehicleDescription,'All') as VehicleDisplayName,  
   ISNULL(u.DisplayName,'') as UserDisplayName, r.ReportTypesName  
  FROM rvlfScheduledReportLog e   
   INNER JOIN rvlfSchedulingReport s ON e.ReportScheduleID = s.ReportScheduleId  
   INNER JOIN rvlfReportTypes r ON s.ReportTypesId = r.ReportTypesId  
   INNER JOIN rvlfOrganization g ON s.OrganizationId= g.OrganizationId  
   INNER JOIN rvlfFleet f ON s.FleetId = f.FleetId  
   LEFT OUTER JOIN rvlfVehicleAssignment va ON va.BoxId = s.VehicleId  
   LEFT OUTER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   LEFT OUTER JOIN rvlfUser u on u.UserId = e.UserID  
   INNER JOIN rvlfTimeZones t ON e.TimeZoneID = t.TimeZoneID  
  WHERE   
   (@bigReportScheduleID IS NULL OR @bigReportScheduleID='' OR e.ReportScheduleID = @bigReportScheduleID)   
   AND (@uiReportRef IS NULL OR @uiReportRef='' OR e.ReportRef = @uiReportRef)  
   AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' or s.OrganizationId = @bigOrganizationID)  
 SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetScheduledReports]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetScheduledReports]        
 @bigScheduledID bigint = null,        
 @dtStartDate datetime = null,        
 @dtEndDate datetime = null,        
 @bitIsStartUP bit = null        
AS        
/*****************************************************************************************************************************/        
-- Name  : rvlf_sp_GetScheduledReports 1461,null,null,null        
-- Description : To get the scheduled reports        
-- Author  : M. Jebamalai Jaya Chitra.        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--   : 01-Mar-2010 MJJC Created Intial Version         
--          : 08-Mar-2010 MJJC Changed the start date calculation based on effective date and converted the date to GMT.        
--   : 11-Mar-2010 MJJC To Get the start and end date from the table and mapped to user preferences.        
--   : 19-Aug-2010 LK Removed the Vehicle Display Name        
--   : 07-Jan-2011 TSK Included the condition to show only Scheduled Reports (blocked send email option)    
--          : 07-Apr-2015 SSG Update the next Generation date time for old schedules      
/******************************************************************************************************************************/        
BEGIN        
 SET NOCOUNT ON         
    
  ----INSERT INTO rvlfLogProcCalls (ProcedureName, ParameterList) VALUES ('rvlf_sp_GetScheduledReports', 'ScheduledID : '+        
  ----ISNULL(CAST(@bigScheduledID as varchar) ,'No Value')+ ' StartDate : ' + ISNULL(CAST(@dtStartDate as varchar(30)),'No Value')+        
  ----' EndDate : '+ISNULL(CAST(@dtEndDate as varchar(30)),'No Value'))       
    
  UPDATE dbo.rvlfSchedulingReport SET  
  NextGenerationDateTime = (CASE WHEN Frequency=0 THEN DATEADD(dd,1,NextGenerationDateTime) WHEN Frequency=1 THEN DATEADD(dd,7,NextGenerationDateTime)  
  WHEN Frequency=2 THEN DATEADD(MM,1,NextGenerationDateTime) WHEN Frequency=3 THEN DATEADD(dd,14,NextGenerationDateTime) END),  
  ReportStartDate= (CASE WHEN Frequency=0 THEN DATEADD(dd,1,ReportStartDate) WHEN Frequency=1 THEN DATEADD(dd,7,ReportStartDate)  
  WHEN Frequency=2 THEN DATEADD(MM,1,ReportStartDate) WHEN Frequency=3 THEN DATEADD(dd,14,ReportStartDate)END),  
  ReportEndDate = (CASE WHEN Frequency=0 THEN DATEADD(dd,1,ReportEndDate) WHEN Frequency=1 THEN DATEADD(dd,7,ReportEndDate)  
  WHEN Frequency=2 THEN DATEADD(MM,1,ReportEndDate) WHEN Frequency=3 THEN DATEADD(dd,14,ReportEndDate) END),  
  IsLocked=0, LockedDateTime= NULL, CanGenerate = 1,ModifiedDateTime=GETUTCDATE()   
  WHERE DATEDIFF(HOUR,NextGenerationDateTime,GETUTCDATE()) >   
  --Added 6 hrs buffer for all the missed schedules  
  (CASE WHEN Frequency=0 THEN 30 WHEN Frequency=1 THEN 174 WHEN Frequency=2 THEN 726 WHEN Frequency=3 THEN 342 END)  
  AND IsDeleted=0 AND IsScheduled=1 AND CanGenerate=1 --AND EffectiveTo IS NULL  
  AND OrganizationId IN (SELECT OrganizationId FROM rvlfOrganization WHERE IsDeleted=0 AND ExpiresOn > GETDATE())   
          
  IF @bitIsStartUP IS NOT NULL AND @bitIsStartUP = 1        
   BEGIN        
    SELECT        
     s.ReportScheduleId, s.ReportTypesId, r.ReportTypesName, s.Frequency,         
     s.ReportStartDate as StartDate, s.ReportEndDate as EndDate,        
     s.GenerateReportOn, s.EffectiveFrom ,        
     s.NextGenerationDateTime, s.EffectiveTo, f.FleetName,         
     ISNULL(v.VehicleDescription,'All') as VehDispName,        
     CASE         
      WHEN s.Frequency = 0 THEN 'Daily'        
      WHEN s.Frequency = 1 THEN 'Weekly'        
      WHEN s.Frequency=2 THEN 'Monthly'      
      WHEN s.Frequency=3 THEN 'Fortnightly' END as FrequencyDetails,        
     g.OrganizationName, z.HoursToBeAdded, z.MinToBeAdded, s.WeekDayFrom, s.WeekDayTo, s.WeekDayOn,        
     s.DayOfMonth, ISNULL(dbo.rvlf_fn_GetNotificationsList(5, s.ReportScheduleId, 1,1,0),'') as EmailList,     
     z.TimeZoneID        
    FROM rvlfSchedulingReport s         
     INNER JOIN rvlfReportTypes r ON s.ReportTypesId = r.ReportTypesId        
     INNER JOIN rvlfOrganization g ON g.OrganizationId = s.OrganizationId        
     INNER JOIN rvlfTimeZones z ON g.CountryId = z.TimeZoneID        
     INNER JOIN rvlfOrganizationSolution t ON s.OrganizationId = t.OrganizationId        
     INNER JOIN rvlfTrinetraSolutions ts ON ts.SolutionId = t.SolutionId        
     INNER JOIN rvlfFleet f ON f.FleetId = s.FleetId        
     LEFT OUTER JOIN rvlfVehicleAssignment va ON va.BoxId in (select * from rvlf_fn_ConvertArrayToTable(s.VehicleId,','))     
     LEFT OUTER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId        
    WHERE s.CanGenerate = 1  AND s.NextGenerationDateTime < @dtStartDate -- and s.IsScheduled = 1        
    AND CONVERT(DATE,s.NextGenerationDateTime) BETWEEN CONVERT(DATE,DATEADD(DD,-3,GETUTCDATE())) AND CONVERT(DATE,GETUTCDATE())  AND g.ExpiresOn > GETDATE()  
	and g.OrganizationId in (6,86)
   END        
  ELSE        
   BEGIN        
    SELECT         
     s.ReportScheduleId,s.EffectiveFrom, s.OrganizationId, s.ReportTypesId, s.FleetId,s.VehicleId, s.IsSummaryVisible,        
     s.IsDetailsVisible, s.ShowHideOptions, s.ReportParameters,s.SortBy, s.FileExtension,        
     CASE WHEN s.FileExtension = 0 THEN '.pdf'        
      WHEN s.FileExtension = 1 THEN '.xls' ELSE '.doc' END as FileExt,        
     s.SortDirection, CASE WHEN s.SortDirection = 0 THEN 'ASC' ELSE 'DESC' END as SortDir,        
      s.Frequency,s.ReportStartDate, s.ReportEndDate , s.GenerateReportOn, s.NextGenerationDateTime,        
      s.ReportFrom , s.ReportTo, s.EffectiveTo, s.WeekDayFrom, s.WeekDayTo, s.WeekDayOn,        
     s.DayOfMonth, u.DisplayName as UserDispName, u.UserId,u.Email, p.Distance,p.TimezoneId , g.OrganizationName,        
      f.FleetName,       
      CASE WHEN s.VehicleId IS NULL OR s.VehicleId='0' THEN 'All' ELSE      
     STUFF((SELECT ','+vp.VehicleDescription FROM rvlfVehicle vp INNER JOIN rvlfVehicleAssignment VA ON vp.VehicleId = VA.VehicleId      
  WHERE VA.BoxId IN  (SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(s.VehicleId,',')) FOR XML PATH('')),1,1,'') END AS VehicleDescription,      
      --v.VehicleDescription,      
       ts.ResourceFileName,         
      DATEADD(MI,z.MinToBeAdded , DATEADD(HH, z.HoursToBeAdded, s.ReportStartDate)) as StartDate,         
      DATEADD(MI,z.MinToBeAdded , DATEADD(HH, z.HoursToBeAdded, s.ReportEndDate)) as EndDate,        
     CASE         
      WHEN s.Frequency = 0 THEN 'Daily'        
      WHEN s.Frequency = 1 THEN 'Weekly'        
      WHEN s.Frequency=2 THEN 'Monthly'       
      WHEN s.Frequency=3 THEN 'Fortnightly' END as FrequencyDetails,        
      rt.ReportTypesName,      
      CASE WHEN s.VehicleId IS NULL OR s.VehicleId='0' THEN 'All' ELSE      
     STUFF((SELECT ','+vp.VehicleDescription FROM rvlfVehicle vp INNER JOIN rvlfVehicleAssignment VA ON vp.VehicleId = VA.VehicleId      
  WHERE VA.BoxId IN  (SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(s.VehicleId,',')) FOR XML PATH('')),1,1,'') END AS VehDispName,      
      --ISNULL(v.VehicleDescription,'All') as VehDispName,       
      s.NextGenerationDateTime        
    FROM rvlfSchedulingReport s        
     INNER JOIN rvlfNotificationList n ON n.NotificationType = 5 AND n.TypeID=s.ReportScheduleId        
     INNER JOIN rvlfReportTypes rt ON s.ReportTypesId = rt.ReportTypesId        
     INNER JOIN rvlfOrganization g ON g.OrganizationId = s.OrganizationId        
     INNER JOIN rvlfOrganizationSolution t ON s.OrganizationId = t.OrganizationId        
     INNER JOIN rvlfTrinetraSolutions ts ON ts.SolutionId = t.SolutionId        
     INNER JOIN rvlfFleet f ON f.FleetId = s.FleetId        
     --LEFT OUTER JOIN rvlfVehicleAssignment va ON va.BoxId in  (select * from rvlf_fn_ConvertArrayToTable(s.VehicleId,','))        
     --LEFT OUTER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId        
     INNER JOIN rvlfUser u On n.UserID = u.UserId        
     INNER JOIN rvlfUserPreferences p ON u.UserId = p.UserId        
     INNER JOIN rvlfTimeZones z On p.TimezoneId = z.TimeZoneID        
    WHERE         
     (u.Email IS Not NULL AND LEN(u.Email) > 0 )   AND g.ExpiresOn > GETDATE()  and u.isdelete=0 and u.islocked=0
     AND (@bigScheduledID IS NULL OR @bigScheduledID='' OR s.ReportScheduleId = @bigScheduledID)        
     --AND (@dtStartDate IS NULL or s.NextGenerationDateTime BETWEEN @dtStartDate and @dtEndDate)        
     AND (@dtStartDate IS NULL or (s.NextGenerationDateTime <@dtStartDate AND CONVERT(DATE,s.NextGenerationDateTime)   
     BETWEEN CONVERT(DATE,DATEADD(DD,-3,GETUTCDATE())) AND CONVERT(DATE,GETUTCDATE()))) AND s.CanGenerate = 1 and n.Email = 1 -- and s.IsScheduled = 1   
            and g.OrganizationId in (6,86)
    -- update         
    UPDATE rvlfSchedulingReport SET IsLocked = 1 , LockedDateTime = SYSUTCDATETIME ()         
    WHERE (@bigScheduledID IS NULL OR @bigScheduledID='' OR ReportScheduleId = @bigScheduledID)        
     AND (@dtStartDate IS NULL or NextGenerationDateTime BETWEEN @dtStartDate and @dtEndDate)        
     AND CanGenerate = 1 AND ReportScheduleId IN        
     (SELECT  s.ReportScheduleId FROM rvlfSchedulingReport s        
     INNER JOIN rvlfNotificationList n ON n.NotificationType = 5 AND n.TypeID=s.ReportScheduleId        
     INNER JOIN rvlfReportTypes rt ON s.ReportTypesId = rt.ReportTypesId        
     INNER JOIN rvlfOrganization g ON g.OrganizationId = s.OrganizationId        
     INNER JOIN rvlfOrganizationSolution t ON s.OrganizationId = t.OrganizationId        
     INNER JOIN rvlfTrinetraSolutions ts ON ts.SolutionId = t.SolutionId        
     INNER JOIN rvlfFleet f ON f.FleetId = s.FleetId        
     LEFT OUTER JOIN rvlfVehicleAssignment va ON va.BoxId in (select * from rvlf_fn_ConvertArrayToTable(s.VehicleId,','))         
     LEFT OUTER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId        
     INNER JOIN rvlfUser u On n.UserID = u.UserId        
     INNER JOIN rvlfUserPreferences p ON u.UserId = p.UserId        
     INNER JOIN rvlfTimeZones z On p.TimezoneId = z.TimeZoneID        
    WHERE         
     (u.Email IS Not NULL AND LEN(u.Email) > 0 )        
     AND (@bigScheduledID IS NULL OR @bigScheduledID='' OR s.ReportScheduleId = @bigScheduledID)        
     AND (@dtStartDate IS NULL or s.NextGenerationDateTime BETWEEN @dtStartDate and @dtEndDate)        
     --AND (@dtStartDate IS NULL or s.NextGenerationDateTime <@dtStartDate)        
     AND s.CanGenerate = 1 AND g.ExpiresOn > GETDATE()and u.isdelete=0 and u.islocked=0)        
   END        
           
 SET NOCOUNT OFF        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetScheduledReports_test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE Procedure [dbo].[rvlf_sp_GetScheduledReports_test]       
   @bigScheduledID bigint = null,        
 @dtStartDate datetime = '2016-07-27 09:00:39.933',--'2016-07-26 02:40:33.563',
 @dtEndDate datetime = '2016-07-26 02:42:33.563',        
 @bitIsStartUP bit = null 
 AS         
--/*****************************************************************************************************************************/        
---- Name  : rvlf_sp_GetScheduledReports 1461,null,null,null        
---- Description : To get the scheduled reports        
---- Author  : M. Jebamalai Jaya Chitra.        
---- Company  : Angler Technologies        
---- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
----   : 01-Mar-2010 MJJC Created Intial Version         
----          : 08-Mar-2010 MJJC Changed the start date calculation based on effective date and converted the date to GMT.        
----   : 11-Mar-2010 MJJC To Get the start and end date from the table and mapped to user preferences.        
----   : 19-Aug-2010 LK Removed the Vehicle Display Name        
----   : 07-Jan-2011 TSK Included the condition to show only Scheduled Reports (blocked send email option)    
----          : 07-Apr-2015 SSG Update the next Generation date time for old schedules      
--/******************************************************************************************************************************/        
 BEGIN        
  SET NOCOUNT ON         
    
--  ----INSERT INTO rvlfLogProcCalls (ProcedureName, ParameterList) VALUES ('rvlf_sp_GetScheduledReports', 'ScheduledID : '+        
--  ----ISNULL(CAST(@bigScheduledID as varchar) ,'No Value')+ ' StartDate : ' + ISNULL(CAST(@dtStartDate as varchar(30)),'No Value')+        
--  ----' EndDate : '+ISNULL(CAST(@dtEndDate as varchar(30)),'No Value'))       
    
--  UPDATE dbo.rvlfSchedulingReport SET  
--  NextGenerationDateTime = (CASE WHEN Frequency=0 THEN DATEADD(dd,1,NextGenerationDateTime) WHEN Frequency=1 THEN DATEADD(dd,7,NextGenerationDateTime)  
--  WHEN Frequency=2 THEN DATEADD(MM,1,NextGenerationDateTime) WHEN Frequency=3 THEN DATEADD(dd,14,NextGenerationDateTime) END),  
--  ReportStartDate= (CASE WHEN Frequency=0 THEN DATEADD(dd,1,ReportStartDate) WHEN Frequency=1 THEN DATEADD(dd,7,ReportStartDate)  
--  WHEN Frequency=2 THEN DATEADD(MM,1,ReportStartDate) WHEN Frequency=3 THEN DATEADD(dd,14,ReportStartDate)END),  
--  ReportEndDate = (CASE WHEN Frequency=0 THEN DATEADD(dd,1,ReportEndDate) WHEN Frequency=1 THEN DATEADD(dd,7,ReportEndDate)  
--  WHEN Frequency=2 THEN DATEADD(MM,1,ReportEndDate) WHEN Frequency=3 THEN DATEADD(dd,14,ReportEndDate) END),  
--  IsLocked=0, LockedDateTime= NULL, CanGenerate = 1,ModifiedDateTime=GETUTCDATE()   
--  WHERE DATEDIFF(HOUR,NextGenerationDateTime,GETUTCDATE()) >   
--  --Added 6 hrs buffer for all the missed schedules  
--  (CASE WHEN Frequency=0 THEN 30 WHEN Frequency=1 THEN 174 WHEN Frequency=2 THEN 726 WHEN Frequency=3 THEN 342 END)  
--  AND IsDeleted=0 AND IsScheduled=1 AND CanGenerate=1 --AND EffectiveTo IS NULL  
--  AND OrganizationId IN (SELECT OrganizationId FROM rvlfOrganization WHERE IsDeleted=0 AND ExpiresOn > GETDATE())   
          
--  IF @bitIsStartUP IS NOT NULL AND @bitIsStartUP = 1        
--   BEGIN        
--    SELECT        
--     s.ReportScheduleId, s.ReportTypesId, r.ReportTypesName, s.Frequency,         
--     s.ReportStartDate as StartDate, s.ReportEndDate as EndDate,        
--     s.GenerateReportOn, s.EffectiveFrom ,        
--     s.NextGenerationDateTime, s.EffectiveTo, f.FleetName,         
--     ISNULL(v.VehicleDescription,'All') as VehDispName,        
--     CASE         
--      WHEN s.Frequency = 0 THEN 'Daily'        
--      WHEN s.Frequency = 1 THEN 'Weekly'        
--      WHEN s.Frequency=2 THEN 'Monthly'      
--      WHEN s.Frequency=3 THEN 'Fortnightly' END as FrequencyDetails,        
--     g.OrganizationName, z.HoursToBeAdded, z.MinToBeAdded, s.WeekDayFrom, s.WeekDayTo, s.WeekDayOn,        
--     s.DayOfMonth, ISNULL(dbo.rvlf_fn_GetNotificationsList(5, s.ReportScheduleId, 1,1,0),'') as EmailList,       
--     z.TimeZoneID        
--    FROM rvlfSchedulingReport s         
--     INNER JOIN rvlfReportTypes r ON s.ReportTypesId = r.ReportTypesId        
--     INNER JOIN rvlfOrganization g ON g.OrganizationId = s.OrganizationId        
--     INNER JOIN rvlfTimeZones z ON g.CountryId = z.TimeZoneID        
--     INNER JOIN rvlfOrganizationSolution t ON s.OrganizationId = t.OrganizationId        
--     INNER JOIN rvlfTrinetraSolutions ts ON ts.SolutionId = t.SolutionId        
--     INNER JOIN rvlfFleet f ON f.FleetId = s.FleetId        
--     LEFT OUTER JOIN rvlfVehicleAssignment va ON va.BoxId in (select * from rvlf_fn_ConvertArrayToTable(s.VehicleId,','))     
--     LEFT OUTER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId        
--    WHERE s.CanGenerate = 1 AND s.NextGenerationDateTime < @dtStartDate -- and s.IsScheduled = 1        
--    AND CONVERT(DATE,s.NextGenerationDateTime) BETWEEN CONVERT(DATE,DATEADD(DD,-3,GETUTCDATE())) AND CONVERT(DATE,GETUTCDATE())  
--   END        
--  ELSE        
--   BEGIN        
    SELECT         
     s.ReportScheduleId,s.EffectiveFrom, s.OrganizationId, s.ReportTypesId, s.FleetId,s.VehicleId, s.IsSummaryVisible,        
     s.IsDetailsVisible, s.ShowHideOptions, s.ReportParameters,s.SortBy, s.FileExtension,        
     CASE WHEN s.FileExtension = 0 THEN '.pdf'        
      WHEN s.FileExtension = 1 THEN '.xls' ELSE '.doc' END as FileExt,        
     s.SortDirection, CASE WHEN s.SortDirection = 0 THEN 'ASC' ELSE 'DESC' END as SortDir,        
      s.Frequency,s.ReportStartDate, s.ReportEndDate , s.GenerateReportOn, s.NextGenerationDateTime,        
      s.ReportFrom , s.ReportTo, s.EffectiveTo, s.WeekDayFrom, s.WeekDayTo, s.WeekDayOn,        
     s.DayOfMonth, u.DisplayName as UserDispName, u.UserId,u.Email, p.Distance,p.TimezoneId , g.OrganizationName,        
      f.FleetName,       
      CASE WHEN s.VehicleId IS NULL OR s.VehicleId='0' THEN 'All' ELSE      
     STUFF((SELECT ','+vp.VehicleDescription FROM rvlfVehicle vp INNER JOIN rvlfVehicleAssignment VA ON vp.VehicleId = VA.VehicleId      
  WHERE VA.BoxId IN  (SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(s.VehicleId,',')) FOR XML PATH('')),1,1,'') END AS VehicleDescription,      
      --v.VehicleDescription,      
       ts.ResourceFileName,         
      DATEADD(MI,z.MinToBeAdded , DATEADD(HH, z.HoursToBeAdded, s.ReportStartDate)) as StartDate,         
      DATEADD(MI,z.MinToBeAdded , DATEADD(HH, z.HoursToBeAdded, s.ReportEndDate)) as EndDate,        
     CASE         
      WHEN s.Frequency = 0 THEN 'Daily'        
      WHEN s.Frequency = 1 THEN 'Weekly'        
      WHEN s.Frequency=2 THEN 'Monthly'       
      WHEN s.Frequency=3 THEN 'Fortnightly' END as FrequencyDetails,        
      rt.ReportTypesName,      
      CASE WHEN s.VehicleId IS NULL OR s.VehicleId='0' THEN 'All' ELSE      
     STUFF((SELECT ','+vp.VehicleDescription FROM rvlfVehicle vp INNER JOIN rvlfVehicleAssignment VA ON vp.VehicleId = VA.VehicleId      
  WHERE VA.BoxId IN  (SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(s.VehicleId,',')) FOR XML PATH('')),1,1,'') END AS VehDispName,      
      --ISNULL(v.VehicleDescription,'All') as VehDispName,       
        s.NextGenerationDateTime,  @dtStartDate,CONVERT(DATE,DATEADD(DD,-3,'26-jul-2016')),CONVERT(DATE,'26-jul-2016')
    FROM rvlfSchedulingReport s        
     INNER JOIN rvlfNotificationList n ON n.NotificationType = 5 AND n.TypeID=s.ReportScheduleId        
     INNER JOIN rvlfReportTypes rt ON s.ReportTypesId = rt.ReportTypesId        
     INNER JOIN rvlfOrganization g ON g.OrganizationId = s.OrganizationId        
     INNER JOIN rvlfOrganizationSolution t ON s.OrganizationId = t.OrganizationId        
     INNER JOIN rvlfTrinetraSolutions ts ON ts.SolutionId = t.SolutionId        
     INNER JOIN rvlfFleet f ON f.FleetId = s.FleetId        
     --LEFT OUTER JOIN rvlfVehicleAssignment va ON va.BoxId in  (select * from rvlf_fn_ConvertArrayToTable(s.VehicleId,','))        
     --LEFT OUTER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId        
     INNER JOIN rvlfUser u On n.UserID = u.UserId        
     INNER JOIN rvlfUserPreferences p ON u.UserId = p.UserId        
     INNER JOIN rvlfTimeZones z On p.TimezoneId = z.TimeZoneID        
    WHERE         
     (u.Email IS Not NULL AND LEN(u.Email) > 0 ) and  s.organizationid in (294)      
     AND (@bigScheduledID IS NULL OR @bigScheduledID='' OR s.ReportScheduleId = @bigScheduledID)        
     --AND (@dtStartDate IS NULL or s.NextGenerationDateTime BETWEEN @dtStartDate and @dtEndDate)        
    -- AND (@dtStartDate IS NULL or (s.NextGenerationDateTime <@dtStartDate AND CONVERT(DATE,s.NextGenerationDateTime)   
    --  BETWEEN CONVERT(DATE,DATEADD(DD,-3,getutcdate())) AND CONVERT(DATE,getutcdate()))) 
	 AND s.CanGenerate = 1 and n.Email = 1 -- and s.IsScheduled = 1   
            
--    -- update         
--    UPDATE rvlfSchedulingReport SET IsLocked = 1 , LockedDateTime = SYSUTCDATETIME ()         
--    WHERE (@bigScheduledID IS NULL OR @bigScheduledID='' OR ReportScheduleId = @bigScheduledID)        
--     AND (@dtStartDate IS NULL or NextGenerationDateTime BETWEEN @dtStartDate and @dtEndDate)        
--     AND CanGenerate = 1 AND ReportScheduleId IN        
--     (SELECT  s.ReportScheduleId FROM rvlfSchedulingReport s        
--     INNER JOIN rvlfNotificationList n ON n.NotificationType = 5 AND n.TypeID=s.ReportScheduleId        
--     INNER JOIN rvlfReportTypes rt ON s.ReportTypesId = rt.ReportTypesId        
--     INNER JOIN rvlfOrganization g ON g.OrganizationId = s.OrganizationId        
--     INNER JOIN rvlfOrganizationSolution t ON s.OrganizationId = t.OrganizationId        
--     INNER JOIN rvlfTrinetraSolutions ts ON ts.SolutionId = t.SolutionId        
--     INNER JOIN rvlfFleet f ON f.FleetId = s.FleetId        
--     LEFT OUTER JOIN rvlfVehicleAssignment va ON va.BoxId in (select * from rvlf_fn_ConvertArrayToTable(s.VehicleId,','))         
--     LEFT OUTER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId        
--     INNER JOIN rvlfUser u On n.UserID = u.UserId        
--     INNER JOIN rvlfUserPreferences p ON u.UserId = p.UserId        
--     INNER JOIN rvlfTimeZones z On p.TimezoneId = z.TimeZoneID        
--    WHERE         
--     (u.Email IS Not NULL AND LEN(u.Email) > 0 )        
--     AND (@bigScheduledID IS NULL OR @bigScheduledID='' OR s.ReportScheduleId = @bigScheduledID)        
--     AND (@dtStartDate IS NULL or s.NextGenerationDateTime BETWEEN @dtStartDate and @dtEndDate)        
--     --AND (@dtStartDate IS NULL or s.NextGenerationDateTime <@dtStartDate)        
--     AND s.CanGenerate = 1)        
--   END        
           
 SET NOCOUNT OFF        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetScheduleReportsSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    
CREATE  PROCEDURE [dbo].[rvlf_sp_GetScheduleReportsSettings]        
 @bigReportScheduleId bigint = NULL,        
 @bigOrganizationID bigint,        
 @bigQueryingUser bigint = 0        
AS  
/******************************************************************************/        
-- Name  : rvlf_sp_GetScheduleReportsSettings null, 6, 140        
-- Description : To get the Schedule Reports Settings        
-- Author  : Kumuthini. L        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>>   Initial Reason        
--    : 03-Mar-2010 Kumuthini Created Intial Version         
--    : 12-Mar-2010 MJJC  Included the status and required information for         
--           converting the date and time to GMT.        
--              :   13-Mar-2010 Kumu        Included Effective To for checking status Expired        
--    : 22-Mar-2010 MJJC  Included last generation date time       
--    : 05-Aug-2011 Ranjith Date format included       
--    : 24-Aug-2013 Sakthi Code included for fortnightly based reports      
/******************************************************************************/        
BEGIN        
 SET NOCOUNT ON         
           
  DECLARE @HoursToBeAdded INT = 0        
  DECLARE @MinsToBeAdded INT = 0        
  DECLARE @DefaultDateFormat INT = 0        
  -- SELECT @HoursToBeAdded = tz.HoursToBeAdded, @MinsToBeAdded = tz.MinToBeAdded        
  -- 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        
        
   SELECT @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        
          
          
  SELECT @HoursToBeAdded = T.HoursToBeAdded, @MinsToBeAdded = T.MinToBeAdded         
  FROM rvlfOrganization Org        
  INNER JOIN rvlfCountry C ON Org.CountryId = C.CountryID        
  INNER JOIN rvlfTimezones T ON C.TimezoneID = T.TimeZoneID        
  WHERE OrganizationId = @bigOrganizationID        
        
  SELECT SR.ReportScheduleId, SR.ReportTypesId, RT.ReportTypesName, SR.FleetId, F.FleetName, SR.VehicleId,     
  --ISNULL(V.VehicleDescription,'All') AS VehicleDescription,    
 CASE WHEN SR.VehicleId IS NULL OR SR.VehicleId='0' or SR.VehicleId='' THEN 'All' ELSE          
 STUFF((SELECT ','+(isnull(vp.VehicleDescription,'ALL'))        
 FROM rvlfVehicle vp INNER JOIN rvlfVehicleAssignment VA ON vp.VehicleId = VA.VehicleId          
 WHERE VA.BoxId IN  (SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(SR.VehicleId,',')) FOR XML PATH('')),1,1,'')  END AS VehicleDescription,         
       
         convert(varchar,DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.EffectiveFrom)),@DefaultDateFormat) + ' '+ convert(varchar,cast(DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.EffectiveFrom))as time),22) AS EffectiveFrom,        
         convert(varchar,DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.EffectiveTo)),@DefaultDateFormat) + ' ' + convert(varchar,cast(DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.EffectiveTo)) as time),22) AS EffectiveTo,        
         DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.EffectiveFrom)) AS EffectiveFromSort,      
         --DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.EffectiveFrom)) AS EffectiveFrom,                 
         DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.EffectiveTo)) AS EffectiveToSort,        
         DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.ReportFrom)) AS ReportFrom,        
         DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.ReportTo)) AS ReportTo,        
         DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.GenerateReportOn)) AS GenerateReportOn,        
         DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.ReportStartDate)) AS ReportStartDate,        
         DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.ReportEndDate)) AS ReportEndDate,        
         @MinsToBeAdded as MinsToBeAdded, @HoursToBeAdded as HoursToBeAdded,        
         SR.IsSummaryVisible, SR.IsDetailsVisible, SR.ShowHideOptions,         
         SR.ReportParameters, SR.SortBy, SR.SortDirection, SR.FileExtension,        
         CASE SR.Frequency WHEN 0 THEN 'Daily' WHEN 1 THEN 'Weekly' WHEN 2 THEN 'Monthly' WHEN 3 THEN 'Fortnightly' END AS Frequency,        
         SR.IsLocked, SR.CanGenerate, SR.WeekDayFrom, SR.WeekDayTo, SR.WeekDayOn, SR.DayOfMonth, SR.CreatedDateTime,       
         convert(varchar,DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.ModifiedDateTime)),@DefaultDateFormat) + ' ' + convert(varchar,cast(DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.ModifiedDateTime)) as time),22)  as ModifiedDateTime
,  
  convert(varchar,DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.NextGenerationDateTime)),@DefaultDateFormat) + ' ' + convert(varchar,cast(DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.NextGenerationDateTime)) as time),22) AS NextGenerationDateTime,        
         DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.NextGenerationDateTime)) AS NextGenerationDateTimeSort,      
         ISNULL(dbo.rvlf_fn_GetNotificationsList(5, SR.ReportScheduleId, 1,1,0),'') as EmailList,         
         REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(5, SR.ReportScheduleId, 1,0,1),''),',',', ') as EmailUserNameList,        
         CASE SR.CanGenerate WHEN 0 THEN   
     CASE WHEN SR.ReportEndDate IS NOT NULL AND SR.EffectiveTo IS NOT NULL  THEN         
       CASE WHEN SR.ReportEndDate >= SR.EffectiveTo /* Expired */ THEN 1        
         --WHEN SR.ReportEndDate > SYSUTCDATETIME () /* Aborted */ THEN 2 END        
         ELSE 4 END        
      WHEN SR.ReportEndDate IS NULL THEN 2        
      ELSE         
              
       CASE WHEN SR.EffectiveTo IS NOT NULL THEN         
        CASE WHEN SR.EffectiveTo < SYSUTCDATETIME() /* Expired */ THEN 1        
          WHEN SR.EffectiveTo > SYSUTCDATETIME () /* Aborted */ THEN 2 END        
       ELSE         
               
         /* Aborted */ 2         
               
       END        
      END        
     ELSE         
     CASE WHEN SR.IsLocked  = 1 /* Under Processing */ THEN 3 ELSE /* Can be scheduled */ 4 END        
         END as ReportStatus,        
           CASE SR.CanGenerate        
     WHEN 0 THEN        
     CASE WHEN SR.ReportEndDate IS NOT NULL AND SR.EffectiveTo IS NOT NULL  THEN         
       CASE WHEN SR.ReportEndDate >= SR.EffectiveTo THEN 'Expired'        
         ELSE 'Can be scheduled' END        
      WHEN SR.ReportEndDate IS NULL THEN 'Aborted'        
      ELSE         
              
       CASE WHEN SR.EffectiveTo IS NOT NULL THEN         
        CASE WHEN SR.EffectiveTo < SYSUTCDATETIME() THEN 'Expired'        
          WHEN SR.EffectiveTo > SYSUTCDATETIME () THEN 'Aborted' END        
       ELSE         
               
         'Aborted'        
               
       END        
      END        
     ELSE         
     CASE WHEN SR.IsLocked  = 1 THEN 'Under Processing' ELSE 'Can be scheduled' END        
         END as ReportStatusDetails, DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.lastGeneratedDateTime )) as lastGeneratedDateTime,CategoryTypesId as ReportCategoryId          
     FROM rvlfSchedulingReport SR        
     INNER JOIN rvlfReportTypes RT ON RT.ReportTypesId = SR.ReportTypesId     
      Inner join rvlfNotificationList NL on SR.ReportScheduleId=NL.TypeID and NL.NotificationType=5  
     inner join rvlfUser U on NL.UserID=U.UserId and U.IsHidden=0     
     LEFT OUTER JOIN rvlfVehicleAssignment VA ON VA.BoxId IN (SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(SR.VehicleId,',')) --= SR.VehicleId        
     LEFT OUTER JOIN rvlfVehicle V ON V.VehicleId = VA.VehicleId        
     LEFT OUTER JOIN rvlfFleet F ON F.FleetId = SR.FleetId        
     WHERE SR.OrganizationId = @bigOrganizationID AND SR.IsDeleted = 0 AND (@bigReportScheduleId IS NULL OR @bigReportScheduleId='' OR SR.ReportScheduleId = @bigReportScheduleId)        
  AND SR.IsScheduled = 1  and SR.Createdby>0       
     --AND sr.ReportTypesId =3        
     --WHERE SR.OrganizationId = @bigOrganizationID AND SR.IsDeleted = 0 AND SR.ReportScheduleId = 0        
      group by SR.ReportScheduleId, SR.ReportTypesId, RT.ReportTypesName, SR.FleetId, F.FleetName, SR.VehicleId,SR.EffectiveFrom,SR.EffectiveTo,SR.ReportFrom,      
       SR.ReportTo,SR.GenerateReportOn,SR.ReportStartDate,SR.ReportEndDate,SR.IsSummaryVisible,SR.IsDetailsVisible,SR.ShowHideOptions,SR.ReportParameters,SR.SortBy      
       ,SR.SortDirection,SR.FileExtension,SR.Frequency,SR.IsLocked,SR.CanGenerate,SR.WeekDayFrom,SR.WeekDayOn,SR.WeekDayTo,SR.DayOfMonth,SR.CreatedDateTime,      
       SR.ModifiedDateTime,SR.NextGenerationDateTime,SR.lastGeneratedDateTime,RT.CategoryTypesId      
 SET NOCOUNT OFF        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSchedulingDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetSchedulingDetails]     
 @bigVehicleId bigint=null,    
 @bigFleetId bigint=null,     
 @dtFromdateTime datetime=null,    
 @dtTodateTime datetime=null,     
 @bigOrganizationId bigint=null,    
 @bigQueryingUser bigint=null     
AS    
/****************************************************************************************/    
-- Name    : [rvlf_sp_GetSchedulingDetails]null,8,'2011-01-03','2011-02-09',6    
-- Description   : To get the scheduling of commands DETAILS    
-- Author    : Narayanasamy.V    
-- Created Date  : 16-Dec-2010    
--  Modified Date :    
/***************************************************************************************/    
BEGIN    
 SET NOCOUNT ON      
     
 DECLARE @HoursToBeAdded INT = 0    
 DECLARE @MinsToBeAdded INT = 0     
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded        
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz    
    ON up.TimeZoneId = tz.TimeZoneId AND(@bigQueryingUser IS NULL OR @bigQueryingUser='' OR up.UserId = @bigQueryingUser)    
     
 --check any not executed schedules are avilable or not    
 IF EXISTS(SELECT ScheduleId FROM rvlfScheduleOfCommandsMaster     
  WHERE ScheduleId NOT IN(SELECT ScheduleId FROM rvlfSchedulingOfCommandsLog) AND EffectiveTo < GETDATE())    
  BEGIN    
   INSERT INTO rvlfSchedulingOfCommandsLog (ScheduleId,ExecutionOn,IsCommandSend,ResponseMsg,[No.ofTries],ResponseId)    
    select ScheduleId,EffectiveTo,0,'Expired',0,5  from rvlfScheduleOfCommandsMaster where ScheduleId not in(select ScheduleId  from rvlfSchedulingOfCommandsLog) and EffectiveTo < GETDATE()    
  END    
      
 SELECT SM.ScheduleId,V.VehicleDescription,C.BoxCmdOutTypeName,CONVERT(varchar,SM.EffectiveFrom,106) as EffectiveFrom,    
  CASE WHEN convert(varchar,SM.EffectiveTo,106) IS NULL THEN 'No End Date' ELSE convert(varchar,SM.EffectiveTo,106) END as EffectiveTo,     
  SM.ExecutionOn  AS ExecutionType,SM.Frequency,SM.PacketInfo,v.VehicleId,l.[No.ofTries] as [No.ofRetries],    
   CASE WHEN SM.Frequency=1 THEN 'Daily Once' WHEN SM.Frequency=2 THEN '3 Days Once' WHEN SM.Frequency=0 THEN 'Only Once' ELSE 'Weekly Once' END AS FrequencyName,    
   C.BoxCmdOutTypeCode,CONVERT(varchar,SM.NextExecutionOn,106) as NextExecutionOn ,    
   CASE WHEN L.ResponseMsg='Expired' THEN CONVERT(varchar(20),DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,L.ExecutionOn)),113)+' - Expired' ELSE CONVERT(varchar(20),DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,L.ExecutionOn)),113) END as ExecutionOn ,    
   CASE WHEN L.IsCommandSend=1 THEN 'Success' WHEN L.IsCommandSend=0 AND L.ResponseMsg='Expired' THEN 'Expired' ELSE 'Failed' END AS commandStatus,    
   L.ScheduleLogId            
  FROM rvlfScheduleOfCommandsMaster SM    
   INNER JOIN rvlfBoxCmdOutType C ON C.BoxCmdOutTypeId=SM.BoxCmdOutTypeId -- Collate SQL_Latin1_General_CP1_CS_AS     
   INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=SM.Boxid     
   INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId     
   INNER JOIN rvlfSchedulingOfCommandsLog L ON L.ScheduleId =SM.ScheduleId     
   INNER JOIN rvlfFleetVehicles FV ON FV.VehicleId=V.VehicleId     
   INNER JOIN rvlfFleet F ON F.FleetId=FV.FleetId     
  WHERE (@bigFleetId IS NULL OR @bigFleetId='' OR F.FleetId=@bigFleetId)    
   AND SM.OrganizationId=@bigOrganizationId     
   AND(@bigVehicleId IS NULL OR @bigVehicleId='' OR V.VehicleId=@bigVehicleId)       
   AND CONVERT(DATE,L.ExecutionOn) BETWEEN CONVERT(DATE,@dtFromdateTime) AND CONVERT(DATE,@dtTodateTime)    
  ORDER BY L.ExecutionOn DESC    
 SET NOCOUNT OFF    
END    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSchedulingOfCommands]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetSchedulingOfCommands]   
 @bigSchedulingId bigint=null,   
 @bigOrganizationId bigint=null    
AS  
/****************************************************************************************/  
-- Name    : [rvlf_sp_GetSchedulingOfCommands]null,6  
-- Description   : To get the scheduling of commands information  
-- Author    : Narayanasamy.V  
-- Created Date  : 13-Dec-2010  
--  Modified Date :  
/***************************************************************************************/  
BEGIN  
 SET NOCOUNT ON    
 SELECT SM.ScheduleId,V.VehicleDescription,C.BoxcmdTypeDesc as BoxCmdOutTypeName,CONVERT(varchar,SM.EffectiveFrom,106) as EffectiveFrom,  
 CASE WHEN convert(varchar,SM.EffectiveTo,106) IS NULL THEN 'No End Date' ELSE convert(varchar,SM.EffectiveTo,106) END as EffectiveTo,SM.ExecutionOn  AS ExecutionType,  
   SM.Frequency,SM.PacketInfo,v.VehicleId,sm.[No.ofRetries],  
   CASE WHEN SM.Frequency=1 THEN 'Daily Once' WHEN SM.Frequency=2 THEN '3 Days Once' WHEN SM.Frequency=0 THEN 'Only Once' ELSE 'Weekly Once' END AS FrequencyName,  
    C.BoxCmdOutTypeCode AS CommandCode,CONVERT(varchar,SM.NextExecutionOn,106) as NextExecutionOn        
  FROM rvlfScheduleOfCommandsMaster SM  
   INNER JOIN rvlfBoxCmdOutType C ON C.BoxCmdOutTypeId=SM.BoxCmdOutTypeId -- Collate SQL_Latin1_General_CP1_CS_AS   
   INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =SM.Boxid   
   INNER JOIN rvlfVehicle V ON V.VehicleId=VA.VehicleId   
  WHERE (@bigSchedulingId IS NULL OR @bigSchedulingId='' OR SM.ScheduleId=@bigSchedulingId)  
   AND SM.OrganizationId=@bigOrganizationId     
   AND (CASE WHEN SM.EffectiveTo IS NULL AND SM.Frequency=0 AND SM.NextExecutionOn IS NOT NULL THEN SM.NextExecutionOn ELSE SM.EffectiveTo END IS NULL  OR   
    (CASE WHEN CONVERT(DATE,SM.EffectiveTo)>=CONVERT(DATE,GETUTCDATE()) THEN   
     CASE WHEN SM.NextExecutionOn IS NULL THEN CONVERT(DATE,DATEADD(D,1,SM.EffectiveTo))   
      ELSE  CONVERT(DATE, SM.NextExecutionOn) END ELSE CONVERT(DATE,SM.EffectiveTo) END)>CONVERT(DATE,GETUTCDATE()))    
 SET NOCOUNT OFF  
END  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSchoolDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================        
-- Author:  Selvakumar        
-- Create date: 27-06-2012        
-- Description: Get the School Details        
-- =============================================        
CREATE PROCEDURE [dbo].[rvlf_sp_GetSchoolDetails]      
@OrganizationID bigint =null      
AS        
BEGIN      
 SELECT SchoolName,SchoolID,GeozoneId from rvlfSchoolMaster      
 where OrganizationID = @OrganizationID and GeozoneId is not null     
 END        

GO
/****** Object:  StoredProcedure [dbo].[rvlf_SP_GetSchoolInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================                  
-- Author:  Selvakumar.S.V                  
-- Create date: 08-Jun-2012                  
-- Description: Manage Student information                 
-- =============================================                  
CREATE PROCEDURE [dbo].[rvlf_SP_GetSchoolInfo]                  
@SchoolID varchar(max) = null,              
@OrganizationID bigint = null,              
@Mode tinyint =0,              
@SchoolName nvarchar(100)=null,               
@StationID nvarchar(30) =null,               
@FleetName nvarchar(50) =null,               
@StartTime varchar(15) =null,              
@EndTime varchar(15) =null,              
@AddressLine1 nvarchar(200)=null,               
@AddressLine2 nvarchar(200)=null,               
@City nvarchar(50)=null,               
@Street nvarchar(100)=null,      
@Region nvarchar(100)=null,      
@Country nvarchar(50)=null,                
@CreatedBy bigint=0,              
@ModifiedBy bigint=0,          
@GeozoneId bigint = 0,          
@WaitingTime bigint = 0,          
@MobileNo nvarchar(20)=null,          
@ReportingPerson bigint = null
          
AS          
BEGIN          
IF(@Mode =1)          
	BEGIN          
		SELECT	f.FleetName as 'StationName',og.GeozoneId,
				--(case when waitingtime >=60 then cast((WaitingTime/60) as varchar) + ' Hour(s)'  else WaitingTime + ' mins' end) as WaitTime,
				(Case When WaitingTime = '15' then '15 Mins' 
					  When WaitingTime = '30' then '30 Mins' 
					  When WaitingTime = '60' then '1 Hour' 
					  When WaitingTime = '90' then '1.5 Hour' 
					  When WaitingTime = '120' then '2 Hours' 
					  When WaitingTime = '150' then '2.5 Hours' 
					  When WaitingTime = '180' then '3 Hours' End) as WaitTime,* 
		FROM rvlfSchoolMaster sm          
		LEFT OUTER JOIN rvlfFleet f on f.StationID = sm.StationID           
		LEFT OUTER JOIN rvlfOrganizationGeozone og on og.GeozoneId = sm.GeozoneId and og.OrganizationId = @OrganizationID      
		WHERE sm.OrganizationID = @OrganizationID
		         
		SELECT * FROM rvlfSchoolMaster WHERE OrganizationID = @OrganizationID
		SELECT * FROM rvlfSchoolMaster WHERE OrganizationID = @OrganizationID and SchoolID=@SchoolID
	END          
ELSE IF(@Mode =2)          
BEGIN          
 DELETE FROM rvlfSchoolMaster WHERE  SchoolID in(select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@SchoolID,',')) and OrganizationID =@OrganizationID              
END          
ELSE IF(@Mode =3)          
BEGIN          
 insert into rvlfSchoolMaster(SchoolName,StationID,StationName,StartTime,EndTime,AddressLine1,AddressLine2,          
 Street,City,Country,Region,OrganizationID,CreatedBy,CreatedDateTime,GeozoneId,WaitingTime,MobileNo,ReportingPerson)
 values(@SchoolName,@StationID,@FleetName,@StartTime,@EndTime,@AddressLine1,@AddressLine2,          
 @Street,@City,@Country,@Region,@OrganizationID,@CreatedBy,GETUTCDATE(),@GeozoneId,@WaitingTime,@MobileNo,@ReportingPerson)
END          
ELSE IF(@Mode =4)          
BEGIN          
 Update rvlfSchoolMaster set SchoolName =@SchoolName,StationID=@StationID,StationName=@FleetName,StartTime=@StartTime,EndTime=@EndTime,          
 AddressLine1=@AddressLine1,AddressLine2=@AddressLine2,Street=@Street,          
 City=@City,Country=@Country,Region=@Region,OrganizationID=@OrganizationID,Modifiedby=@ModifiedBy,ModifiedDate=GETUTCDATE(),geozoneId=@GeozoneId,      
 WaitingTime=@WaitingTime,MobileNo=@MobileNo,ReportingPerson=@ReportingPerson
 where SchoolID =@SchoolID and OrganizationID =@OrganizationID          
END          
ELSE IF(@Mode =5)          
BEGIN          
 SELECT COUNT(*) as 'Result' FROM rvlfSchoolMaster               
 WHERE              
 ((@SchoolID IS NULL OR @SchoolID='') OR SchoolID = @SchoolID)               
 AND SchoolID <> @SchoolID          
END          
ELSE IF(@Mode =6)          
BEGIN          
 SELECT COUNT(*) as 'Result' FROM rvlfSchoolMaster               
 WHERE              
 ((@SchoolID IS NULL OR @SchoolID='') OR SchoolID = @SchoolID)               
 AND SchoolID <> @SchoolID          
END          
ELSE IF(@Mode =7)          
BEGIN          
 SELECT * FROM rvlfSchoolMaster s    
 inner join rvlfStudentMaster sm on sm.schoolId = s.schoolId and sm.IsDelete = 0             
 WHERE              
 s.SchoolID in(select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@SchoolID,',')) and s.OrganizationID =@OrganizationID       
END      
ELSE IF(@Mode =8)          
BEGIN          
 SELECT * FROM rvlfSchoolMaster               
 WHERE  Schoolname =  @SchoolName and OrganizationID =@OrganizationID    
END        
ELSE IF(@Mode =9)          
BEGIN          
 SELECT * FROM rvlfSchoolMaster               
 WHERE  Schoolname =  @SchoolName and OrganizationID =@OrganizationID    
  AND SchoolID <> @SchoolID    
END       
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSensorDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetSensorDetails]  
 @VehicleID int = Null,  
 @bigOrganizationId bigint = Null,  
 @bigUserId bigint = Null    
AS  
/**************************************************************************************************/  
-- Name  : [rvlf_sp_GetSensorDetails]NULL,1,44  
-- Description : To get the sensor details.  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 18-Mar-2010 To get the sensor details  
--    : 19-Aug-2010 Removed the Display Name  
/**************************************************************************************************/  
  
BEGIN  
 SELECT VEH.VehicleId,VehicleDescription,LOCATION,Notify,Warning,Critical, REPLACE(Email,';','; ') as Emails,  
     CASE WHEN  
  (CASE WHEN Notify='true' THEN 'Notify' ELSE '' END +      
   CASE WHEN Warning='true' THEN 'Warning' ELSE '' END +   
   CASE WHEN Critical='true' THEN 'Critical' ELSE '' END)='' THEN 'No Alarm' ELSE  
  (CASE  WHEN Notify='true' THEN (CASE WHEN (Warning='true' or Critical='true') THEN 'Notify; ' ELSE 'Notify' END ) ELSE '' END +      
   CASE WHEN Warning='true' THEN (CASE WHEN Critical='true' THEN 'Warning; ' ELSE 'Warning' END ) ELSE '' END +   
   CASE WHEN Critical='true' THEN 'Critical' ELSE '' END)END as Severity,  
     ISNULL(dbo.rvlf_fn_GetNotificationsList(4, veh.VehicleID, 1,1,0),'') as EmailList,   
  ISNULL(dbo.rvlf_fn_GetNotificationsList(4, veh.VehicleID, 0,1,0),'') as SMSList,  
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(4, veh.VehicleID, 1,0,1),''),',',', ') as EmailUserNameList,  
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(4, veh.VehicleID, 0,0,1),''),',',', ') as SMSUserNameList,  
  tz.TimeZoneName,veh.VehicleDescription AS DisplayName,veh.location,VA.BoxId    
 FROM rvlfVehicle VEH  
  INNER JOIN rvlfTimeZones tz on veh.TimeZone = tz.TimeZoneID  
  INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=VEH.VehicleId   
 WHERE (@VehicleID IS NULL OR @VehicleID='' OR VEH.VehicleId=@VehicleID OR @VehicleID=0)  
  AND(@bigOrganizationId IS NULL OR @bigOrganizationId='' OR VEH.OrganizationId=@bigOrganizationId)  
  AND(@bigUserId IS NULL OR @bigUserId='' OR VEH.CreatedBy=@bigUserId)  
  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSentMsgs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetSentMsgs](@VehicleID int,@startdate datetime,@enddate datetime)  
AS  
BEGIN  
 select V.VehicleID,V.VehicleDescription,VA.BoxID,SentDateTime,CT.BoxCmdOutTypeName,UserID,Priority,
 			CASE WHEN Acknowledged = 1 THEN 'True' 
				WHEN Acknowledged = 0 THEN 'False' 
				WHEN  Acknowledged = 2 THEN 'Success'
				WHEN  Acknowledged = 3 THEN 'Update Failed'
				WHEN  Acknowledged = 4 THEN 'CRC Incorrect'
				WHEN  Acknowledged = 5 THEN 'No Communication'
				WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'
				ELSE 'Nothing' END AS Acknowledged
 --CASE WHEN Acknowledged =0 THEN '' WHEN Acknowledged=1 THEN 'True' END as Acknowledged 
 from rvlfMsgOutHst OH  
   INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID  
   INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId  
  WHERE V.VehicleID = @vehicleID and SentDateTime Between @startdate and @enddate order by sentDatetime desc  
END  
-- rvlf_sp_GetSentMsgs 2,'2009-05-28 11:00:00','2009-05-30 12:000:00'


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetServiceBasedNotifications]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetServiceBasedNotifications]
	@bigServiceDetailsId bigint,
	@bigServiceCategoryId bigint
AS
/**************************************************************************************/
--	Name		:	rvlf_sp_GetServiceBasedNotifications
--	Description	:	To get the maintenance service based Email Ids
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	24-Jun-2010		Created Intial Version 
/**************************************************************************************/
BEGIN
SET NOCOUNT ON 
			
	SELECT M.ServiceName, dbo.rvlf_fn_GetEmailIds(dbo.rvlf_fn_GetNotificationsList(7, M.ServiceId, 1,1,0)) AS Email
	FROM rvlfMaintenanceService M
	INNER JOIN rvlfMaintenanceCategoryService mc ON mc.ServiceId = M.ServiceId
	WHERE mc.ServiceCategoryId = @bigServiceCategoryId AND M.ServiceId NOT IN 
		(SELECT ServiceId FROM rvlfMaintenanceServiceDetails WHERE ServiceDetailsId = @bigServiceDetailsId)
		AND ISNULL(dbo.rvlf_fn_GetNotificationsList(7, M.ServiceId, 1,1,0),'') <> ''

SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetServiceCategoryDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetServiceCategoryDetails]
	@bigServiceCategoryId bigint = NULL,
	@bigOrganizationId bigint
AS
/**************************************************************************************/
--	Name		:	rvlf_sp_GetServiceCategoryDetails
--	Description	:	To get the maintenance service category details
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	09-Jun-2010		Created Intial Version 
/**************************************************************************************/
BEGIN
SET NOCOUNT ON 
			
	SELECT C.ServiceCategoryId, C.ServiceCategoryName, C.ServiceCatDescription,
	0 as AssignedStatus,
	--CASE WHEN EXISTS(SELECT MP.ServiceCategoryId FROM rvlfMaintenancePlanDetails MP INNER JOIN rvlfVehiclePlanAssignment VP ON VP.PlanId = MP.PlanId
    --   WHERE MP.ServiceCategoryId = C.ServiceCategoryId) THEN 1 ELSE 0 END VehicleAssigned
    0 AS VehicleAssigned
	FROM rvlfMaintenanceServiceCategory C  
	WHERE C.OrganizationId = @bigOrganizationId AND 
	 (@bigServiceCategoryId IS NULL OR @bigServiceCategoryId = '' OR C.ServiceCategoryId = @bigServiceCategoryId) order by c.ServiceCategoryName

SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetServiceHistory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[rvlf_sp_GetServiceHistory]  
 @bigOrganizationID bigint,  
 @bigFleetId bigint = NULL,  
 @bigVehicleId bigint = NULL,  
 @dtStartDate DateTime = NULL,  
 @dtEndDate DateTime = NULL,  
 @bigPlanId bigint = NULL,  
 @intServiceType int = NULL,  
 @tiServiceStatus tinyint = NULL,  
 @tiMaintenanceType tinyint = NULL,  
 @bigQueryingUser bigint = 0,  
 @intBoxID varchar(max) = NULL  
AS   
/**************************************************************************************/  
-- Name  : rvlf_sp_GetServiceHistory 6,8,NULL,'11/20/2018 12:54:00 PM','11/24/2019 12:54:00 PM',NULL,NULL,NULL,Null,398,'0'  
-- Description : To get the vehicle maintenance history details  
-- Author  : Jeyanthi.S  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 06-Oct-2010  Kumuthini Created Intial Version   
--       :   07-Feb-2011  Kumuthini  Changed the procedure based on the fine tunings and included the Adhoc services  
/**************************************************************************************/  
BEGIN  
SET NOCOUNT ON   
  
 Declare @dtFDate datetime =@dtStartDate  
 Declare @dtEDate datetime =@dtEndDate  
   
 DECLARE @Distance varchar(20)  
 DECLARE @ConversionFactor numeric (10,2) = 1.0  
 DECLARE @DefaultDateFormat INT = 0  
   DECLARE @HoursToBeAdded INT = 0    
 DECLARE @MinsToBeAdded INT = 0   
  
 SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,    
     @Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END,  
      @HoursToBeAdded = tz.HoursToBeAdded, @MinsToBeAdded = tz.MinToBeAdded ,        
     @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 = @bigQueryingUser    
   
 CREATE TABLE #tempServiceHistory(VehicleId bigint, VehicleDescription varchar(20), Vin varchar(20), LicensePlate varchar(20), MakeName varchar(200),  
 ModelName varchar(200), Color varchar(20), ModelYear smallint, PlanId bigint, PlanName varchar(100), ServiceType varchar(15), ServicesPlanned varchar(max),   
 ServicesDone varchar(max), Comments varchar(250), ServicedOn DateTime, PlannedCost numeric(18,2), ServiceCost numeric(18,2),   
 [Status] varchar(10), [Type] varchar(10))   
  
 INSERT INTO #tempServiceHistory(VehicleId, VehicleDescription, Vin, LicensePlate, MakeName, ModelName, Color, ModelYear, PlanId, PlanName,  
 ServiceType, ServicesPlanned, ServicesDone, Comments, ServicedOn, PlannedCost, ServiceCost, [Status], [Type])  
   
 (SELECT vp.VehicleId,v.VehicleDescription,Vin,LicensePlate,M.MakeName,Mo.ModelName,Color,ModelYear,mp.PlanId, mp.PlanName,   
  (CASE WHEN vm.ServiceType = 0 THEN 'Engine Hours' WHEN vm.ServiceType = 2 THEN 'Time Based' END) ServiceType,   
  dbo.rvlf_fn_GetMaintenanceServices(5, mp.PlanId, null) AS ServicesPlanned, CASE WHEN vm.Status = 2 THEN 'N/A' ELSE dbo.rvlf_fn_GetMaintenanceServices(1, null, vm.ServiceDetailsId) END AS ServicesDone,   
  vm.Comments, vm.ExecutedOn AS ServicedOn, mp.TotalPlannedCost AS PlannedCost, ISNULL(vm.ServiceCost, 0) AS ServiceCost,  
  CASE WHEN vm.Status = 0 THEN 'Pending' WHEN vm.Status = 1 THEN 'Completed'   
    WHEN vm.Status = 2 THEN 'Skipped' WHEN vm.Status = 3 THEN 'Dismissed' END AS [Status], 'Planned' AS [Type]      
  FROM rvlfVehicleMaintenanceService vm  
  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId  
  INNER JOIN rvlfVehicleAssignment va ON va.VehicleId = vp.VehicleId  
  INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId   
  INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId  
  LEFT JOIN rvlfMake M ON M.MakeId = V.MakeId   
  LEFT JOIN rvlfModel Mo ON Mo.ModelId = V.ModelId  
  WHERE mp.OrganizationId = @bigOrganizationID AND IsNearing = 1 AND (vm.Status <> 0 AND (@tiServiceStatus IS NULL OR vm.Status = @tiServiceStatus))   
   AND CONVERT(DATE, vm.ExecutedOn, 101) BETWEEN CONVERT(DATE, @dtStartDate, 101) AND CONVERT(DATE, @dtEndDate, 101)  
   AND ((@bigPlanId IS NULL) OR (@bigPlanId = 0) OR (vp.PlanId = @bigPlanId))  
   AND (@intServiceType IS NULL OR ServiceType = @intServiceType)  
   AND (@tiMaintenanceType IS NULL OR @tiMaintenanceType = 0 OR @tiMaintenanceType = 1)  
   AND (@intBoxID  IS NULL OR @intBoxID  ='0' OR va.BoxId in(select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))   
   
 UNION  
   
 SELECT v.VehicleId, v.VehicleDescription, Vin, LicensePlate, M.MakeName, Mo.ModelName, Color, ModelYear, 0 AS PlanId, 'N/A' AS PlanName,  
 'N/A' AS ServiceType, 'N/A' AS ServicesPlanned, dbo.rvlf_fn_GetMaintenanceServices(6, null, AdhocServiceId) AS ServicesDone, ad.Comments, ad.ExecutionOn,  
 0 AS PlannedCost, ad.TotalServiceCost AS ServiceCost, 'Completed' AS [Status], 'Adhoc' AS Type  
 FROM rvlfAdhocServices ad  
 INNER JOIN rvlfVehicle v ON v.VehicleId = ad.VehicleId  
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId  
 INNER JOIN rvlfVehicleAssignment va ON va.VehicleId = v.VehicleId  
 LEFT JOIN rvlfMake M ON M.MakeId = V.MakeId   
 LEFT JOIN rvlfModel Mo ON Mo.ModelId = V.ModelId  
 WHERE v.OrganizationId = @bigOrganizationID AND (@tiServiceStatus IS NULL OR 1 = @tiServiceStatus)  
 AND (CONVERT(DATE, ad.ExecutionOn, 101) BETWEEN CONVERT(DATE, @dtStartDate, 101) AND CONVERT(DATE, @dtEndDate, 101))  
 AND (@bigPlanId IS NULL OR 0 = @bigPlanId) AND @intServiceType IS NULL  
 AND (@tiMaintenanceType IS NULL OR @tiMaintenanceType = 0 OR @tiMaintenanceType = 2) AND (@intBoxID  IS NULL OR @intBoxID   ='0' OR va.BoxId in(select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))))  
   
 ALTER TABLE #tempServiceHistory ADD NoOfPlannedMaintenances int,NoOfServices int, NoOfSkippedServices int, NoOfCompletedServices int, TotPlannedCost numeric(18, 2),  
  TotCostIncurred numeric(18, 2),TotalServiceCost numeric(18, 2), CostDeviation int, NoOfAdhocServices int, TotalAdhocServiceCost numeric(18, 2), AdhocCostDeviation int  
   
 UPDATE sh SET sh.NoOfPlannedMaintenances = (SELECT COUNT([Type]) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId AND sh1.Type = 'Planned'),  
  sh.NoOfServices = (SELECT COUNT([Type]) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId),    
  sh.NoOfSkippedServices = (SELECT COUNT([Type]) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId AND sh1.Type = 'Planned' AND sh1.Status = 'Skipped'),  
  sh.NoOfCompletedServices = (SELECT COUNT([Type]) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId AND sh1.Type = 'Planned' AND sh1.Status = 'Completed'),  
  sh.TotPlannedCost = ISNULL((SELECT SUM(sh1.PlannedCost) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId AND sh1.Type = 'Planned'), 0),  
  sh.TotCostIncurred = ISNULL((SELECT SUM(sh1.ServiceCost) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId), 0),   
  sh.TotalServiceCost = ISNULL((SELECT SUM(sh1.ServiceCost) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId AND sh1.Type = 'Planned'), 0),  
  sh.NoOfAdhocServices = (SELECT COUNT([Type]) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId AND sh1.Type = 'Adhoc'),  
  sh.TotalAdhocServiceCost = ISNULL((SELECT SUM(sh1.ServiceCost) FROM #tempServiceHistory sh1 WHERE sh1.VehicleId = sh.VehicleId AND sh1.Type = 'Adhoc'), 0)  
 FROM #tempServiceHistory sh  
   
 UPDATE #tempServiceHistory SET CostDeviation = (CASE WHEN TotalServiceCost <= TotPlannedCost THEN 0 ELSE (((TotalServiceCost - TotPlannedCost) * 100) / TotPlannedCost) END),  
  AdhocCostDeviation = (CASE WHEN NoOfAdhocServices > 0 THEN 100 ELSE 0 END)  
   
 DECLARE @PlannedCostSummary numeric(18, 2)  
 DECLARE @ActualCostSummary numeric(18, 2)  
 DECLARE @CostDeviationSummary int  
   
 SET @PlannedCostSummary = (SELECT SUM(PlannedCost) FROM #tempServiceHistory)  
 SET @ActualCostSummary = (SELECT SUM(ServiceCost) FROM #tempServiceHistory)  
 select @PlannedCostSummary=case when @PlannedCostSummary=0 then 1 else @PlannedCostSummary end
 SET @CostDeviationSummary = (CASE WHEN @ActualCostSummary <= @PlannedCostSummary THEN 0 ELSE (((@ActualCostSummary - @PlannedCostSummary) * 100) / (case when @PlannedCostSummary=0 then 1 else @PlannedCostSummary end)) END)  
   
    SELECT VehicleId,VehicleDescription,Vin,LicensePlate,MakeName,  
 ModelName,Color,ModelYear,PlanId,PlanName,ServiceType,ServicesPlanned,   
 ServicesDone,Comments,Convert(varchar,ServicedOn,@DefaultDateFormat)  as ServicedOn,ServicedOn AS 'ServicedOnSort',PlannedCost,ServiceCost,   
 [Status],[Type],NoOfPlannedMaintenances,NoOfServices,NoOfSkippedServices,NoOfCompletedServices,TotPlannedCost,TotCostIncurred,TotalServiceCost,
 CostDeviation,NoOfAdhocServices,TotalAdhocServiceCost,AdhocCostDeviation,@PlannedCostSummary AS PlannedCostSummary, @ActualCostSummary AS ActualCostSummary, 
 @CostDeviationSummary AS CostDeviationSummary,(@PlannedCostSummary - @ActualCostSummary) AS CostSavings ,  
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,  
  PasGenerateddate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())  
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate      
    FROM #tempServiceHistory sh   
    ORDER BY CONVERT(DATE, sh.ServicedOn)  
      
      
DROP TABLE #tempServiceHistory
SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetServicePushNotifications]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 28-Mar-2019
-- Description:	For Push notification list.
-- rvlf_sp_GetServicePushNotifications 578,132
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetServicePushNotifications] 
	-- Add the parameters for the stored procedure here
	@bigUserID BIGINT,
	@bigOrganizationID bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	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 top 10 ('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) as Title, (' 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) + '%') as NotificationMessage,CONVERT(varchar,nl.CreateDateTime,@DefaultDateFormat) + ' '+ Convert(varchar,cast(nl.CreateDateTime as time),22) as CreateDateTime
 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 and u.OrganizationId=@bigOrganizationID order by nl.CreateDateTime desc
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetServiceURL_App]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetServiceURL_App]
@ModelCode VARCHAR(256)
AS
/*********************************************************************************************
Procedure Name	: rvlf_sp_GetServiceURL_App 'smm'
Description		: Get the service url for the model
Created By		: Sakthi Gopinath S
Created Date	: 02-Apr-2013
*********************************************************************************************/
BEGIN
SET NOCOUNT ON
	IF EXISTS(SELECT 1 FROM dbo.rvlfOrganization WHERE OrganizationCode=@ModelCode)
	BEGIN
		--SELECT o.OrganizationId,o.OrganizationCode,o.OrganizationDisplayName,ma.ModelCode,oa.URLId,oa.ServiceURL FROM dbo.rvlfModel_App ma 
		--INNER JOIN dbo.rvlfOrganizationServiceURL_App oa ON oa.OrgId=ma.OrganizationId
		--INNER JOIN dbo.rvlfOrganization o ON o.OrganizationId=oa.OrgId
		--WHERE o.ExpiresOn > GETUTCDATE() AND ma.ModelCode=@ModelCode
		
		SELECT o.OrganizationId,o.OrganizationCode,o.OrganizationDisplayName,'NA' AS ModelCode,oa.URLId,oa.ServiceURL FROM 
		dbo.rvlfOrganizationServiceURL_App oa INNER JOIN dbo.rvlfOrganization o ON o.OrganizationId=oa.OrgId
		WHERE o.ExpiresOn > GETUTCDATE() AND o.OrganizationCode=@ModelCode
	END
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSetInvOrderRequest]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
              
CREATE proc [dbo].[rvlf_sp_GetSetInvOrderRequest]             
(                              
@OrderNo bigint=null,                
@OrderReqno varchar(50)=null,                
@Comments varchar(300)=null,                
@Status char(1)='N',                
@bigOrganizationId bigint = Null,                            
@bigUserId bigint = Null,                            
@OrderItems xml=null,               
@DueDate datetime=null,                  
@Operation char(1)                            
)                              
as                                  
/******************************************************************************/                                                                          
-- Name  : rvlf_sp_GetSetInvOrderRequest 2,null,null,null,6,292,null,null,'s'                                      
-- Description : Order Request Details Entry and select                                  
-- Author  : Gopal.R                                    
-- Company  : Angler Technologies                                    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                    
-- Created Date -27-Dec-2014                                     
/******************************************************************************/                                    
begin                                
declare @trancount int;                                              
set @trancount = @@trancount;                              
begin TRY                              
 if @trancount = 0                              
  begin transaction                              
 ELSE                              
  save transaction rvlf_sp_GetSetInvOrderRequest;                
  ----Code Starts-----                  
IF(@Operation= 'I')                
BEGIN                 
INSERT into rvlfInvOrderRequest                 
 (OrderBy,OrderDate,Comments,[Status],IsDelete,OrganizationId,DueDate)              
 values (@bigUserId,GETutcDATE(),@Comments,@Status,0,@bigOrganizationId,@DueDate)                
  --Insert Item detials in the line item tables--                              
 set @OrderNo=(select IDENT_CURRENT('rvlfInvOrderRequest'))           
 INSERT into rvlfInvOrderReqItems(OrderNo,Itemcode,UnitPrice,ReqQty,IssuedQty,TotalAmt,Remarks,IsDelete)                
     SELECT  @OrderNo as OrderNo,x.d.value('Itemcode[1]','varchar(100)') AS ProductName,                                
     x.d.value('UnitPrice[1]','numeric(18,2)')AS ProductId,                                                
     x.d.value('ReqQty[1]','bigint')AS ProductId,                                                
     x.d.value('IssuedQty[1]','bigint')AS ProductId,                                 
     x.d.value('TotalAmt[1]','numeric(18,2)')AS ProductId,                                                
     x.d.value('Remarks[1]','varchar(300)')AS ProductId,0                              
 FROM @OrderItems.nodes('/DocumentElement/OrderItems') x(d)                
          
select OrderReqno,replace(convert(varchar(11),OrderDate,106),' ','-') as OrderDate,UserName,          
replace(convert(varchar(11),DueDate,106),' ','-') as DueDate from rvlfInvOrderRequest a          
inner join rvlfUser b on a.OrderBy=b.UserId          
where OrderNo =(select IDENT_CURRENT('rvlfInvOrderRequest'))          
  --UPDATE Itm set AvailQty= AvailQty + Qty from rvlfInvItemMaster Itm inner join                 
  --(select ItemCode,SUM(IssuedQty) as Qty from rvlfInvOrderReqItems where OrderNo=@OrderNo and IsDelete=0 group by ItemCode) as InvItm               
 --on Itm.Itemcode=InvItm.ItemCode                 
                 
END                
ELSE IF (@Operation ='U')                
BEGIN                                 
            
update rvlfInvOrderRequest set               
CancelledBy=case when @Status='R' then @bigUserId else null end,              
CancelledDate=case when @Status='R' then GETUTCDATE() else null end,              
ApprovedBy =case when @Status='A' then @bigUserId else null end,              
ApprovedDate =case when @Status='A' then GETUTCDATE() else null end,              
DueDate=@DueDate,                
 Comments=@Comments,[Status]=@Status,ModifiedBy=@bigUserId,ModifiedDate=GETUTCDATE()                 
 where OrderNo=@OrderNo and OrganizationId=@bigOrganizationId                 
 --delete from rvlfInvoiceItems where InvSno=@InvSno                 
 UPDATE rvlfInvOrderReqItems set IsDelete=1 where OrderNo=@OrderNo                                
 INSERT into rvlfInvOrderReqItems(OrderNo,Itemcode,UnitPrice,ReqQty,IssuedQty,TotalAmt,Remarks,IsDelete)                
     SELECT  @OrderNo as OrderNo,x.d.value('Itemcode[1]','varchar(100)') AS ProductName,                                
     x.d.value('UnitPrice[1]','numeric(18,2)')AS ProductId,                                                
     x.d.value('ReqQty[1]','bigint')AS ProductId,                           
     x.d.value('IssuedQty[1]','bigint')AS ProductId,                                 
     x.d.value('TotalAmt[1]','numeric(18,2)')AS ProductId,                           
     x.d.value('Remarks[1]','varchar(300)')AS ProductId,0                              
 FROM @OrderItems.nodes('/DocumentElement/OrderItems') x(d)          
 IF(@Status='A')        
 BEGIN        
 update Itm set AvailQty= isnull(AvailQty,0) - ReqQty from rvlfInvItemMaster Itm inner join rvlfInvOrderReqItems InvItm on Itm.Itemcode=InvItm. ItemCode where InvItm.OrderNo=@OrderNo and InvItm.IsDelete=0                               
 END      
Select OrderNo,OrderReqno,replace(convert(varchar(11),OrderDate,106),' ','-') as OrderDate,b.UserName as DisplayName,          
replace(convert(varchar(11),DueDate,106),' ','-') as DueDate,    
case when @Status='R' then CancelledBy else ApprovedBy end as Processby,    
case when @Status='R' then CancelledDate else ApprovedDate end as Processdate,    
case when @Status='R' then 'Cancelled' else 'Approved' end as ProcessStatus,    
c.UserName as ProcessbyName,b.Email from rvlfInvOrderRequest a          
inner join rvlfUser b on a.OrderBy=b.UserId     
inner join rvlfUser c on case when @Status='R' then CancelledBy else ApprovedBy end=c.UserId    
where OrderNo =@OrderNo        
 END          
-----------------------------------------------                  
ELSE IF (@Operation ='D')        
BEGIN                                
update rvlfInvOrderRequest set                 
 IsDelete=1,ModifiedBy=@bigUserId,ModifiedDate=GETUTCDATE()        
 where OrderNo=@OrderNo and OrganizationId=@bigOrganizationId             
 update rvlfInvOrderReqItems set  IsDelete=1 where OrderNo=@OrderNo           
END        
  ------------------------------------------      
IF(@Operation = 'S')         
BEGIN         
select OrderNo,OrderBy,replace(convert(varchar(11),OrderDate,106),' ','-') as OrderDate,ApprovedBy,ApprovedDate,CancelledBy,CancelledDate,Comments,[Status],            
case when [Status]='A' then 'Approved'             
when [Status]='R' then 'Cancelled'             
when [Status]='P' then 'Pending' else 'New' End as StatusDesc ,            
Odrusr.UserName as OrderByName,            
Aprusr.UserName as ApprovedByName,            
CalUsr.UserName as CancelledByName            
,ORQ.OrganizationID,ORQ.IsDelete,replace(convert(varchar(11),DueDate,106),' ','-') as DueDate,OrderReqno from rvlfInvOrderRequest as ORQ       
left join rvlfUser Odrusr on ORQ.OrderBy=Odrusr.UserId            
left join rvlfUser Aprusr on ORQ.ApprovedBy=Aprusr.UserId            
left join rvlfUser CalUsr on ORQ.CancelledBy=CalUsr.UserId            
where ORQ.IsDelete=0 AND (@OrderNo IS NULL or @OrderNo = '' OR OrderNo= @OrderNo)and ORQ.OrganizationID=@bigOrganizationId  
        
if(@OrderNo is not null)        
begin        
select Row_Number() over (order by OrderSno) as [index],OrderSno,ORI.OrderNo,ORI.Itemcode,isnull(ORI.UnitPrice,0) as UnitPrice,        
isnull(ReqQty,0) as ReqQty,isnull(IssuedQty,0) as IssuedQty,isnull(TotalAmt,0) as TotalAmt,Remarks ,Itm.ItemName,Itm.AvailQty ,      
case when isnull(ReqQty,0)>Itm.AvailQty then 0 else 1 end as IsAvail      
 from rvlfInvOrderRequest as ORQ inner join rvlfInvOrderReqItems as ORI on ORQ.OrderNo=ORI.OrderNo              
inner join rvlfInvItemMaster Itm on ORI.Itemcode=Itm.Itemcode            
where ORQ.IsDelete=0 and ORI.IsDelete=0 and ORI.OrderNo= @OrderNo and ORQ.OrganizationID=@bigOrganizationId          
end              
              
END         
lbexit:        
        if @trancount = 0         
   commit;         
 end TRY         
    begin CATCH        
    declare @error int, @message varchar(4000), @xstate int;        
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();         
    if @xstate = -1        
        rollback;         
    if @xstate = 1 and @trancount = 0         
        rollback          
    if @xstate = 1 and @trancount > 0        
        rollback transaction usp_my_procedure_name;         
        raiserror('Insert/Update Failed. %d: %s', 16, 1, @error, @message);                            
    end CATCH                                       
END       
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSetItemDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_GetSetItemDetails] --2,null,null,null,null,null,null,null,6,292,null,'s'                          
(                 
	@ItemSNo bigint=null,         
	@Itemcode varchar(50)=null,         
	@ItemName varchar(150)=null,         
	@ItemDesc varchar(300)=null,         
	@AvailQty int=0,         
	@ReorderQty int=0,         
	@OpenQty int=0 ,         
	@UnitPrice numeric(18,2)=0.00,         
	@bigOrganizationId bigint = Null,         
	@bigUserId bigint = Null,         
	@ItemCatID int=null ,        
	@UoM varchar(15)=null ,        
	@tblNotificationsList XML = null,    
	@Operation char(1)=null,
	@ItemImage nvarchar(MAX)=null,
	@SerialNo nvarchar(20) = NULL
)        
AS        
	BEGIN     
		declare @tblNotificationsListTmp As NotificaitonUserList      
		DECLARE @docHandle int            
		DECLARE  @temptable TABLE (UserID Bigint,Email bit,SMS bit)                                          
		IF @tblNotificationsList IS NOT NULL                                     
			BEGIN                                                    
				EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblNotificationsList                                                             
				INSERT INTO @tempTable                                                                          
				SELECT * FROM OPENXML(@docHandle, '/DocumentElement/Notification')                                   
				WITH                                     
				(                                             
				UserID bigint 'UserID'                                              
				,Email  bit  'Email'                                                                        
				,SMS bit  'SMS'                                    
				)                                          
			END                                    
                                 
		insert into  @tblNotificationsListTmp                                  
		select * from @temptable       
        
		IF(@Operation ='S')  --Select        
			BEGIN     
				select ItemSNo,Itemcode,ItemName,ItemDesc,AvailQty,OpenQty,ReorderQty,UnitPrice,IsActive,        
				ItemCatID,ItemCategoryName, TotalReceipts, UOM,   
				ISNULL(dbo.rvlf_fn_GetNotificationsList(16, ItemSNo, 1,1,0),'') as EmailList,                                                
				ISNULL(dbo.rvlf_fn_GetNotificationsList(16, ItemSNo, 0,1,0),'') as SMSList,                                        
				REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(16, ItemSNo, 1,0,1),''),',',', ') as EmailUserNameList,     
				REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(16, ItemSNo, 0,0,1),''),',',', ') as SMSUserNameList,isnull(ItemImage,'') as ItemImage, SerialNo as SerialNo
				from (       
				SELECT ItemSNo,ITM.Itemcode,ItemName,ItemDesc,AvailQty,OpenQty,ReorderQty,ITM.UnitPrice,IsActive,        
				ITM.ItemCatID,ItemCategoryName,
				--COUNT(IET.InvSno) as TotalReceipts 
				0 as TotalReceipts, 
				ITM.UOM ,ITM.ItemImage,ITM.SerialNo
				from rvlfInvItemMaster ITM inner join rvlfItemCategory ItmC on ITM.ItemCatID=Itmc.ItemCatID   
				--left join rvlfInvoiceItems IET on ITM.Itemcode=IET.ItemCode       
				where ITM.OrganizatioID=@bigOrganizationId  and IsActive=1        
				and (@ItemSNo is null or @ItemSNo = '' or ItemSNo=@ItemSNo)        
				and (@ItemName is null or @ItemName = '' or ItemName like @ItemName + '%')          
				and (@ItemCatID is null or @ItemCatID = '' or ITM.ItemCatID=@ItemCatID)      
				group by ItemSNo,ITM.Itemcode,ItemName,ItemDesc,AvailQty,OpenQty,ReorderQty,ITM.UnitPrice,IsActive,        
				ITM.ItemCatID,ItemCategoryName ,ITM.UOM ,ITM.ItemImage,ITM.SerialNo
				) as a  order by SerialNo --Itemcode,ItemCategoryName
          
			END                          
		IF(@Operation ='I')  --Insert                        
			BEGIN      
			if not exists(select * from rvlfInvItemMaster where Itemcode =@Itemcode and OrganizatioID=@bigOrganizationId and IsActive=1)                      
				BEGIN                        
					if not exists(select * from rvlfInvItemMaster where ItemName =@ItemName and OrganizatioID=@bigOrganizationId and IsActive=1)                      
						BEGIN 
						   --IF not exists(select * from rvlfInvItemMaster where SerialNo =@SerialNo and OrganizatioID=@bigOrganizationId and IsActive=1)  
						     --BEGIN  
							--SET @Itemcode=dbo.rvlf_fn_GetFirstLetterofWord(@ItemName) + CAST((select IDENT_CURRENT('rvlfInvItemMaster')) as varchar)                       
							   select * from rvlfInvItemMaster
							   Insert into rvlfInvItemMaster (Itemcode,ItemName,ItemDesc,AvailQty,OpenQty,ReorderQty,UnitPrice,IsActive ,ItemCatID,Createdby,CreatedDate, OrganizatioID,UOM,ItemImage,SerialNo)                        
							   values (@Itemcode,@ItemName,@ItemDesc,@OpenQty,@OpenQty,@ReorderQty,@UnitPrice,1,@ItemCatID,@bigUserId,GETUTCDATE(),                   
							   @bigOrganizationId,@UoM,@ItemImage,@SerialNo)      
							   SET @ItemSNo = IDENT_CURRENT('rvlfInvItemMaster')    
							   EXEC rvlf_sp_Save_notificationsList @tblNotificationsListTmp,16,@ItemSNo 	
							 --END
							 -- ELSE
							  -- RAISERROR('Serial No already exists!',15,0)												                                 
						END                      
					ELSE                      
					RAISERROR('Item Name already exists!',15,0)                      
       
				end      
			ELSE                      
			RAISERROR('Item Code already exists!',15,0)      
			END        
                        
		IF(@Operation ='U')  --Update                        
			BEGIN                          
				IF not exists(select * from rvlfInvItemMaster where Itemcode =@Itemcode and OrganizatioID=@bigOrganizationId and ItemSNo != @ItemSNo and IsActive=1)
					BEGIN      
						IF not exists(select * from rvlfInvItemMaster where ItemName =@ItemName and OrganizatioID=@bigOrganizationId and ItemSNo != @ItemSNo and IsActive=1)
							BEGIN   
							 --IF not exists(select * from rvlfInvItemMaster where SerialNo =@SerialNo and OrganizatioID=@bigOrganizationId and ItemSNo != @ItemSNo and IsActive=1)  
						     -- BEGIN                    
								update rvlfInvItemMaster set Itemcode =@Itemcode,ItemName=@ItemName,ItemDesc=@ItemDesc,ReorderQty=@ReorderQty,UnitPrice=@UnitPrice,AvailQty=@AvailQty,            
								ItemCatID=@ItemCatID,UOM=@UoM,ItemImage=@ItemImage,SerialNo=@SerialNo from rvlfInvItemMaster where OrganizatioID=@bigOrganizationId  and ItemSNo=@ItemSNo     
								DELETE FROM rvlfNotificationList WHERE TypeID = @ItemSNo AND NotificationType = 16                  
								exec rvlf_sp_Save_notificationsList @tblNotificationsListTmp,16,@ItemSNo 
							 -- END 
							--ELSE
							 --RAISERROR('Serial No already exists!',15,0)                         
							END                      
						ELSE                      
							RAISERROR('Item Name already exists!',15,0)                      
					END      
				ELSE                      
					RAISERROR('Item Code already exists!',15,0)                      
			END      
                          
		IF(@Operation ='D')  --Delete Item                        
			BEGIN                          
				IF exists(select * from rvlfItemTypeDetails where ItemID=@ItemSNo)              
					BEGIN
						RAISERROR('You cannot delete an item already assigned to equipment',15,0)           
					end
				else
					begin
						Update rvlfInvItemMaster set IsActive =0 where OrganizatioID=@bigOrganizationId and ItemSNo=@ItemSNo      
						DELETE FROM rvlfNotificationList WHERE TypeID = @ItemSNo AND NotificationType = 16                                     
					end
			END                          
		IF(@Operation ='C')  --check Valid Item name              
			BEGIN              
				if not exists(select * from rvlfInvItemMaster where ItemName =@ItemName and OrganizatioID=@bigOrganizationId and IsActive=1)                      
					select 0               
				ELSE              
					select 1              
			END                   
	END 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSetUserSetting]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetSetUserSetting]                 
/******************************************************                
Stored Procedure Name : [rvlf_sp_GetSetUserSetting] 19,0,3,0            
Purpose     : Retrieve  Users' details                
Created by    : Ranjith N                
Created date   : 10-Feb-14                
Update History:                
              
*******************************************************/                 
 @intUserid int =null,            
 @IsPushNotfication int = null,                
 @intLastHour int = null,            
 @intGet int = null,        
 @intTimeZoneID int = null,      
 @DefaultFleetId int = null,      
 @DefaultVehicleId int =null,    
 @LandingPageId int =null,
 @RefreshFreqId int = NULL         
             
AS                
BEGIN                    
            
                 
 IF (@intGet = 0)            
 Begin            
 Select u.Userid,isnull(u.IsPushNotfication,1) as IsPushNotfication,isnull(u.LastHour,2) as LastHour,up.TimezoneId,  
 DefaultFleetId,DefaultVehicleId,LandingPageId,f.FleetName,v.VehicleDescription,va.BoxId as DeviceID,up.RefreshFrequencyId  
 from rvlfUser u        
 inner join rvlfUserPreferences up on up.UserId =u.UserId        
 left outer join rvlfFleet f on f.FleetId = up.DefaultFleetId  
 left outer join rvlfVehicle v on v.VehicleId = up.DefaultVehicleId  
 left outer join rvlfVehicleAssignment va on va.VehicleId = v.VehicleId  
 where u.UserId = @intUserid            
 End            
 Else             
 Begin            
 Update rvlfUser set IsPushNotfication = @IsPushNotfication,LastHour = @intLastHour where UserId = @intUserid           
 update rvlfUserPreferences set TimezoneId =@intTimeZoneID,DefaultFleetId=@DefaultFleetId,DefaultVehicleId=@DefaultVehicleId,LandingPageId=@LandingPageId,RefreshFrequencyId=@RefreshFreqId where  UserId = @intUserid         
 End         
                      
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSetUserSettingParents_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetSetUserSettingParents_PhoneGap]                   
/******************************************************                  
Stored Procedure Name : [rvlf_sp_GetSetUserSettingParents_PhoneGap] 19,0,3,0              
Purpose     : Retrieve  Parent details                  
Created by    : Ranjith N                  
Created date   : 30-june-15                  
Update History:                  
                
*******************************************************/                   
 @intUserid int =null,              
 @IsPushNotfication int = null,   
 @VarEmail varchar(500) = null,         
 @intGet int = null    
                
AS                  
BEGIN                      
              
                   
 IF (@intGet = 0)              
 Begin              
  Select u.Userid,isnull(u.IsPushNotfication,1) as IsPushNotfication,Email    
  from rvlfParentMaster u  where u.UserId = @intUserid              
 End              
 Else IF (@intGet = 1)                
 Begin              
 Update rvlfParentMaster set IsPushNotfication = @IsPushNotfication,Email=@VarEmail where UserId = @intUserid              
 End    
 Else IF (@intGet = 2)                
 Begin              
 Update rvlfParentMaster set Email=@VarEmail where UserId = @intUserid              
 End              
               
                
                        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSeverities]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetSeverities]
AS
/******************************************************************************/
--	Name		  : rvlf_sp_GetSeverities
--	Description	  :	To get all the Severities
--	Author		  :	Kumuthini. L
--	Created Date  : 13-July-09
--  Modified Date : 14-Jul-09 by Uma, included sorting
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 
	
	SELECT AlarmLevelId, AlarmLevelName,1 As CanSendNotification,1 As CreateAlarm FROM rvlfSeverity 
	
	ORDER BY  AlarmLevelId ASC
		
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSeverities_Alarm]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Procedure [dbo].[rvlf_sp_GetSeverities_Alarm]        
	@bigUserID	bigint = null             
AS          
/******************************************************************************/          
-- Name    : rvlf_sp_GetSeverities_New   19
-- Description   : To get all the Severities          
-- Author    : Kumuthini. L          
-- Created Date  : 13-July-09          
--  Modified Date : 14-Jul-09 by Uma, included sorting          
/******************************************************************************/          
BEGIN          
	DECLARE @Lang varchar(50)                 
	SELECT @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigUserID           
	
	SET NOCOUNT ON           
	           
	SELECT AlarmLevelId, case	When @Lang='LanguageArNew' then ISNULL(AlarmLevelName_Ar,AlarmLevelName)  
								when @Lang='LanguageHindi' then ISNULL(AlarmLevelName_Hin,AlarmLevelName)  
								else AlarmLevelName end as AlarmLevelName, 1 As CanSendNotification, 1 As CreateAlarm 
	FROM rvlfSeverity  Where AlarmLevelId <>0
	ORDER BY  AlarmLevelId ASC          

	/******* For Cannot find Table(1) issue fixing. Kindly remove this after latest code has been uploaded  - 24-Feb-14 ******/
	--SELECT AlarmLevelId, case	When  @Lang='LanguageArNew' then ISNULL(AlarmLevelName_Ar,AlarmLevelName)  
	--							when @Lang='LanguageHindi' then ISNULL(AlarmLevelName_Hin,AlarmLevelName)  
	--							else AlarmLevelName end as AlarmLevelName, 1 As CanSendNotification, 1 As CreateAlarm 
	--FROM rvlfSeverity   
	--ORDER BY  AlarmLevelId ASC          
	/*****************************/
	
	SET NOCOUNT OFF          
END          
        
        

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSeverities_New]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetSeverities_New]        
	@bigUserID	bigint = null             
AS          
/******************************************************************************/          
-- Name    : rvlf_sp_GetSeverities_New   19
-- Description   : To get all the Severities          
-- Author    : Kumuthini. L          
-- Created Date  : 13-July-09          
--  Modified Date : 14-Jul-09 by Uma, included sorting          
/******************************************************************************/          
BEGIN          
	DECLARE @Lang varchar(50)                 
	SELECT @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigUserID           
	
	SET NOCOUNT ON           
	           
	SELECT AlarmLevelId, case	When @Lang='LanguageArNew' then ISNULL(AlarmLevelName_Ar,AlarmLevelName)  
								when @Lang='LanguageHindi' then ISNULL(AlarmLevelName_Hin,AlarmLevelName)  
								else AlarmLevelName end as AlarmLevelName, 1 As CanSendNotification, 1 As CreateAlarm 
	FROM rvlfSeverity  --Where AlarmLevelId < 4
	ORDER BY  AlarmLevelId ASC          

	/******* For Cannot find Table(1) issue fixing. Kindly remove this after latest code has been uploaded  - 24-Feb-14 ******/
	--SELECT AlarmLevelId, case	When  @Lang='LanguageArNew' then ISNULL(AlarmLevelName_Ar,AlarmLevelName)  
	--							when @Lang='LanguageHindi' then ISNULL(AlarmLevelName_Hin,AlarmLevelName)  
	--							else AlarmLevelName end as AlarmLevelName, 1 As CanSendNotification, 1 As CreateAlarm 
	--FROM rvlfSeverity   
	--ORDER BY  AlarmLevelId ASC          
	/*****************************/
	
	SET NOCOUNT OFF          
END          
        
        

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSeverityTemplate]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetSeverityTemplate]	
@intSeverityTempId int=null
AS
/**************************************************************************************/
--	Name		:	rvlf_sp_GetSeverityTemplate 3
--	Description	:	To get Severity Template
--	Author		:	S. Jeyanthi
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	26-Oct-2010		Created Intial Version  
/*************************************************************************************/
BEGIN
	SET NOCOUNT ON 
	 
	--SELECT SeverityTempId,SeverityTempName,SensorIds,OutputIds FROM rvlfSeverityTemplate	
    --WHERE (@intSeverityTempId IS NULL) OR (@intSeverityTempId =0) OR (SeverityTempId =@intSeverityTempId)     
   
    DECLARE @tblSeverity Table(ID int identity, SeverityTempId int, SeverityTempName nvarchar(50),
	SensorIds nvarchar(50),OutputIds nvarchar(50),SensorNames nvarchar(500), OutputNames nvarchar(500))

	INSERT INTO @tblSeverity(SeverityTempId,SeverityTempName,SensorIds,OutputIds)
	SELECT SeverityTempId,SeverityTempName,SensorIds,OutputIds FROM rvlfSeverityTemplate	
	WHERE (@intSeverityTempId IS NULL) OR (@intSeverityTempId =0) OR (SeverityTempId =@intSeverityTempId)

	DECLARE @intTotalCount int = (SELECT Count(ID) from @tblSeverity)
	DECLARE @index int =1
 
	WHILE @index <= @intTotalCount
		BEGIN
						
			Declare @vcSensorIds nvarchar(50)=NULL,@vcSensorNames nvarchar(500)=NULL, 
			 @vcOutputIds nvarchar(50)=NULL,@vcOutputNames nvarchar(500)=NULL
			
			SELECT @vcSensorIds=SensorIds, @vcOutputIds=OutputIds FROM @tblSeverity WHERE ID=@index
					
			SELECT @vcSensorNames=Coalesce(@vcSensorNames,'')+ CONVERT(varchar,SensorName)+',' FROM rvlfSensor 
			WHERE SensorId in(SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcSensorIds,','))
			
			SELECT @vcOutputNames=Coalesce(@vcOutputNames,'')+ CONVERT(varchar,OutputName)+',' FROM rvlfOutput
			WHERE OutputId in (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcOutputIds,','))	
			
			--UPDATE 	@tblSeverity SET SensorNames =@vcSensorNames, OutputNames=@vcOutputNames WHERE ID=@index
			UPDATE 	@tblSeverity SET SensorNames = REVERSE(STUFF(REVERSE(@vcSensorNames),charindex(',',REVERSE(@vcSensorNames)), 1, '')),
			OutputNames=REVERSE(STUFF(REVERSE(@vcOutputNames),charindex(',',REVERSE(@vcOutputNames)), 1, '')) WHERE ID=@index
			
			SET @index +=1
		END

	SELECT * FROM @tblSeverity  
	
	IF(@intSeverityTempId IS Not NULL)
	BEGIN
	
	 SELECT SensorId,SensorName FROM rvlfSensor 
	 WHERE SensorId in(SELECT * FROM rvlf_fn_ConvertArrayToTable((Select SensorIds from rvlfSeverityTemplate where SeverityTempId=@intSeverityTempId),','))
	 
	 SELECT OutputId,OutPutName FROM rvlfOutput
	 WHERE OutputId in(SELECT * FROM rvlf_fn_ConvertArrayToTable((Select OutputId from rvlfSeverityTemplate where SeverityTempId=@intSeverityTempId),','))
	 
    END
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_getShiftDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_getShiftDetails]
	@EquipmentID varchar(max)=null
AS
BEGIN
  /* --------------------Shift Details -------------------------*/

  SELECT [Shift],FORMAT(CAST( StartTime AS DATETIME),'HH:mm') AS StartTime, FORMAT(CAST( EndTime AS DATETIME),'HH:mm') AS EndTime,NoofShift,EConsumptionType AS ECType FROM rvlf_EnergyConsumption WHERE  EquipmentId =@EquipmentID
 
  /*------------------- Compactor  Details --------------------*/
    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
   FROM rvlf_CompactorDetails C inner join rvlfMAKDevices Md on C.DeviceId = Md.BoxId
   WHERE Md.BoxId = @EquipmentID and Md.IsDelete= 0   
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSMSBasedQueryDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetSMSBasedQueryDetails]             
AS            
/******************************************************************************/            
-- Name  : [rvlf_sp_GetSMSBasedQueryDetails]            
-- Description : To get the SMS based Query details based on the current date            
-- Author  : N.Ranjith        
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--    : 17-Dec-2013 N.Ranjith Created initial version            
/******************************************************************************/            
BEGIN            
             
      
             
 DECLARE @tblSMSSchedulingInfo table                  
  (                  
  ScheduleId int        
  )             
  --_SendSMSTest    
  INSERT INTO @tblSMSSchedulingInfo (ScheduleId)                              
  select distinct nl.SMSScheduleID           
     from rvlfNotificationLog NL inner join rvlfScheduleOfCommandsMaster scm on scm.ScheduleId =NL.SMSScheduleID        
     inner join rvlfSchedulingOfCommandsLog SCL on SCL.ScheduleId = scm.ScheduleId        
     where NL.SMSScheduleID is not null and NL.MessageDetails is null and NL.SMSProcessedDate is null         
     and SCL.IsCommandSend = 1 and scm.BoxCmdOutTypeId= 5                
             
 if exists(select * from @tblSMSSchedulingInfo)        
  Begin                            
  DECLARE @IntScheduleId INT =(SELECT MIN(ScheduleId) FROM @tblSMSSchedulingInfo)                              
  WHILE @IntScheduleId IS NOT NULL                  
  BEGIN               
  --_SendSMSTest    
  update rvlfNotificationLog set         
  MessageDetails = (        
     Select top 1 b.StreetAddress from  rvlfMsgInHst b inner join rvlfScheduleOfCommandsMaster sc on sc.Boxid = b.BoxId        
  inner join rvlfSchedulingOfCommandsLog SCL on SCL.ScheduleId = sc.ScheduleId        
  where  b.BoxId = sc.Boxid and b.ValidGps = 0 and b.StreetAddress is not null and b.IsProcessed = 0  and        
   sc.ScheduleId = @IntScheduleId and sc.BoxCmdOutTypeId = 5 and sc.ScheduleId is not null)        
   where SMSScheduleID = @IntScheduleId and MessageDetails is null and SMSProcessedDate is null         
          
  ----UPDATE a         
  --       -- SET a.MessageDetails = b.StreetAddress        
  --       select b.StreetAddress        
  --         FROM                  
  --        rvlfNotificationLog_SendSMSTest a        
  --         inner join rvlfMsgInHst b on a.BoxId = b.BoxId        
  --         inner join rvlfScheduleOfCommandsMaster sc on sc.Boxid = b.BoxId        
  --   inner join rvlfSchedulingOfCommandsLog SCL on SCL.ScheduleId = sc.ScheduleId           
  --         where b.ValidGps = 0 and b.StreetAddress is not null and b.IsProcessed = 0  and        
  --    SMSScheduleID = @IntScheduleId and sc.BoxCmdOutTypeId = 5 and a.SMSProcessedDate is null         
              
  SELECT @IntScheduleId=MIN(ScheduleId)FROM @tblSMSSchedulingInfo WHERE ScheduleId>@IntScheduleId                       
                    
  END         
  --update rvlfNotificationLog_SendSMSTest set         
  --MessageDetails = (select b.LastStreetAddress from rvlfBoxId b inner join rvlfScheduleOfCommandsMaster sc on sc.Boxid = b.BoxId        
  --inner join rvlfSchedulingOfCommandsLog SCL on SCL.ScheduleId = sc.ScheduleId        
  --where sc.ScheduleId = @bigScheduleId and sc.BoxCmdOutTypeId = 5 and sc.ScheduleId is not null)          
  End        
          
          
 --select MessageDetails as MessageTemplate,cast(NL.MobileNo as bigint) as MobileNo,VehicleID as VehId,VehicleDescription as  DisplayName        
 -- from rvlfNotificationLog_SendSMSTest NL inner join rvlfSchedulingOfCommandsLog SCL on SCL.ScheduleId = NL.SMSScheduleID        
 -- where NL.SMSScheduleID is not null and NL.MessageDetails is not null and NL.SMSProcessedDate is null         
 -- and SCL.IsCommandSend = 1      
       
 SELECT     
 n.MessageInID,         
Case when t.HoursToBeAdded is null then Convert(varchar,GETUTCDATE(),6) + ',' + right(CONVERT( varchar, GETUTCDATE(), 100),7) else    
 Convert(varchar, DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, n.OriginDateTime)),6) + ',' + right(CONVERT( varchar,  DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, n.OriginDateTime)), 100),7) end as OriginDateTime,      
Case when t.HoursToBeAdded is null then Convert(varchar,GETUTCDATE(),6) + ',' + right(CONVERT( varchar, GETUTCDATE(), 100),7) else               
  Convert(varchar,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, n.DateTimeReceived)),6) + ',' + right(CONVERT( varchar, DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, n.DateTimeReceived)), 100),7) end as DateTimeReceived,                
 
  n.CanSendEmail, n.IsMailSent, n.CanSendSMS, n.IsSMSSent,                
  isnull(n.UserID,0) as UserID,isnull(u.DisplayName,'Unknown') as DisplayName,isnull(u.Email,'Unknown') as Email, n.MobileNo, n.OrganizationID,n.OrganizationID as OrgId, 
  dbo.rvlf_fn_getsmssettings(n.OrganizationID) as SMSsettings, 
  CASE WHEN h.StreetAddress like 'Address Not Found' OR h.StreetAddress like 'N/A' THEN                  
   'http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+                
   cast(h.Longitude as varchar(15) )                
  --WHEN h.ValidGps = 0 THEN                 
  -- h.StreetAddress + ' http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )                
  -- +','+cast(h.Longitude as varchar(15) )                  
  ELSE h.StreetAddress END AS StreetAddress,                
  CAST((h.Speed * CASE WHEN p.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +                 
   CASE WHEN p.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,                
  isnull(h.BoxId,0) as BoxId, isnull(m.BoxMsgInTypeDesc,114) as BoxMsgInTypeDesc, isnull(n.VehicleID,0) as VehicleID, isnull(v.VehicleDescription,'Unknown') as VehicleName,     
  isnull(v.VehicleDescription,'Unknown') as VehicleDescription,                
  isnull(n.FleetID,0) as FleetID, isnull(n.FleetName,'Unknown') as FleetName, isnull(v.LicensePlate,'Unknown') as LicensePlate, n.Subjectsufix, dbo.rvlf_fn_GetTimeFromSeconds(n.Duration) as Duration, n.MessageDetails,                
  (Case When n.MessageDetails like '%Unknown mobile number!%'  then 'Msg:<#Message Type#>\n-Trinetra'    
    When n.MessageDetails like '%You do not have privilege to this vehicle!%'  then 'Msg:<#Message Type#>\nInfo:<#VehicleName#>\n-Trinetra'    
    else    
  replace('Msg:<#Message Type#>\nInfo:<#VehicleName#>\n<#DateTime#>\n<#Speed#>\n-Trinetra','\n<#Speed#>','') end) as  MessageTemplate,    
  n.SMSbasedQueryID          
  --_SendSMSTest          
 FROM rvlfNotificationLog n                
  left outer JOIN rvlfMsgInHst h ON n.MessageInID = h.MessageInID         
  left outer JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                
  left outer JOIN rvlfVehicleAssignment va ON n.BoxId = va.BoxId                
  left outer JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
  left outer  JOIN rvlfUser u ON n.UserID = u.UserId                
  left outer  JOIN rvlfUserPreferences p On u.UserId = p.UserId                
  left outer  JOIN rvlfTimeZones t ON p.TimezoneId = t.TimeZoneID                
  left outer  JOIN rvlfOrganization org ON org.OrganizationId = v.OrganizationId                
  left outer  JOIN rvlfMsgInSMSTemplates mt ON mt.BoxMsgInTypeID =                 
   (CASE WHEN EXISTS(SELECT m.BoxMsgInTypeId FROM rvlfMsgInSMSTemplates m                
    WHERE m.BoxMsgInTypeID = h.BoxMsgInTypeId) THEN h.BoxMsgInTypeID                
   ELSE 0 END)    
  left outer  join rvlfSchedulingOfCommandsLog scl on scl.ScheduleId = n.SMSScheduleID                 
  WHERE CanSendSMS = 1 and n.IsSMSSent = 0 and SMSProcessedDate is null and convert(date,n.OriginDateTime) >= '2014-02-19'  AND                
  (NoOfSMSTries IS NULL OR NoOfSMSTries < org.TotalNoofSMSTries) and scl.IsCommandSend = 1     
    
Union all    
    
SELECT distinct    
 n.MessageInID,         
Case when t.HoursToBeAdded is null then Convert(varchar,GETUTCDATE(),6) + ',' + right(CONVERT( varchar, GETUTCDATE(), 100),7) else    
 Convert(varchar, DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, n.OriginDateTime)),6) + ',' + right(CONVERT( varchar,  DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, n.OriginDateTime)), 100),7) end as OriginDateTime,      
Case when t.HoursToBeAdded is null then Convert(varchar,GETUTCDATE(),6) + ',' + right(CONVERT( varchar, GETUTCDATE(), 100),7) else               
  Convert(varchar,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, n.DateTimeReceived)),6) + ',' + right(CONVERT( varchar, DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, n.DateTimeReceived)), 100),7) end as DateTimeReceived,                 
  n.CanSendEmail, n.IsMailSent, n.CanSendSMS, n.IsSMSSent,                
  isnull(n.UserID,0) as UserID,isnull(u.DisplayName,'Unknown') as DisplayName,isnull(u.Email,'Unknown') as Email, n.MobileNo, n.OrganizationID,n.OrganizationID as OrgId, dbo.rvlf_fn_getsmssettings(n.OrganizationID) as SMSsettings,              
  CASE WHEN h.StreetAddress like 'Address Not Found' OR h.StreetAddress like 'N/A' THEN                  
   'http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+                
   cast(h.Longitude as varchar(15) )                
  --WHEN h.ValidGps = 0 THEN                 
  -- h.StreetAddress + ' http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )                
  -- +','+cast(h.Longitude as varchar(15) )                  
  ELSE h.StreetAddress END AS StreetAddress,                
  CAST((h.Speed * CASE WHEN p.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +                 
   CASE WHEN p.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,                
  isnull(h.BoxId,0) as BoxId, isnull(m.BoxMsgInTypeDesc,114) as BoxMsgInTypeDesc, isnull(n.VehicleID,0) as VehicleID, isnull(v.VehicleDescription,'Unknown') as VehicleName,     
  isnull(v.VehicleDescription,'Unknown') as VehicleDescription,                
  isnull(n.FleetID,0) as FleetID, isnull(n.FleetName,'Unknown') as FleetName, isnull(v.LicensePlate,'Unknown') as LicensePlate, n.Subjectsufix, dbo.rvlf_fn_GetTimeFromSeconds(n.Duration) as Duration, n.MessageDetails,                
  (Case When n.MessageDetails like '%Unknown mobile number!%'  then 'Msg:<#Message Type#>\n-Trinetra'    
    When n.MessageDetails like '%You do not have privilege to this vehicle!%'  then 'Msg:<#Message Type#>\nInfo:<#VehicleName#>\n-Trinetra'    
    else    
  replace('Msg:<#Message Type#>\nInfo:<#VehicleName#>\n<#DateTime#>\n<#Speed#>\n-Trinetra','\n<#Speed#>','') end) as  MessageTemplate,    
  n.SMSbasedQueryID       
  --_SendSMSTest             
 FROM rvlfNotificationLog n                
  left outer JOIN rvlfMsgInHst h ON n.MessageInID = h.MessageInID         
  left outer JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                
  left outer JOIN rvlfVehicleAssignment va ON n.BoxId = va.BoxId                
  left outer JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
  left outer  JOIN rvlfUser u ON n.UserID = u.UserId                
  left outer  JOIN rvlfUserPreferences p On u.UserId = p.UserId                
  left outer  JOIN rvlfTimeZones t ON p.TimezoneId = t.TimeZoneID                
  left outer  JOIN rvlfOrganization org ON org.OrganizationId = v.OrganizationId                
  left outer  JOIN rvlfMsgInSMSTemplates mt ON mt.BoxMsgInTypeID =                 
   (CASE WHEN EXISTS(SELECT m.BoxMsgInTypeId FROM rvlfMsgInSMSTemplates m                
    WHERE m.BoxMsgInTypeID = h.BoxMsgInTypeId) THEN h.BoxMsgInTypeID                
   ELSE 0 END)    
  left outer  join rvlfSchedulingOfCommandsLog scl on scl.ScheduleId = n.SMSScheduleID                 
  WHERE CanSendSMS = 1 and n.IsSMSSent = 0 and SMSProcessedDate is null and convert(date,n.OriginDateTime) >= '2014-02-19'  AND                
  (NoOfSMSTries IS NULL OR NoOfSMSTries < org.TotalNoofSMSTries) and     
  (n.MessageDetails like '%Invalid%' )        
      
  union all     
    
SELECT distinct    
 n.MessageInID,         
Case when t.HoursToBeAdded is null then Convert(varchar,GETUTCDATE(),6) + ',' + right(CONVERT( varchar, GETUTCDATE(), 100),7) else    
 Convert(varchar, DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, n.OriginDateTime)),6) + ',' + right(CONVERT( varchar,  DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, n.OriginDateTime)), 100),7) end as OriginDateTime,      
Case when t.HoursToBeAdded is null then Convert(varchar,GETUTCDATE(),6) + ',' + right(CONVERT( varchar, GETUTCDATE(), 100),7) else               
  Convert(varchar,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, n.DateTimeReceived)),6) + ',' + right(CONVERT( varchar, DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, n.DateTimeReceived)), 100),7) end as DateTimeReceived,                 
  n.CanSendEmail, n.IsMailSent, n.CanSendSMS, n.IsSMSSent,                
  isnull(n.UserID,0) as UserID,isnull(u.DisplayName,'Unknown') as DisplayName,isnull(u.Email,'Unknown') as Email, n.MobileNo, n.OrganizationID,n.OrganizationID as OrgId,dbo.rvlf_fn_getsmssettings(n.OrganizationID) as SMSsettings, 
  CASE WHEN h.StreetAddress like 'Address Not Found' OR h.StreetAddress like 'N/A' THEN                  
   'http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+                
   cast(h.Longitude as varchar(15) )                
  --WHEN h.ValidGps = 0 THEN                 
  -- h.StreetAddress + ' http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )                
  -- +','+cast(h.Longitude as varchar(15) )                  
  ELSE h.StreetAddress END AS StreetAddress,                
  CAST((h.Speed * CASE WHEN p.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +                 
   CASE WHEN p.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,                
  isnull(h.BoxId,0) as BoxId, isnull(m.BoxMsgInTypeDesc,114) as BoxMsgInTypeDesc, isnull(n.VehicleID,0) as VehicleID, isnull(v.VehicleDescription,'Unknown') as VehicleName,     
  isnull(v.VehicleDescription,'Unknown') as VehicleDescription,                
  isnull(n.FleetID,0) as FleetID, isnull(n.FleetName,'Unknown') as FleetName, isnull(v.LicensePlate,'Unknown') as LicensePlate, n.Subjectsufix, dbo.rvlf_fn_GetTimeFromSeconds(n.Duration) as Duration, n.MessageDetails,                
  (Case When n.MessageDetails like '%Unknown mobile number!%'  then 'Msg:<#Message Type#>\n-Trinetra'    
    When n.MessageDetails like '%You do not have privilege to this vehicle!%'  then 'Msg:<#Message Type#>\nInfo:<#VehicleName#>\n-Trinetra'    
    else    
  replace('Msg:<#Message Type#>\nInfo:<#VehicleName#>\n<#DateTime#>\n<#Speed#>\n-Trinetra','\n<#Speed#>','') end) as  MessageTemplate,    
  n.SMSbasedQueryID          
  --_SendSMSTest          
 FROM rvlfNotificationLog n                
  left outer JOIN rvlfMsgInHst h ON n.MessageInID = h.MessageInID         
  left outer JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                
  left outer JOIN rvlfVehicleAssignment va ON n.BoxId = va.BoxId                
  left outer JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
  left outer  JOIN rvlfUser u ON n.UserID = u.UserId                
  left outer  JOIN rvlfUserPreferences p On u.UserId = p.UserId                
  left outer  JOIN rvlfTimeZones t ON p.TimezoneId = t.TimeZoneID                
  left outer  JOIN rvlfOrganization org ON org.OrganizationId = v.OrganizationId                
  left outer  JOIN rvlfMsgInSMSTemplates mt ON mt.BoxMsgInTypeID =                 
   (CASE WHEN EXISTS(SELECT m.BoxMsgInTypeId FROM rvlfMsgInSMSTemplates m                
    WHERE m.BoxMsgInTypeID = h.BoxMsgInTypeId) THEN h.BoxMsgInTypeID                
   ELSE 0 END)    
  left outer  join rvlfSchedulingOfCommandsLog scl on scl.ScheduleId = n.SMSScheduleID                 
  WHERE CanSendSMS = 1 and n.IsSMSSent = 0 and SMSProcessedDate is null and convert(date,n.OriginDateTime) >= '2014-02-19'  AND                
  (NoOfSMSTries IS NULL OR NoOfSMSTries < org.TotalNoofSMSTries) and     
  (n.SMSScheduleID = 0)    and  (n.MessageDetails not like '%Invalid%' )        
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSMSBasedQueryRpt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Proc [dbo].[rvlf_sp_GetSMSBasedQueryRpt]  
 @bigFleetID bigint = null,
 @intBoxID varchar(max) = null,                                  
 @dtStartDate datetime = null,                                    
 @dtEndDate datetime = null,                            
 @bigOrganizationID bigint = null,                                    
 @bigQueryingUser bigint = 0
 as     
 -- =============================================                                              
-- Name   : rvlf_sp_GetSMSBasedQueryRpt   8,null,'2014-04-07 08:00:00.000','2014-04-12 08:08:08.000',6,18 
-- Author  : Gopal.R                                              
-- Create date : 25-Feb-2014  
-- Description :  GetSMSBasedQueryRpt                                              
-- Company  : Angler Technologies                                              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                              
-- =============================================     
begin   

 Declare @dtFDate datetime =@dtStartDate                                  
 Declare @dtEDate datetime =@dtEndDate                             
 DECLARE @HoursToBeAdded INT = 0                                    
 DECLARE @MinsToBeAdded INT = 0                                    
 DECLARE @ConversionFactor numeric (10,2) = 1.0                                    
 DECLARE @DistanceCaptionPrefix varchar(15)                                    
 DECLARE @SpeedCaptionPrefix varchar(15)                                  
 DECLARE @DefaultDateFormat INT = 0;                                  
 DECLARE @Hours varchar(max) = 0                      
 DECLARE @Minutes INT = 0                  
 DECLARE @Sign char =0               
 DECLARE @ToDate Datetime = NULL                           
 DECLARE @FromDate Datetime = NULL 
 Declare @SMSReport table(     
 UserName nvarchar(100) ,   
 DisplayName nvarchar(200),  
 MobileNo varchar(15),  
 Email varchar(200),  
 OrganizationId int,  
 BoxCmdOutTypeName varchar(50),  
 BoxCmdOutTypeId tinyint,  
 ActualExecutionDate datetime,  
 ExecutionOn datetime,   
 IsCommandSend bit,  
 [No.ofTries] tinyint,  
 ResponseMsg varchar(300),  
 ReplyMsg varchar(300),  
 EmailProcessedDate datetime,  
 BoxId int,  
 CanSendSMS bit,  
 SMSScheduleID int,  
 SMSProcessedDate datetime,  
 BoxMsgInTypeId tinyint,  
 CustomProp varchar(2000),  
 OriginDateTime datetime,  
 MessageInID uniqueidentifier,   
 Vin varchar(20),  
 LicensePlate varchar(20),  
 VehicleDescription varchar(40) ,  
 SuccessCmd int,  
 FailedCmd int,  
 Inprogress int,  
 Commands int  
 )  
 
 
 IF @bigFleetID IS NULL      
  BEGIN      
   SELECT @bigFleetID=FleetID from rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1      
  END  
   
SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                            
-- @Hours= HOURS,@ToDate = ToDate,@FromDate = FromDate,                            
 --@Sign = SUBSTRING(Hours,1,1),@Minutes = SUBSTRING(Hours,5,2),                            
 @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,                        
 @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)                                    
 FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz                                    
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser      
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                                    
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))  
 
insert into @SMSReport
 
select USR.UserName,USR.DisplayName,USR.MobileNo,USR.Email,USR.OrganizationId,  
 --BCOT.BoxCmdOutTypeName,
 BCOT.BoxcmdTypeDesc,--+ ':120',  
 SCM.BoxCmdOutTypeId,SCM.ActualExecutionDate,--SCM.ExecutionOn,  
 SCL.ExecutionOn,SCL.IsCommandSend,SCL.[No.ofTries],--SCL.ResponseMsg, 
 case when SCL.ResponseMsg like '%success%' then 'Success' else SCL.ResponseMsg end, 
 (isnull(NL.MessageDetails,'')+ISNULL(' - '+convert(varchar,Nl.SMSProcessedDate,106),''))as ReplyMsg,Nl.SMSProcessedDate,NL.BoxId,NL.CanSendSMS,NL.SMSScheduleID,NL.SMSProcessedDate,   
 MHST.BoxMsgInTypeId,MHST.CustomProp,MHST.OriginDateTime,MHST.MessageInID,   
 v.Vin,v.LicensePlate,v.VehicleDescription ,   
 case when scl.ResponseMsg like '%success%' then 1 else 0 end,  
 case when scl.IsCommandSend like 0 then 1 else 0 end,  
 case when CAST(MHST.OriginDateTime as DATE)=CAST(getdate()as date) then 1 else 0 end,  
 null
from rvlfScheduleOfCommandsMaster SCM   
INNER JOIN rvlfNotificationLog_SendSMSTest NL on SCM.ScheduleId=NL.SMSScheduleID  
INNER JOIN rvlfBoxCmdOutType BCOT on SCM.BoxCmdOutTypeId=BCOT.BoxCmdOutTypeId  
INNER JOIN rvlfMsgInHst MHST on NL.MessageInID=MHST.MessageInID and CustomProp like '%SMS%'   
INNER JOIN rvlfUser USR on Nl.UserID=USR.UserId
INNER JOIN rvlfSchedulingOfCommandsLog SCL on NL.SMSScheduleID=SCL.ScheduleId         
INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON MHST.BoxId = va.BoxId  
INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId      
INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId    

where
--(@intBoxID IS NULL OR @intBoxID='' or MHST.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) 
 V.OrganizationId=@bigOrganizationID
 and NL.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate
 AND ( @bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID)   
  
--select  * from @SMSReport
  
 declare @SuccessCmd int
 declare @Inprogress int
 declare @FailedCmd int
 declare @TotalCmd int
 
 select @SuccessCmd=SUM(SuccessCmd),@Inprogress=SUM(Inprogress),@FailedCmd=SUM(FailedCmd) from @SMSReport  
 select @TotalCmd = @SuccessCmd + @Inprogress + @FailedCmd
 --select @SuccessCmd
 select UserName,DisplayName,MobileNo,Email,OrganizationId,  
 BoxCmdOutTypeName ,  
 BoxCmdOutTypeId,ActualExecutionDate,  
 ExecutionOn,IsCommandSend,[No.ofTries],ResponseMsg, EmailProcessedDate,  
 BoxId,CanSendSMS,SMSScheduleID,SMSProcessedDate,ResponseMsg,ReplyMsg as ResponseMsg1,  
 BoxMsgInTypeId,CustomProp,
Convert(Date,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime))) as OriginDateTime1,
Convert(varchar,OriginDateTime,@DefaultDateFormat)  + ' ' + Convert(varchar,cast(OriginDateTime as time),22) as OriginDateTime,
 MessageInID,   
 Vin,LicensePlate,VehicleDescription,@SuccessCmd as SuccessCmd,  
 @FailedCmd as FailedCmd, @Inprogress as Inprogress, @TotalCmd as [No.ofTries],
Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,
Convert(varchar,@dtEDate,@DefaultDateFormat)+            
 ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,            
 PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())            
 from @SMSReport  
 group by UserName,DisplayName,MobileNo,Email,OrganizationId,  
 BoxCmdOutTypeName ,  
 BoxCmdOutTypeId,ActualExecutionDate,  
 ExecutionOn,IsCommandSend,[No.ofTries],ResponseMsg, EmailProcessedDate,  
 BoxId,CanSendSMS,SMSScheduleID,SMSProcessedDate,ResponseMsg,  
 BoxMsgInTypeId,CustomProp,OriginDateTime,MessageInID,   
 Vin,LicensePlate,VehicleDescription ,ReplyMsg   
 order by OriginDateTime desc
  
end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSMSSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetSMSSettings]
AS
/******************************************************************************/
--	Name		:	rvlf_sp_GetSMSSettings
--	Description	:	To get the SMS settings
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	14-Nov-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON
	select * from rvlfSMSSettings
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSMSSummary]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetSMSSummary]              
 @StartDate datetime = null,              
 @EndDate datetime = null,          
 @bigQueryingUser bigint=null,             
 @bigOrganizationID bigint =NULL          
AS              
/******************************************************************************/                
-- Name  : rvlf_sp_GetSMSSummary '2011-10-01','2011-10-10',140  
-- Description : To get the SMS Summary                
-- Created date : 09-Jul-2011              
-- Created by : Sakthi Gopinath S         
--            : Ranjith - Date format included  
--			  : Sakthi  - Get SMS type for summary details
/******************************************************************************/                
BEGIN              
  
  SET NOCOUNT ON              

	Declare @dtFDate datetime =@StartDate      
	Declare @dtEDate datetime =@EndDate                
	Declare @tintTotalOrg tinyint = null              
	Declare @bigSMSProcess bigint = null              
	Declare @bigSMSNotProcess bigint = null           
	DECLARE @HoursToBeAdded INT = 0                    
	DECLARE @MinsToBeAdded INT = 0                    
	DECLARE @DefaultDateFormat INT = 0

    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,    
    @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 = @bigQueryingUser           
              
	--SET @StartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@StartDate))            
	--SET @EndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@EndDate))               
  
	SELECT @tintTotalOrg=COUNT(Distinct O.OrganizationID) from rvlfnotificationlog N INNER JOIN rvlfOrganization O ON N.OrganizationID = O.OrganizationId              
	WHERE ((@StartDate IS NULL AND @EndDate IS NULL) OR (SMSprocesseddate BETWEEN CONVERT(date,@StartDate) AND CONVERT(date,@EndDate)))              
               
	SELECT @bigSMSProcess=COUNT(O.OrganizationID) from rvlfnotificationlog N INNER JOIN rvlfOrganization O ON N.OrganizationID = O.OrganizationId              
	WHERE ((@StartDate IS NULL AND @EndDate IS NULL) OR (SMSprocesseddate BETWEEN CONVERT(date,@StartDate) AND CONVERT(date,@EndDate)))              
	AND N.IsSMSSent=1          
               
	SELECT @bigSMSNotProcess=COUNT(O.OrganizationID) from rvlfnotificationlog N INNER JOIN rvlfOrganization O ON N.OrganizationID = O.OrganizationId              
	WHERE ((@StartDate IS NULL AND @EndDate IS NULL) OR (SMSprocesseddate BETWEEN CONVERT(date,@StartDate) AND CONVERT(date,@EndDate)))              
	AND N.IsSMSSent=0            
             
	DECLARE @SMSSummary TABLE            
	(            
	   OrganizationId BIGINT,            
	   OrganizationName VARCHAR(50),            
	   VehicleDescription VARCHAR(50) NULL,            
	   BoxId INT NULL,            
	   BoxMsgInTypeName VARCHAR(50) NULL,            
	   MessageDetails VARCHAR(250) NULL,            
	   MobileNo VARCHAR(15) NULL,            
	   UserName VARCHAR(50) NULL,            
	   SMSProcessedDate DATETIME NULL,            
	   TotOrg INT NULL,            
	   TotSMSProcess  INT NULL,            
	   TotSMSNotProcess  INT NULL,            
	   SMSProcess INT NULL,            
	   SMSNotProcess INT NULL,            
	   TotSMS INT NULL,            
	   OrgGroupId INT NULL,          
	   SMSStatus bit          
	)            
	
	INSERT INTO @SMSSummary ( OrganizationId,OrganizationName,VehicleDescription,BoxId,BoxMsgInTypeName,MessageDetails,            
	MobileNo,UserName,SMSProcessedDate,TotOrg,TotSMSProcess,TotSMSNotProcess,SMSStatus)             
	SELECT O.OrganizationId,O.OrganizationName,VehicleDescription,BoxId,BoxMsgInTypeName,MessageDetails,              
	N.MobileNo,UserName,SMSProcessedDate,@tintTotalOrg,@bigSMSProcess,@bigSMSNotProcess,N.IsSMSSent             
	FROM rvlfnotificationlog N INNER JOIN rvlfOrganization O on N.OrganizationID = O.OrganizationId              
	WHERE ((@StartDate IS NULL AND @EndDate IS NULL) OR (SMSprocesseddate BETWEEN CONVERT(date,@StartDate) AND CONVERT(date,@EndDate)))              
             
	Update x SET x.SMSProcess=y.SMSProcessed FROM @SMSSummary x INNER JOIN               
	(SELECT O.OrganizationId,COUNT(N.IsSMSError) as SMSProcessed from rvlfnotificationlog N               
	INNER JOIN rvlfOrganization O ON N.OrganizationID = O.OrganizationId WHERE               
	((@StartDate IS NULL AND @EndDate IS NULL) OR (SMSprocesseddate BETWEEN CONVERT(date,@StartDate) AND CONVERT(date,@EndDate)))              
	AND N.IsSMSSent=1 Group by O.OrganizationID) y               
	ON x.OrganizationId=y.OrganizationId              
               
	Update x SET x.SMSNotProcess=y.SMSNotProcessed FROM @SMSSummary x INNER JOIN               
	(SELECT O.OrganizationId,COUNT(N.IsSMSError) as SMSNotProcessed from rvlfnotificationlog N               
	INNER JOIN rvlfOrganization O ON N.OrganizationID = O.OrganizationId WHERE               
	((@StartDate IS NULL AND @EndDate IS NULL) OR (SMSprocesseddate BETWEEN CONVERT(date,@StartDate) AND CONVERT(date,@EndDate)))              
	AND N.IsSMSSent=0 Group by O.OrganizationID) y               
	ON x.OrganizationId=y.OrganizationId              
             
	--get the organization wise tottal sms count.            
	DECLARE @tblSummary table            
	(            
		Orgid bigint,            
		OrgName varchar(50),            
		TotSMS int,          
		TotSMSProc int,          
		TotSMSNotProc int,
		MobileNumber varchar(15)
	)            
	
	INSERT INTO @tblSummary (Orgid,OrgName,TotSMS,TotSMSProc,TotSMSNotProc)            
	SELECT OrganizationID, OrganizationName,COUNT(OrganizationID),SMSProcess,SMSNotProcess FROM @SMSSummary 
	GROUP BY OrganizationID,OrganizationName,SMSProcess,SMSNotProcess
             
	INSERT INTO @SMSSummary(OrganizationId,OrganizationName,TotSMS,SMSProcess,SMSNotProcess,OrgGroupId)            
	SELECT Orgid,OrgName,TotSMS,TotSMSProc,TotSMSNotProc,1 FROM @tblSummary          
	
	Update a SET a.MobileNo=b.MobileNo FROM @SMSSummary a INNER JOIN @SMSSummary b ON a.OrganizationId=b.OrganizationId
	WHERE a.OrgGroupId=1
          
	SELECT OrganizationId,OrganizationName,VehicleDescription,BoxId,BoxMsgInTypeName,MessageDetails,MobileNo,UserName,            
	Convert(varchar,SMSProcessedDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(SMSProcessedDate as time),22) as SMSProcessedDate,    
	SMSProcessedDate AS SMSProcessedDateSort,    
	ISNULL(TotOrg,'-')AS TotOrg,ISNULL(TotSMSProcess,'-')AS TotSMSProcess,            
	ISNULL(TotSMSNotProcess,'-')AS TotSMSNotProcess,ISNULL(CAST(SMSProcess AS VARCHAR),'-') AS SMSProcess,          
	ISNULL(CAST(SMSNotProcess AS VARCHAR),'-') AS SMSNotProcess,            
	TotSMS,OrgGroupId,(ISNULL(TotSMSProcess,0)+ISNULL(TotSMSNotProcess,0)) AS TotOrgCount,          
	CASE WHEN SMSStatus=1 THEN 'Processed' ELSE 'Unprocessed' END AS SMSStatus,        
	CASE WHEN Substring(MobileNo,1,2)='91' THEN 'Domestic'         
	ELSE 'International' END AS SMSType,    
	Convert(varchar,@dtFDate,@DefaultDateFormat) + ' 00:00 AM'  as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+    
	   ' 11:59 PM' as PasEndDate,  
	     PasGenerateddate =dbo.rvlf_fn_DayLightSavings(@StartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())          
	   --Convert(varchar,GETDATE(),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(GETDATE() as time),22) as PasGenerateddate          
	   --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate   
	FROM @SMSSummary Order by OrganizationName,VehicleDescription,SMSProcessedDate ASC          
           
 SET NOCOUNT OFF              
              
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSpeedAlertsForDrillDownCriticalChart]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[rvlf_sp_GetSpeedAlertsForDrillDownCriticalChart]    

 @VehicleDesc varchar(max) = NULL,    
 @bigOrganizationID bigint = NULL,    
 @bigQueryingUser bigint = NULL,
 @dtStartDate datetime = Null,    
 @dtEndDate datetime = NULL,
 @bigFleetID bigint = null  
 
AS  
/********************************************************************************************************    
-- Name		   : rvlf_sp_GetSpeedAlertsForDrillDownCriticalChart
-- Description : To get the Speed Alerts details        
-- Author      : Ranjith N        
*********************************************************************************************************/ 
BEGIN    
 SET NOCOUNT ON 
 --select a.Speed,COUNT(a.speed) as NoofSpeedCount
 --FROM rvlfMsgInHst  a  
 --  INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
 --  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
 --  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
 -- WHERE   
 --     (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND 
 --          (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and    
 --    v.VehicleDescription =@VehicleDesc  and
 --  ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
 --    a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
 --  and a.BoxMsgInTypeId =4
 
 --  GROUP BY a.Speed
 --  order by a.Speed desc
 
  DECLARE @ConversionFactor numeric (10,2) = 1.0  
  
    select @ConversionFactor = CASE WHEN Distance = 0 THEN 0.62 ELSE 1.0 END  
     from rvlfUserPreferences where UserId = @bigQueryingUser    
     
 
 DECLARE @tblSpeedAlert TABLE     
  ( RangeAlert varchar(max),SpeedCount int)
  
	insert into @tblSpeedAlert(RangeAlert,SpeedCount)
 
	select '30-60', COUNT(a.Speed) from rvlfMsgInHst a
		INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
		INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId 
		where    
		(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND 
		(@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and      
		v.VehicleDescription =@VehicleDesc  and
		((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
		a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
		and a.BoxMsgInTypeId =4 
		--and a.speed >30 and a.Speed <= 60
		 and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int)  >30 and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int) <= 60   
 
	insert into @tblSpeedAlert(RangeAlert,SpeedCount)
	select '61-90', COUNT(a.Speed) from rvlfMsgInHst a
		INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
		INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId 
		where    
		(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND 
		(@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and      
		v.VehicleDescription =@VehicleDesc  and
		((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
		a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
		and a.BoxMsgInTypeId =4 
		--and a.speed >60 and a.Speed <= 90
		and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int)  >60 and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int) <= 90   

	insert into @tblSpeedAlert(RangeAlert,SpeedCount)
	select '91-120', COUNT(a.Speed) from rvlfMsgInHst a
		INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
		INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId 
		where    
		(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND 
		(@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and      
		v.VehicleDescription =@VehicleDesc  and
		((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
		a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
		and a.BoxMsgInTypeId =4 
		--and a.speed >90 and a.Speed <= 120
		and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int)  >90 and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int) <= 120   

		insert into @tblSpeedAlert(RangeAlert,SpeedCount)
		--select '150-200', COUNT(Speed)
		--from rvlfMsgInHst where 
		--OriginDateTime between '10/10/2011 4:44:28 AM' and '10/17/2011 4:44:28 AM' 
		--and BoxId =999888 
		--and BoxMsgInTypeId =4
		--and speed >150 and Speed <= 200
		select 'Above 120', COUNT(a.Speed) from rvlfMsgInHst a
			INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
			INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
			INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId 
			where    
			(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND 
			(@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and      
			v.VehicleDescription =@VehicleDesc  and
			((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
			a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
			and a.BoxMsgInTypeId =4 
			--and a.speed >120 
			and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int)  >120 

		select * from @tblSpeedAlert 

    SET NOCOUNT OFF    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSpeedAlertsForDrillDownCriticalChart_FleetBased]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[rvlf_sp_GetSpeedAlertsForDrillDownCriticalChart_FleetBased]    

 @VehicleDesc varchar(max) = NULL,    
 @bigOrganizationID bigint = NULL,    
 @bigQueryingUser bigint = NULL,
 @dtStartDate datetime = Null,    
 @dtEndDate datetime = NULL,
 @bigFleetID bigint = null  
 
AS  
/********************************************************************************************************    
-- Name		   : rvlf_sp_GetSpeedAlertsForDrillDownCriticalChart_FleetBased
-- Description : To get the Speed Alerts details        
-- Author      : Kapil        
*********************************************************************************************************/ 
BEGIN    
 SET NOCOUNT ON 
 --select a.Speed,COUNT(a.speed) as NoofSpeedCount
 --FROM rvlfMsgInHst  a  
 --  INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
 --  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
 --  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
 -- WHERE   
 --     (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND 
 --          (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and    
 --    v.VehicleDescription =@VehicleDesc  and
 --  ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
 --    a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
 --  and a.BoxMsgInTypeId =4
 
 --  GROUP BY a.Speed
 --  order by a.Speed desc
 
  DECLARE @ConversionFactor numeric (10,2) = 1.0  
  
    select @ConversionFactor = CASE WHEN Distance = 0 THEN 0.62 ELSE 1.0 END  
     from rvlfUserPreferences where UserId = @bigQueryingUser    
     
 
 DECLARE @tblSpeedAlert TABLE     
  (RangeAlert varchar(max),SpeedCount int)
  
	insert into @tblSpeedAlert(RangeAlert,SpeedCount)
 
	select '30-60', COUNT(a.Speed) from rvlfMsgInHst a
		INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
		INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId 
		INNER JOIN rvlfFleet F on F.FleetId = fv.FleetId 
		where    
		(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND 
		--(@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and      
		f.FleetName =@VehicleDesc  and
		((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
		a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
		and a.BoxMsgInTypeId =4 
		--and a.speed >30 and a.Speed <= 60
		 and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int)  >30 and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int) <= 60   
 
	insert into @tblSpeedAlert(RangeAlert,SpeedCount)
	select '61-90', COUNT(a.Speed) from rvlfMsgInHst a
		INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
		INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId
		INNER JOIN rvlfFleet F on F.FleetId = fv.FleetId  
		where    
		(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND 
		--(@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and      
		f.FleetName =@VehicleDesc  and
		((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
		a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
		and a.BoxMsgInTypeId =4 
		--and a.speed >60 and a.Speed <= 90
		and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int)  >60 and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int) <= 90   

	insert into @tblSpeedAlert(RangeAlert,SpeedCount)
	select '91-120', COUNT(a.Speed) from rvlfMsgInHst a
		INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
		INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId 
		INNER JOIN rvlfFleet F on F.FleetId = fv.FleetId 
		where    
		(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND 
	--	(@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and      
	f.FleetName =@VehicleDesc  and
		((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
		a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
		and a.BoxMsgInTypeId =4 
		--and a.speed >90 and a.Speed <= 120
		and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int)  >90 and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int) <= 120   

		insert into @tblSpeedAlert(RangeAlert,SpeedCount)
		--select '150-200', COUNT(Speed)
		--from rvlfMsgInHst where 
		--OriginDateTime between '10/10/2011 4:44:28 AM' and '10/17/2011 4:44:28 AM' 
		--and BoxId =999888 
		--and BoxMsgInTypeId =4
		--and speed >150 and Speed <= 200
		select 'Above 120', COUNT(a.Speed) from rvlfMsgInHst a
			INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId  
			INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
			INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId 
			INNER JOIN rvlfFleet F on F.FleetId = fv.FleetId 
			where    
			(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID) AND 
			--(@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) and      
			f.FleetName =@VehicleDesc  and
			((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
			a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
			and a.BoxMsgInTypeId =4 
			--and a.speed >120 
			and CAST (CAST(a.Speed AS numeric(10,2)) * @ConversionFactor  as int)  >120 

		select * from @tblSpeedAlert 

    SET NOCOUNT OFF    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSpeedBand]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetSpeedBand]        
@bigFleetID bigint = null,        
@intBoxID varchar(max) = null,            
@dtStartDate datetime=null,        
@dtEndDate datetime=null,        
@bigOrganizationID bigint = null,        
@bigQueryingUser bigint = null      
AS        
/********************************************************************************************************        
-- Name     : rvlf_sp_GetSpeedBand 173,null,'06/16/2013 08:00:00 AM','06/17/2013 08:00:00 PM',113,648  
-- Description : To get the speed band details            
-- Author      : S.Sakthi Gopinath S            
*********************************************************************************************************/        
BEGIN        
        
 SET NOCOUNT ON        
     
  Declare @dtFDate datetime =@dtStartDate        
  Declare @dtEDate datetime =@dtEndDate         
  DECLARE @HoursToBeAdded INT = 0            
  DECLARE @MinsToBeAdded INT = 0            
  DECLARE @DefaultDateFormat INT = 0;        
              
  SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,            
  @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 = @bigQueryingUser            
               
  SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))            
  SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))          
        
  DECLARE @tblSpeedBand TABLE         
  ( [ID] bigint identity(1,1),[BoxId] bigint, [CustomProp] [varchar](500) NULL,  [SpeedBand1] [varchar](150) NULL,        
    [SpeedBand2] [varchar](150) NULL, [SpeedBand3] [varchar](150) NULL, [SpeedBand4] [varchar](150) NULL,        
    [SpeedBand5] [varchar](150) NULL, [SpeedBand6] [varchar](150) NULL, [SentDateTime] datetime null  unique clustered  (ID,Boxid)       
  )        
  INSERT INTO @tblSpeedBand(BoxId,CustomProp,SpeedBand1,SpeedBand2,SpeedBand3,SpeedBand4,SpeedBand5,SpeedBand6,SentDateTime)        
  SELECT MO.BoxId,MO.CustomProp,    
  CASE WHEN LEN(MO.CustomProp) > 4  THEN CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,Charindex('02,',MO.CustomProp,0)+5,7),CHARINDEX(',',SUBSTRING(MO.CustomProp,Charindex('02,',MO.CustomProp,0)+5,7))-3,3)) AS VARCHAR)+' - '+ CAST(ABS(SUBSTRING(SUBSTRING(MO
  
.CustomProp,Charindex('02,',MO.CustomProp,0)+5,7),CHARINDEX(',',SUBSTRING(MO.CustomProp,Charindex('02,',MO.CustomProp,0)+5,7))+1,3)) AS VARCHAR) ELSE 'NA' END AS SpeedBand1,        
  CASE WHEN LEN(MO.CustomProp) > 16 THEN CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,18,7),CHARINDEX(',',SUBSTRING(MO.CustomProp,18,7))-3,3))  AS VARCHAR)+' - '+CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,18,7),CHARINDEX(',',SUBSTRING(MO.CustomProp,18,7))+1
  
,3))  AS VARCHAR) ELSE 'NA' END AS SpeedBand2,        
  CASE WHEN LEN(MO.CustomProp) > 28 THEN CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,30,7),CHARINDEX(',',SUBSTRING(MO.CustomProp,30,7))-3,3)) AS VARCHAR)+' - '+ CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,30,7),CHARINDEX(',',SUBSTRING(MO.CustomProp,30,7))+1
  
,3)) AS VARCHAR) ELSE 'NA' END AS SpeedBand3,        
  CASE WHEN LEN(MO.CustomProp) > 40 THEN CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,42,7),CHARINDEX(',',SUBSTRING(MO.CustomProp,42,7))-3,3)) AS VARCHAR)+' - '+ CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,42,7),CHARINDEX(',',SUBSTRING(MO.CustomProp,42,7))+1
  
,3)) AS VARCHAR) ELSE 'NA' END AS SpeedBand4,        
  CASE WHEN LEN(MO.CustomProp) > 52 THEN CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,54,7),CHARINDEX(',',SUBSTRING(MO.CustomProp,54,7))-3,3)) AS VARCHAR) +' - '+ CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,54,7),CHARINDEX(',',SUBSTRING(MO.CustomProp,54,7))+
  
1,3))  AS VARCHAR)ELSE 'NA' END AS SpeedBand5,        
  CASE WHEN LEN(MO.CustomProp) > 64 THEN CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,66,7),CHARINDEX(',',SUBSTRING(MO.CustomProp,66,7))-3,3)) AS VARCHAR) +' - '+ CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,66,7),CHARINDEX(',',SUBSTRING(MO.CustomProp,66,7))+
  
1,3)) AS VARCHAR) ELSE 'NA' END AS SpeedBand6,    
        
  --CASE WHEN LEN(MO.CustomProp) > 4  THEN CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,Charindex('02,',MO.CustomProp,0)+5,5),CHARINDEX(',',SUBSTRING(MO.CustomProp,Charindex('02,',MO.CustomProp,0)+5,5),0)-2,2)) AS varchar)+' - '+CAST(ABS(SUBSTRING(SUBSTRING
--(MO.CustomProp,Charindex('02,',MO.CustomProp,0)+5,5),CHARINDEX(',',SUBSTRING(MO.CustomProp,Charindex('02,',MO.CustomProp,0)+5,5),0)+1,2)) AS VARCHAR) ELSE 'NA' END AS SpeedBand1,        
  --CASE WHEN LEN(MO.CustomProp) > 13 THEN CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,15,5),CHARINDEX(',',SUBSTRING(MO.CustomProp,15,5),0)-2,2)) AS varchar)+' - '+CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,15,5),CHARINDEX(',',SUBSTRING(MO.CustomProp,15,5)
--,0)+1,2)) AS VARCHAR)ELSE 'NA' END AS SpeedBand2,        
  --CASE WHEN LEN(MO.CustomProp) > 22 THEN CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,24,5),CHARINDEX(',',SUBSTRING(MO.CustomProp,24,5),0)-2,2)) AS varchar)+' - '+CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,24,5),CHARINDEX(',',SUBSTRING(MO.CustomProp,24,5)
--,0)+1,2)) AS VARCHAR)ELSE 'NA' END AS SpeedBand3,        
  --CASE WHEN LEN(MO.CustomProp) > 31 THEN CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,33,5),CHARINDEX(',',SUBSTRING(MO.CustomProp,33,5),0)-2,2)) AS varchar)+' - '+CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,33,5),CHARINDEX(',',SUBSTRING(MO.CustomProp,33,5)
--,0)+1,2)) AS VARCHAR)ELSE 'NA' END AS SpeedBand4,        
  --CASE WHEN LEN(MO.CustomProp) > 40 THEN CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,42,5),CHARINDEX(',',SUBSTRING(MO.CustomProp,42,5),0)-2,2)) AS varchar)+' - '+CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,42,5),CHARINDEX(',',SUBSTRING(MO.CustomProp,42,5)
--,0)+1,2)) AS VARCHAR)ELSE 'NA' END AS SpeedBand5,        
  --CASE WHEN LEN(MO.CustomProp) > 49 THEN CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,51,5),CHARINDEX(',',SUBSTRING(MO.CustomProp,51,5),0)-2,2)) AS varchar)+' - '+CAST(ABS(SUBSTRING(SUBSTRING(MO.CustomProp,51,5),CHARINDEX(',',SUBSTRING(MO.CustomProp,51,5)
--,0)+1,2)) AS VARCHAR)ELSE 'NA' END AS SpeedBand6,    
      
  --CASE WHEN LEN(MO.CustomProp) > 5 THEN Replace(SUBSTRING(MO.CustomProp,Charindex('02,',CustomProp,0)+5,5),',',' - ') ELSE 'NA' END AS SpeedBand1,        
  --CASE WHEN LEN(MO.CustomProp) > 13 THEN Replace(SUBSTRING(MO.CustomProp,15,5),',',' - ') ELSE 'NA' END AS SpeedBand2,        
  --CASE WHEN LEN(MO.CustomProp) > 22 THEN Replace(SUBSTRING(MO.CustomProp,24,5),',',' - ') ELSE 'NA' END AS SpeedBand3,        
  --CASE WHEN LEN(MO.CustomProp) > 31 THEN Replace(SUBSTRING(MO.CustomProp,33,5),',',' - ') ELSE 'NA' END AS SpeedBand4,        
  --CASE WHEN LEN(MO.CustomProp) > 40 THEN Replace(SUBSTRING(MO.CustomProp,42,5),',',' - ') ELSE 'NA' END AS SpeedBand5,        
      
  --CASE WHEN LEN(MO.CustomProp) > 5 THEN Replace(SUBSTRING(MO.CustomProp,Charindex('02,',CustomProp,0)+5,4),',',' - ') ELSE 'NA' END AS SpeedBand1,        
  --CASE WHEN LEN(MO.CustomProp) > 11 THEN Replace(SUBSTRING(MO.CustomProp,13,5),',',' - ') ELSE 'NA' END AS SpeedBand2,        
  --CASE WHEN LEN(MO.CustomProp) > 19 THEN Replace(SUBSTRING(MO.CustomProp,21,5),',',' - ') ELSE 'NA' END AS SpeedBand3,        
  --CASE WHEN LEN(MO.CustomProp) > 28 THEN Replace(SUBSTRING(MO.CustomProp,29,5),',',' - ') ELSE 'NA' END AS SpeedBand4,        
  --CASE WHEN LEN(MO.CustomProp) > 35 THEN Replace(SUBSTRING(MO.CustomProp,37,5),',',' - ') ELSE 'NA' END AS SpeedBand5,      
  --CASE WHEN LEN(MO.CustomProp) > 49 THEN Replace(SUBSTRING(MO.CustomProp,51,5),',',' - ') ELSE 'NA' END AS SpeedBand6,        
  MO.SentDateTime FROM rvlfMsgOutHst MO INNER JOIN rvlfUser u ON u.UserId=MO.UserId         
  WHERE MO.BoxCmdOutTypeId=55 and MO.SentDateTime < @dtEndDate         
  Group by MO.BoxId,MO.CustomProp,MO.BoxCmdOutTypeId,MO.SentDateTime,u.UserName Order By MO.SentDateTime DESC        
        
  --SELECT * FROM @tblSpeedBand        
     
 DECLARE @tblSpeedBand_1 TABLE         
 ([ID] bigint identity(1,1), [BoxId] bigint, [BandName] [varchar](500) NULL,  [TotalDuration] varchar(75) null,  unique clustered  (ID,Boxid)       
 )        
     
 Insert into @tblSpeedBand_1(BoxId,BandName,TotalDuration)      
 SELECT BoxId,SUBSTRING(CustomProp,Charindex('Band Name=',CustomProp,0)+10,12),      
 dbo.rvlf_fn_GetTimeFromSeconds(SUM(Cast(SUBSTRING(CustomProp,Charindex('Duration=',CustomProp,0)+9,(CHARINDEX(';Odometer=',CustomProp,1)- (CHARINDEX('Duration=',CustomProp,1)+9))) AS int)))      
 FROM rvlfMsgInHst WHERE BoxMsgInTypeId=113 and SUBSTRING(CustomProp,Charindex('Band Name=',CustomProp,0)+10,12) NOT LIKE 'Duration%'      
 and OriginDateTime BETWEEN @dtStartDate and @dtEndDate      
 Group by BoxId,SUBSTRING(CustomProp,Charindex('Band Name=',CustomProp,0)+10,12)      
 Order by BoxId,SUBSTRING(CustomProp,Charindex('Band Name=',CustomProp,0)+10,12)      
      
      
  Declare @tblSpeedBand_2 TABLE      
  (      
 [ID] bigint identity(1,1),BoxId bigint null, OriginDateTime Varchar(30) null,OriginDateTimeSort datetime null,BandName varchar(500) null,SpeedRange varchar(10) null,      
 SP1 int null,SP2 int null,SP3 int null,SP4 int null,SP5 int null,SP6 int null,Duration varchar(50) null,SP int null,      
 SP1_Sec varchar(75) default 'NA',SP2_Sec varchar(75) default 'NA',SP3_Sec varchar(75) default 'NA',SP4_Sec varchar(75) default 'NA',SP5_Sec varchar(75) default 'NA',SP6_Sec varchar(75) default 'NA',      
 SP1_Range varchar(75) default 'NA',SP2_Range varchar(75) default 'NA',SP3_Range varchar(75) default 'NA',SP4_Range varchar(75) default 'NA',SP5_Range varchar(75) default 'NA',SP6_Range varchar(75) default 'NA',      
 Distance int null,FleetName varchar(100) null,Vin varchar(50) null,LicensePlate varchar(60) null,VehicleDescription varchar(200) null,      
 OrganizationDisplayName varchar(150) null, unique clustered  (ID,Boxid)       
  )      
      
  INSERT INTO @tblSpeedBand_2       
  (BoxId, OriginDateTime,OriginDateTimeSort,BandName,SpeedRange,SP1,SP2,SP3,SP4,SP5,SP6,Duration,SP,Distance,FleetName,Vin,LicensePlate,VehicleDescription,OrganizationDisplayName)      
  SELECT h.BoxId,      
  OriginDateTime = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,h.OriginDateTime),    
  --CONVERT(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime)),@DefaultDateFormat)+ ' ' + CONVERT(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime)) as time),22)  as OriginDateTime,      
  h.OriginDateTime AS OriginDateTimeSort,    
  --Convert(varchar,h.OriginDateTime,@DefaultDateFormat) + ' ' + Convert(varchar,cast(h.OriginDateTime as time),22) as OriginDateTime,        
  SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12) AS BandName,        
  CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 1' THEN         
   ISNULL((SELECT Top 1 SpeedBand1 FROM @tblSpeedBand WHERE BoxId=h.BoxId),'NA')        
  WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 2' THEN         
   ISNULL((SELECT Top 1 SpeedBand2 FROM @tblSpeedBand WHERE BoxId=h.BoxId),'NA')        
  WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 3' THEN         
   ISNULL((SELECT Top 1 SpeedBand3 FROM @tblSpeedBand WHERE BoxId=h.BoxId),'NA')        
  WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 4' THEN         
   ISNULL((SELECT Top 1 SpeedBand4 FROM @tblSpeedBand WHERE BoxId=h.BoxId),'NA')        
  WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 5' THEN         
   ISNULL((SELECT Top 1 SpeedBand5 FROM @tblSpeedBand WHERE BoxId=h.BoxId),'NA')        
  WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 6' THEN         
   ISNULL((SELECT Top 1 SpeedBand6 FROM @tblSpeedBand WHERE BoxId=h.BoxId),'NA')        
  ELSE  '-'        
  END AS SpeedRange,        
  CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 1' THEN 1 ELSE 0 END AS SP1,        
  CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 2' THEN 1 ELSE 0 END AS SP2,        
  CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 3' THEN 1 ELSE 0 END AS SP3,        
  CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 4' THEN 1 ELSE 0 END AS SP4,        
  CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 5' THEN 1 ELSE 0 END AS SP5,        
  CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 6' THEN 1 ELSE 0 END AS SP6,        
  dbo.rvlf_fn_GetTimeFromSeconds(Cast(SUBSTRING(h.CustomProp,Charindex('Duration=',h.CustomProp,0)+9,        
  (CHARINDEX(';Odometer=',h.CustomProp,1)- (CHARINDEX('Duration=',h.CustomProp,1)+9))) AS int)) AS Duration,      
  Cast(SUBSTRING(h.CustomProp,Charindex('Duration=',h.CustomProp,0)+9,            
  (CHARINDEX(';Odometer=',h.CustomProp,1)- (CHARINDEX('Duration=',h.CustomProp,1)+9))) AS int) AS SP,     
  --CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 1' THEN tblSB.TotalDuration ELSE Cast('00:00:00' AS Time) END AS SP1_Sec,        
  --CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 2' THEN tblSB.TotalDuration ELSE Cast('00:00:00' AS Time) END AS SP2_Sec,        
  --CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 3' THEN tblSB.TotalDuration ELSE Cast('00:00:00' AS Time) END AS SP3_Sec,        
  --CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 4' THEN tblSB.TotalDuration ELSE Cast('00:00:00' AS Time) END AS SP4_Sec,        
  --CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 5' THEN tblSB.TotalDuration ELSE Cast('00:00:00' AS Time) END AS SP5_Sec,        
  --CASE WHEN SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)='Speed Band 6' THEN tblSB.TotalDuration ELSE Cast('00:00:00' AS Time) END AS SP6_Sec,          
  0 as Distance,f.FleetName,v.Vin,v.LicensePlate,v.VehicleDescription,o.OrganizationDisplayName        
  FROM rvlfMsgInHst h         
  INNER JOIN rvlfVehicleAssignment va ON va.BoxId=h.BoxId INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId        
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=v.VehicleId        
  INNER JOIN rvlfFleet f ON fv.FleetId=f.FleetId        
  INNER JOIN rvlfOrganization o ON v.OrganizationId=o.OrganizationId        
  INNER JOIN @tblSpeedBand_1 tblSB ON tblSB.BoxId=h.BoxId and tblSB.BandName= SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12)      
  WHERE h.BoxMsgInTypeId=113 and SUBSTRING(h.CustomProp,Charindex('Band Name=',h.CustomProp,0)+10,12) NOT LIKE 'Duration%' and        
  (f.FleetId=@bigFleetID) and    
  (o.OrganizationId=@bigOrganizationID) and    
  (@intBoxID IS NULL OR @intBoxID='0' OR @intBoxID='' OR va.BoxId in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) and     
  h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
  Order By BoxId ASC, BandName ASC,OriginDateTime DESC        
      
  Update b SET b.SP1_Sec=ISNULL(a.TotalDuration,'NA') FROM @tblSpeedBand_1 a INNER JOIN @tblSpeedBand_2 b on b.BoxId=a.BoxId and a.BandName='Speed Band 1'      
  Update b SET b.SP2_Sec=ISNULL(a.TotalDuration,'NA') FROM @tblSpeedBand_1 a INNER JOIN @tblSpeedBand_2 b on b.BoxId=a.BoxId and a.BandName='Speed Band 2'      
  Update b SET b.SP3_Sec=ISNULL(a.TotalDuration,'NA') FROM @tblSpeedBand_1 a INNER JOIN @tblSpeedBand_2 b on b.BoxId=a.BoxId and a.BandName='Speed Band 3'      
  Update b SET b.SP4_Sec=ISNULL(a.TotalDuration,'NA') FROM @tblSpeedBand_1 a INNER JOIN @tblSpeedBand_2 b on b.BoxId=a.BoxId and a.BandName='Speed Band 4'      
  Update b SET b.SP5_Sec=ISNULL(a.TotalDuration,'NA') FROM @tblSpeedBand_1 a INNER JOIN @tblSpeedBand_2 b on b.BoxId=a.BoxId and a.BandName='Speed Band 5'      
  Update b SET b.SP6_Sec=ISNULL(a.TotalDuration,'NA') FROM @tblSpeedBand_1 a INNER JOIN @tblSpeedBand_2 b on b.BoxId=a.BoxId and a.BandName='Speed Band 6'      
      
  Update a SET a.SP1_Range=REPLACE(b.SpeedRange,' - ',' to ')+' kms' FROM @tblSpeedBand_2 a INNER JOIN @tblSpeedBand_2 b ON a.BoxId=b.BoxId and b.BandName='Speed Band 1'          
  Update a SET a.SP2_Range=REPLACE(b.SpeedRange,' - ',' to ')+' kms' FROM @tblSpeedBand_2 a INNER JOIN @tblSpeedBand_2 b ON a.BoxId=b.BoxId and b.BandName='Speed Band 2'          
  Update a SET a.SP3_Range=REPLACE(b.SpeedRange,' - ',' to ')+' kms' FROM @tblSpeedBand_2 a INNER JOIN @tblSpeedBand_2 b ON a.BoxId=b.BoxId and b.BandName='Speed Band 3'          
  Update a SET a.SP4_Range=REPLACE(b.SpeedRange,' - ',' to ')+' kms' FROM @tblSpeedBand_2 a INNER JOIN @tblSpeedBand_2 b ON a.BoxId=b.BoxId and b.BandName='Speed Band 4'          
  Update a SET a.SP5_Range=REPLACE(b.SpeedRange,' - ',' to ')+' kms' FROM @tblSpeedBand_2 a INNER JOIN @tblSpeedBand_2 b ON a.BoxId=b.BoxId and b.BandName='Speed Band 5'          
  Update a SET a.SP6_Range=REPLACE(b.SpeedRange,' - ',' to ')+' kms' FROM @tblSpeedBand_2 a INNER JOIN @tblSpeedBand_2 b ON a.BoxId=b.BoxId and b.BandName='Speed Band 6'          
      
        
  SELECT *,Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,      
  Convert(varchar,@dtEDate,@DefaultDateFormat)+' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,    
  PasGenerateddate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())        
  --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate        
  
   
  FROM @tblSpeedBand_2      
      
  --To Get data for speed band charts     
  SELECT BoxId,VehicleDescription,    
  ABS(SUM(CASE BandName WHEN 'Speed Band 1' THEN SP ELSE 0 END)/60) AS Q1,    
  ABS(SUM(CASE BandName WHEN 'Speed Band 2' THEN SP ELSE 0 END)/60) AS Q2,    
  ABS(SUM(CASE BandName WHEN 'Speed Band 3' THEN SP ELSE 0 END)/60) AS Q3,    
  ABS(SUM(CASE BandName WHEN 'Speed Band 4' THEN SP ELSE 0 END)/60) AS Q4,    
  ABS(SUM(CASE BandName WHEN 'Speed Band 5' THEN SP ELSE 0 END)/60) AS Q5,    
  ABS(SUM(CASE BandName WHEN 'Speed Band 6' THEN SP ELSE 0 END)/60) AS Q6,    
  dbo.rvlf_fn_GetTimeFromSeconds(SUM(CASE BandName WHEN 'Speed Band 1' THEN SP ELSE 0 END)) AS Dur1,    
  dbo.rvlf_fn_GetTimeFromSeconds(SUM(CASE BandName WHEN 'Speed Band 2' THEN SP ELSE 0 END)) AS Dur2,    
  dbo.rvlf_fn_GetTimeFromSeconds(SUM(CASE BandName WHEN 'Speed Band 3' THEN SP ELSE 0 END)) AS Dur3,    
  dbo.rvlf_fn_GetTimeFromSeconds(SUM(CASE BandName WHEN 'Speed Band 4' THEN SP ELSE 0 END)) AS Dur4,    
  dbo.rvlf_fn_GetTimeFromSeconds(SUM(CASE BandName WHEN 'Speed Band 5' THEN SP ELSE 0 END)) AS Dur5,    
  dbo.rvlf_fn_GetTimeFromSeconds(SUM(CASE BandName WHEN 'Speed Band 6' THEN SP ELSE 0 END)) AS Dur6    
  FROM @tblSpeedBand_2 GROUP BY BoxId,VehicleDescription    
        
 SET NOCOUNT OFF        
     
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetStationName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================          
-- Author:  Selvakumar          
-- Create date: 27-06-2012          
-- Description: Get the Station          
-- =============================================          
CREATE PROCEDURE [dbo].[rvlf_sp_GetStationName]        
@FleetID bigint =0,          
@OrganizationID bigint =0,          
@StationID bigint =0,          
@Mode bigint =0,      
@SchoolID Bigint =0        
AS          
BEGIN          
IF(@Mode=1)          
 BEGIN       
 IF(@SchoolID is null or @SchoolID ='')      
 BEGIN      
 SELECT distinct(f.StationID),f.FleetId,f.FleetName FROM rvlfFleet F           
 INNER JOIN rvlfFleetVehicles fv on fv.FleetId = f.FleetId          
 INNER JOIN rvlfVehicle v on v.VehicleId = fv.VehicleId         
 where f.OrganizationId =@OrganizationID        
 END      
 ELSE      
 BEGIN      
 SELECT distinct(f.StationID),f.FleetId,f.FleetName FROM rvlfFleet F           
 INNER JOIN rvlfFleetVehicles fv on fv.FleetId = f.FleetId          
 INNER JOIN rvlfVehicle v on v.VehicleId = fv.VehicleId        
 INNER JOIN rvlfSchoolMaster sm on sm.StationID = f.StationID       
 where f.OrganizationId =@OrganizationID and  sm.SchoolID = @SchoolID       
 END      
 END          
ELSE IF(@Mode =2)          
 BEGIN          
 SELECT distinct(f.FleetId),f.FleetName, F.StationID FROM rvlfFleet F           
 INNER JOIN rvlfFleetVehicles fv on fv.FleetId = f.FleetId          
 INNER JOIN rvlfVehicle v on v.VehicleId = fv.VehicleId          
 where f.OrganizationId = @OrganizationID and F.StationID =@StationID          
 END          
ELSE IF(@Mode =3)          
 BEGIN          
 SELECT InternalNo,va.StationID from rvlfFleetVehicles vf           
 inner join rvlfVehicle vg on vg.VehicleId = vf.VehicleId          
 inner join rvlfFleet va on va.FleetId = vf.FleetId      
 WHERE va.StationID = @FleetID and InternalNo is not NULL          
 END          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetStockDtlsReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROC [dbo].[rvlf_sp_GetStockDtlsReport]    
@bigFleetID bigint = NULL,                  
@intBoxID varchar(max) = NULL,                  
@dtStartDate datetime = NULL,                  
@dtEndDate datetime =NULL,                  
@bigOrganizationID bigint = NULL,                  
@bigQueryingUser bigint = NULL,    
@ItemQty varchar(1)='0'    
AS                              
/*******************************************************************************************************/    
-- Name  : [rvlf_sp_GetStockDtlsReport] null,null,'2015-06-15 10:27:01.000','2015-06-17 11:23:00.000',6,94,0
-- Description : To get the Stock Details as a report                  
-- Created date : 23-Jun-2015                  
-- Created by : Gopalakrishnan.R                  
/*******************************************************************************************************/                                
BEGIN                              
SET NOCOUNT ON                              
                             
 DECLARE @dtFDate datetime =@dtStartDate                                
 DECLARE @dtEDate datetime =@dtEndDate                                
 DECLARE @HoursToBeAdded INT = 0                                
 DECLARE @MinsToBeAdded INT = 0                                 
 DECLARE @DefaultDateFormat INT = 0                              
 DECLARE @MinQty int=0,@MaxQty int=0    
select @MinQty=(case when @ItemQty=1 then 0 when @ItemQty=2 then 101 when @ItemQty=3 then 501 when @ItemQty=4 then 1000 else 0 end),    
@MaxQty=(case when @ItemQty=1 then 100 when @ItemQty=2 then 500 when @ItemQty=3 then 1000 when @ItemQty=4 then 0 else 0 end)    
    
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                              
 @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(@bigQueryingUser IS NULL OR @bigQueryingUser='' OR up.UserId = @bigQueryingUser)                          
     
 SELECT itmc.ItemCatID,itmc.ItemCategoryName,ItmC.ItemCatDesc,Itm.Itemcode,Itm.ItemName,itm.OpenQty,Itm.ReorderQty,Itm.UnitPrice,Itm.UOM,  
 itm.AvailQty, case when ReorderQty > AvailQty then 1 else 0 end as LowStock,    
Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate          
 from  rvlfInvItemMaster Itm inner join rvlfItemCategory ItmC on Itm.ItemCatID=ItmC.ItemCatID    
WHERE  itm.IsActive=1 and  
--  (@dtStartDate BETWEEN DateFrom AND DateTo  or @dtEndDate BETWEEN DateFrom AND DateTo)  and                   
 (@bigFleetID IS NULL OR @bigFleetID=0 OR Itm.ItemCatID=@bigFleetID) and      
 (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR Itm.OrganizatioID=@bigOrganizationID) and    
 (Itm.AvailQty >=@MinQty and ( @MaxQty=0 or Itm.AvailQty<=@MaxQty ))    
--order by DateFrom              
  
SET NOCOUNT OFF                              
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetstudentAssignments]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetstudentAssignments]                      
 @intVehicleId bigint =null,                      
 @bigOrganizationID bigint = null,                      
 @bitIsAssigned bit = 0,                       
 @intUserid bigint = null                          
AS                      
/******************************************************************************/                      
-- Name  : rvlf_sp_GetStudentAssignments 32,6,0,19                     
-- Description : To get assinged and unassinged users in User Groups                      
-- Author  : Ranjith. N                      
-- Company  : Angler Technologies                      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                      
--    : 25-Aug-2014  Created Intial Version                       
/******************************************************************************/                      
BEGIN                      
 SET NOCOUNT ON                   
                 
  Declare @Lang varchar(50)                                     
 select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @intUserid                      
                      
 --declare @usergrp int                    
 --   set @usergrp=(SELECT g.UserGroupId FROM rvlfStudentVehicleAssignment ga                         
 --   INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId                        
 --   WHERE ga.UserId = @intUserid)                    
                          
                          
 IF @bitIsAssigned = 0                       
 BEGIN                      
          
 select distinct(v.StudentID),v.StudentMasterID, v.StudentFirstName,v.StudentFirstName as DisplayName, v.StudentFirstName as Firstname,                          
   v.StudentLastName as LastName, v.Active as IsActive,                  
    CASE WHEN v.Active = 1 THEN 'Active' Else 'Inactive' END as ActiveStatusDisp,                             
    CASE WHEN v.Active =1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus ,RFID  , v.GeozoneId ,OG.GeozoneName,sm.SchoolName,v.LandmarkName              
  FROM rvlfStudentMaster v      
  inner join rvlfSchoolMaster sm on sm.SchoolID=v.SchoolID  
  left join rvlfOrganizationGeozone OG on v.GeozoneId=OG.GeozoneId  and OG.OrganizationId=@bigOrganizationID                       
  WHERE (v.OrganizationId = @bigOrganizationID)  and                             
   v.StudentMasterID NOT IN   (select distinct StudentMasterId from rvlfStudentVehicleAssignment)           
   --AND v.StudentMasterID NOT IN                      
   -- ( SELECT ug.StudentMasterID FROM rvlfStudentVehicleAssignment ug WHERE (@intVehicleId IS NULL OR @intVehicleId='' OR ug.VehicleId = @intVehicleId))                      
           
                 
  ORDER BY StudentFirstName asc                      
 END                       
 ELSE IF @bitIsAssigned = 1                      
 BEGIN                              
   
    
  select distinct(v.StudentID),v.StudentMasterID, v.StudentFirstName,v.StudentFirstName as DisplayName, v.StudentFirstName as Firstname,                          
   v.StudentLastName as LastName, v.Active as IsActive,                  
    CASE WHEN v.Active = 1 THEN 'Active'  else 'Inactive' END as ActiveStatusDisp,                             
    CASE WHEN v.Active =1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus,RFID,v.GeozoneId,OG.GeozoneName,sm.SchoolName,v.LandmarkName      
  FROM rvlfStudentMaster v                           
  INNER JOIN rvlfStudentVehicleAssignment ug ON v.StudentMasterID = ug.StudentMasterID                           
  inner join rvlfSchoolMaster sm on sm.SchoolID=v.SchoolID  
  left join rvlfOrganizationGeozone OG on v.GeozoneId=OG.GeozoneId  and OG.OrganizationId=@bigOrganizationID     
  WHERE (v.OrganizationId = @bigOrganizationID)                           
   AND (@intVehicleId IS NULL OR @intVehicleId='' OR ug.VehicleId = @intVehicleId)                                
  ORDER BY StudentFirstName asc     
                
 END             
                       
 SET NOCOUNT OFF                      
END                      
                      
-- exec rvlf_sp_GetUserGroupAssignments @intUserGroupId = 3,@bigOrganizationID = 1,@vcUserName='k' 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_SP_GetStudentAttendance]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_SP_GetStudentAttendance]                
@intVehicleId varchar(max) = null,            
@bigOrganizationID bigint =null,            
@dtStartDate Datetime = null,  
@dtEndDate Datetime = null,  
@intUserid bigint = null     
AS            
/******************************************************************************/            
-- Name  : rvlf_SP_GetStudentAttendance 2308,230,'04/Oct/2016 12:00:00 AM','06/Oct/2016 8:00:00 AM',140        
-- Description : Getting Student History            
-- Author  : N.Ranjith  
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--    : 12-Sep-2014            
/******************************************************************************/       
BEGIN                 
 SET NOCOUNT ON;     
 DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                              
  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit,@Lang varchar(50),  @LangSetting varchar(20)                                 
                                 
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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')                                     
  FROM rvlfUserPreferences up                               
   INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                               
  WHERE up.UserId = @intUserid                                                              
     
IF OBJECT_ID ('tempdb.dbo.#tblHistory') IS NOT NULL
drop table #tblHistory
IF OBJECT_ID ('tempdb.dbo.##tempTest') IS NOT NULL
drop table ##tempTest
IF OBJECT_ID ('tempdb.dbo.##tempTestWhile') IS NOT NULL
drop table ##tempTestWhile

   Create table #tblHistory
  ( 
   Sno bigint identity(1,1),
  Date_Name varchar(max)
  ) 
insert into #tblHistory
SELECT 'StudentID'
union
Select 'StudentName'
;WITH date_range (calc_date) AS (
    SELECT DATEADD(DAY, DATEDIFF(DAY, 0, @dtEndDate) - DATEDIFF(DAY, @dtStartDate, @dtEndDate), 0)
        UNION ALL SELECT DATEADD(DAY, 1, calc_date)
            FROM date_range
            WHERE DATEADD(DAY, 1, calc_date) <= @dtEndDate)

insert into #tblHistory
SELECT  REPLACE(CONVERT(varchar,calc_date,106),' ','') 
FROM date_range;

--select * from #tblHistory

DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX), @sql1 NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME(Date_Name)
  FROM (SELECT p.Date_Name,p.Sno FROM #tblHistory AS p 
  GROUP BY p.Sno,p.Date_Name) AS x;
SET @sql = N'select * into ##tempTest from( SELECT ' + STUFF(@columns, 1, 2, '') + '
FROM
(
  SELECT cast(p.Date_Name as varchar) as Date_Name,cast(p.Sno as varchar) as Sno
   FROM #tblHistory AS p
   
) AS j PIVOT
(
  min(sno) FOR Date_Name IN ('
  + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
  + ')
) AS p) as p1;';
--PRINT @sql;


EXEC sp_executesql @sql;

Declare @ActiveStatus varchar(max)
delete from ##tempTest
--Alter table  ##tempTest add StudentID varchar(max),StudentName varchar(max)

insert into ##tempTest (StudentId,StudentName)
select sm.StudentMasterID,sm.StudentFirstName
			from rvlfStudentVehicleAssignment SVM 
			inner join rvlfVehicle v on v.VehicleId = SVM.VehicleId
				inner join rvlfStudentMaster sm on sm.StudentMasterID =SVM.StudentMasterId
				where  v.OrganizationId = @bigOrganizationID and (@intVehicleID IS NULL OR @intVehicleID='' OR v.VehicleId = @intVehicleID) 
				
--select StudentMasterID,StudentFirstName from rvlfStudentMaster where OrganizationID = @bigOrganizationID

select * into ##tempTestWhile from( 
select * from rvlf_StudentRFIDSMSMessegeInIDLog h				
where h.OrganizationId = @bigOrganizationID and (cast(h.entryexit as date) between @dtStartDate  and @dtEndDate)and (h.VehicleId = @intVehicleID))as p3
 
  DECLARE @intStudentMasterID varchar(max) =(SELECT MIN(StudentID) FROM ##tempTest)    
      
  WHILE @intStudentMasterID IS NOT NULL    
   BEGIN    
  
      
   DECLARE @intStudentMasterID1 varchar(max) =(SELECT MIN(Date_Name) FROM #tblHistory)    
      
   WHILE @intStudentMasterID1 IS NOT NULL    
   BEGIN   
		 
		 
		 if exists(select *
			from ##tempTestWhile h --rvlf_StudentRFIDSMSMessegeInIDLog h				
				where h.OrganizationId = @bigOrganizationID and  (cast(h.entryexit as date) between @dtStartDate  and @dtEndDate) and (@intVehicleID IS NULL OR @intVehicleID='' OR h.VehicleId = @intVehicleID) and 
     			(REPLACE(CONVERT(varchar,h.EntryExit,106),' ','') = @intStudentMasterID1) and
     			h.rfid = (select RFID from rvlfStudentMaster where StudentMasterID = @intStudentMasterID))
     			begin 
     			Set @ActiveStatus = 1
     			end
     			else
     			Begin
     			Set @ActiveStatus = 0
     			end
		
		SET @sql1 = N'update ##tempTest set [' + @intStudentMasterID1 + ']=' + @ActiveStatus + ' where StudentId=' + @intStudentMasterID
		EXEC sp_executesql @sql1;
		
        
   
    select @intStudentMasterID1 = MIN(Date_Name) from #tblHistory where Date_Name > @intStudentMasterID1              
  End  
   
   select @intStudentMasterID = MIN(StudentId) from ##tempTest where StudentId > @intStudentMasterID              
  End  
  
select * from ##tempTest




                             
 --SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                                      
 --SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))     
    
  --DECLARE @tblHistory table    
  --(    
  --StudentName varchar(max),
  --DateInt bigint
  --)  
  --insert into @tblHistory(StudentName) 
  --select StudentFirstName from rvlfStudentMaster where OrganizationID = @bigOrganizationID
   
 -- DECLARE @hid INT
 -- DECLARE @intStudentNameLooping varchar(max) =(SELECT MIN(StudentName) FROM @tblHistory)    
      
 -- WHILE @intStudentNameLooping IS NOT NULL    
 --  BEGIN   
   
 --   SET @hid=1;
	--WHILE @hid < 31
 --   BEGIN 
 --   INSERT @tblHistory(DateInt)
 --   VALUES(@hid)
 --   SET @hid = @hid + 1;
 --   END
   
 --  select @intStudentNameLooping = MIN(StudentName) from @tblHistory where StudentName > @intStudentNameLooping              
 -- End  
 
 --select * from @tblHistory
   
 SET NOCOUNT OFF;     
   
End 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_SP_GetStudentAttendance_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_SP_GetStudentAttendance_PhoneGap]                
@bigQueryingUser bigint = 0,            
@intStudentId varchar(max) = null ,
@dtStartDate Datetime = null,  
@dtEndDate Datetime = null
       
AS            
/******************************************************************************/            
-- Name  : rvlf_SP_GetStudentAttendance_PhoneGap 11,null,'09/01/2014 12:00:00 AM','09/05/2014 8:00:00 AM'
-- Description : Getting Student History            
-- Author  : N.Ranjith  
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--    : 12-Sep-2014            
/******************************************************************************/       
BEGIN         

SET NOCOUNT ON;     
 DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                              
  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit,@Lang varchar(50),  @LangSetting varchar(20)                                 
                                 
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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')                                     
  FROM rvlfUserPreferences up                               
   INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                               
  WHERE up.UserId = @bigQueryingUser                                                              
     
IF OBJECT_ID ('tempdb.dbo.#tblHistoryAttendance') IS NOT NULL
drop table #tblHistoryAttendance
IF OBJECT_ID ('tempdb.dbo.##tempTestAttendance') IS NOT NULL
drop table ##tempTestAttendance

   Create table #tblHistoryAttendance
  ( 
   Sno bigint identity(1,1),
  Date_Name varchar(max)
  ) 
insert into #tblHistoryAttendance
SELECT 'StudentID'
union
Select 'StudentName'
;WITH date_range (calc_date) AS (
    SELECT DATEADD(DAY, DATEDIFF(DAY, 0, @dtEndDate) - DATEDIFF(DAY, @dtStartDate, @dtEndDate), 0)
        UNION ALL SELECT DATEADD(DAY, 1, calc_date)
            FROM date_range
            WHERE DATEADD(DAY, 1, calc_date) <= @dtEndDate)

insert into #tblHistoryAttendance
SELECT  REPLACE(CONVERT(varchar,calc_date,106),' ',' ') 
FROM date_range;

--select * from #tblHistory

DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX), @sql1 NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME(Date_Name)
  FROM (SELECT p.Date_Name,p.Sno FROM #tblHistoryAttendance AS p 
  GROUP BY p.Sno,p.Date_Name) AS x;
SET @sql = N'select * into ##tempTestAttendance from( SELECT ' + STUFF(@columns, 1, 2, '') + '
FROM
(
  SELECT cast(p.Date_Name as varchar) as Date_Name,cast(p.Sno as varchar) as Sno
   FROM #tblHistoryAttendance AS p
   
) AS j PIVOT
(
  min(sno) FOR Date_Name IN ('
  + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
  + ')
) AS p) as p1;';
--PRINT @sql;


EXEC sp_executesql @sql;

Declare @ActiveStatus varchar(max)
delete from ##tempTestAttendance
--Alter table  ##tempTest add StudentID varchar(max),StudentName varchar(max)

insert into ##tempTestAttendance (StudentId,StudentName)
select sm.StudentMasterID,sm.StudentFirstName
			from rvlfStudentVehicleAssignment SVM 
			inner join rvlfVehicle v on v.VehicleId = SVM.VehicleId
				inner join rvlfStudentMaster sm on sm.StudentMasterID =SVM.StudentMasterId
		inner join rvlfParentMaster p on p.MobileNo = sm.ContactNo
	where
     p.UserId = @bigQueryingUser		and
	   (@intStudentId IS NULL OR @intStudentId='' OR sm.StudentMasterID = @intStudentId) 
--select StudentMasterID,StudentFirstName from rvlfStudentMaster where OrganizationID = @bigOrganizationID

--select * from ##tempTestAttendance
 
  DECLARE @intStudentMasterID varchar(max) =(SELECT MIN(StudentID) FROM ##tempTestAttendance)    
      
  WHILE @intStudentMasterID IS NOT NULL    
   BEGIN    
  
      
   DECLARE @intDate_Name varchar(max) =(SELECT MIN(Date_Name) FROM #tblHistoryAttendance)    
      
   WHILE @intDate_Name IS NOT NULL    
   BEGIN   

		 if exists(select *
			from rvlf_StudentRFIDSMSMessegeInIDLog h
				inner join rvlfParentMaster p on p.OrganizationId = h.OrganizationID
				where p.UserId = @bigQueryingUser and
     			(REPLACE(CONVERT(varchar,h.EntryExit,106),' ','') = @intDate_Name) and
     			h.rfid = (select RFID from rvlfStudentMaster where StudentMasterID = @intStudentMasterID))
     			begin 
     			Set @ActiveStatus = 1
     			end
     			else
     			Begin
     			Set @ActiveStatus = 0
     			end
		
		SET @sql1 = N'update ##tempTestAttendance set [' + @intDate_Name + ']=' + @ActiveStatus + ' where StudentId=' + @intStudentMasterID
		EXEC sp_executesql @sql1;
   
    select @intDate_Name = MIN(Date_Name) from #tblHistoryAttendance where Date_Name > @intDate_Name              
  End  
   	
   select @intStudentMasterID = MIN(StudentId) from ##tempTestAttendance where StudentId > @intStudentMasterID              
  End  
  
select * from ##tempTestAttendance
   
 SET NOCOUNT OFF;     
 
         
-- SET NOCOUNT ON;     
-- DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                              
--  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit,@Lang varchar(50),  @LangSetting varchar(20)                                 
                                 
-- SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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')                                     
--  FROM rvlfUserPreferences up                               
--   INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                               
--  WHERE up.UserId = @bigQueryingUser                                                              
     
--IF OBJECT_ID ('tempdb.dbo.#tblHistory') IS NOT NULL
--drop table #tblHistory
--IF OBJECT_ID ('tempdb.dbo.##tempTest') IS NOT NULL
--drop table ##tempTest

--   Create table #tblHistory
--  ( 
--   Sno bigint identity(1,1),
--  Date_Name varchar(max),

--  ) 
--insert into #tblHistory
--Select Null
--;WITH date_range (calc_date) AS (
--    SELECT DATEADD(DAY, DATEDIFF(DAY, 0, @dtEndDate) - DATEDIFF(DAY, @dtStartDate, @dtEndDate), 0)
--        UNION ALL SELECT DATEADD(DAY, 1, calc_date)
--            FROM date_range
--            WHERE DATEADD(DAY, 1, calc_date) <= @dtEndDate)

--insert into #tblHistory
--SELECT  REPLACE(CONVERT(varchar,calc_date,106),' ','') 
--FROM date_range;



--   Create table #tblStudentLst
--  ( 
--     Sno bigint identity(1,1),
--	 StudentId bigint,	 
--   Studentname varchar(max)

--  ) 

--  insert into #tblStudentLst
--  select sm.StudentMasterID, sm.StudentFirstName   from rvlfStudentMaster sm   
--	inner join rvlfParentMaster p on p.MobileNo = sm.ContactNo
--	where--  (@intVehicleID IS NULL OR @intVehicleID='' OR va.VehicleId = @intVehicleID) and 
--     p.UserId = @bigQueryingUser	

----select h.Sno,h.Date_Name,sm.StudentFirstName   from #tblHistory h,rvlfStudentMaster sm
   
----	inner join rvlfParentMaster p on p.MobileNo = sm.ContactNo
----	where--  (@intVehicleID IS NULL OR @intVehicleID='' OR va.VehicleId = @intVehicleID) and 
----     p.UserId = @bigQueryingUser		
	 
	

--DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX), @sql1 NVARCHAR(MAX);
--SET @columns = N'';
--SELECT @columns += N', p.' + QUOTENAME(Studentname)
--  FROM (SELECT p.Studentname,p.Sno FROM #tblStudentLst AS p 
--  GROUP BY p.Sno,p.Studentname) AS x;
--SET @sql = N'select * into ##tempTest from( SELECT ' + STUFF(@columns, 1, 2, '') + '
--FROM
--(
--  SELECT cast(p.Studentname as varchar) as Studentname,cast(p.Sno as varchar) as Sno
--   FROM #tblStudentLst AS p
   
--) AS j PIVOT
--(
--  min(sno) FOR Studentname IN ('
--  + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
--  + ')
--) AS p) as p1;';


--EXEC sp_executesql @sql;

--	--SET @sql1 = N' Select * from  ##tempTest;'
--	--	EXEC sp_executesql @sql1;

----Declare @ActiveStatus varchar(max)
--delete from ##tempTest
--Select * into #tblHistoryStudentAttendance  from   #tblHistory,##tempTest 

--insert into #tblHistoryStudentAttendance (Sno,Date_Name)
--select Sno,Date_Name from #tblHistory


--select * from #tblHistoryStudentAttendance



------Alter table  ##tempTest add StudentID varchar(max),StudentName varchar(max)

----insert into ##tempTest (StudentId,StudentName)
----select sm.StudentMasterID,sm.StudentFirstName
----			from rvlfStudentVehicleAssignment SVM 
----			inner join rvlfVehicle v on v.VehicleId = SVM.VehicleId
----				inner join rvlfStudentMaster sm on sm.StudentMasterID =SVM.StudentMasterId
----				inner join rvlfParentMaster p on p.MobileNo = sm.ContactNo
----				where--  (@intVehicleID IS NULL OR @intVehicleID='' OR va.VehicleId = @intVehicleID) and 
----                 p.UserId = @bigQueryingUser			 
------select StudentMasterID,StudentFirstName from rvlfStudentMaster where OrganizationID = @bigOrganizationID

 
--  DECLARE @intStudentMasterID varchar(max) =(SELECT MIN(StudentID) FROM #tblHistoryStudentAttendance)    
      
--  WHILE @intStudentMasterID IS NOT NULL    
--   BEGIN    
  
      
--   DECLARE @intStudentMasterID1 varchar(max) =(SELECT MIN(Date_Name) FROM #tblHistory)    
      
--   WHILE @intStudentMasterID1 IS NOT NULL    
--   BEGIN   
		 
		 
--		 if exists(select *
--			from rvlf_StudentRFIDSMSMessegeInIDLog h
--			inner join rvlfStudentMaster s on s.StudentMasterID = h.StudentID
--			inner join rvlfParentMaster p on p.MobileNo = s.ContactNo				
--				where 
--				    p.UserId = @bigQueryingUser and
--				-- (@intVehicleID IS NULL OR @intVehicleID='' OR h.VehicleId = @intVehicleID) and h.OrganizationId = @bigOrganizationID and
--     			(REPLACE(CONVERT(varchar,h.EntryExit,106),' ','') = @intStudentMasterID1) and
--     			h.rfid = (select RFID from rvlfStudentMaster where StudentMasterID = @intStudentMasterID))
--     			begin 
--     			Set @ActiveStatus = 1
--     			end
--     			else
--     			Begin
--     			Set @ActiveStatus = 0
--     			end
		
--		SET @sql1 = N'update ##tempTest set [' + @intStudentMasterID1 + ']=' + @ActiveStatus + ' where StudentId=' + @intStudentMasterID
--		EXEC sp_executesql @sql1;
		
        
   
--    select @intStudentMasterID1 = MIN(Date_Name) from #tblHistory where Date_Name > @intStudentMasterID1              
--  End  
   
--   select @intStudentMasterID = MIN(StudentId) from ##tempTest where StudentId > @intStudentMasterID              
--  End  
  
--select * from ##tempTest
 --SET NOCOUNT OFF;     
   
End 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_SP_GetStudentHistory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_SP_GetStudentHistory]              
@intVehicleId varchar(max) = null,          
@bigOrganizationID bigint =null,          
@dtStartDate Datetime = null,
@dtEndDate Datetime = null,
@intUserid bigint = null   
AS          
/******************************************************************************/          
-- Name  : rvlf_SP_GetStudentHistory 2302,230,'10/28/2015 12:00:00 AM','9/28/2015 8:00:00 AM',140      
-- Description : Getting Student History          
-- Author  : N.Ranjith
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : 12-Sep-2014          
/******************************************************************************/     
BEGIN               
 SET NOCOUNT ON;   
 DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                            
  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit,@Lang varchar(50),  @LangSetting varchar(20)                               
                               
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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')                                   
  FROM rvlfUserPreferences up                             
   INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                             
  WHERE up.UserId = @intUserid                                                            
                                
 --SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                                    
 --SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))   
  
  DECLARE @tblHistory table  
  (  
  Boxid bigint,
  Origindatetime datetime,
  CustomProp varchar(max),
  BoxmsginTypeId bigint,
  RFID varchar(max),
  GeozoneID bigint
  )
  insert into @tblHistory
 -- select h.BoxId,OriginDateTime,CustomProp,BoxMsgInTypeId,dbo.rvlf_fn_GetParamValueWithIndex(customprop,'RF_ID=',';'),dbo.rvlf_fn_GetParamValueWithIndex(customprop,'GeozoneID=',';') from rvlfMsgInHst h
 -- inner join rvlfVehicleAssignment va on va.BoxId = h.BoxId 
 -- inner join rvlfVehicle v on v.VehicleId =va.VehicleId
 -- left outer join rvlfStudentVehicleAssignment SVM on SVM.VehicleId =va.VehicleId
 -- where  (@intVehicleID IS NULL OR @intVehicleID='' OR va.VehicleId = @intVehicleID) and v.OrganizationId = @bigOrganizationID and
 ----(h.OriginDateTime between @dtStartDate and @dtEndDate) 
 --(convert(date,h.OriginDateTime) = convert(date,@dtStartDate)) 
 --and BoxMsgInTypeId in (5,6,114,100) and (CustomProp like '%geozone%' or CustomProp like '%RF_ID%') order by Origindatetime 
  select h.BoxId,EntryExit,null,StatusType,RFID,GeozoneID
  from rvlf_StudentRFIDSMSMessegeInIDLog h
  inner join rvlfVehicleAssignment va on va.BoxId = h.BoxId 
  inner join rvlfVehicle v on v.VehicleId =va.VehicleId
  left outer join rvlfStudentVehicleAssignment SVM on SVM.VehicleId =va.VehicleId
  where  (@intVehicleID IS NULL OR @intVehicleID='' OR va.VehicleId = @intVehicleID) and v.OrganizationId = @bigOrganizationID and
 --(h.OriginDateTime between @dtStartDate and @dtEndDate) 
 (convert(date,h.EntryExit) = convert(date,@dtStartDate)) 
 and StatusType in (1,2)  order by EntryExit 
 
 --select * from @tblHistory  order by Origindatetime 
  
 DECLARE @tblStudentHistory table  
  (  
   StudentMasterID Bigint,  
   StudentFirstName varchar(max),
   SchoolName varchar(max),      
   RFID varchar(max),    
   DateTimePunch DateTime,
   SchoolEntryPunch DateTime,  
   SchoolExitPunch DateTime,
   IsMapped bit
  )  

Declare @dtDateTimePunch DateTime,@SchoolEntryPunch DateTime,@SchollExitPunch DateTime
DECLARE @intGeozoneIDLooping INT =(SELECT MIN(GeozoneID) FROM @tblHistory)  
    
  WHILE @intGeozoneIDLooping IS NOT NULL  
   BEGIN 
   
 
 DECLARE @intRFIDLooping varchar(max) =(SELECT MIN(RFID) FROM @tblHistory)  
    
  WHILE @intRFIDLooping IS NOT NULL  
   BEGIN 
   
 --select top 1 @SchoolEntryPunch=OriginDateTime from @tblHistory where OriginDateTime between @dtStartDate and 
 --( select top 1 origindatetime from @tblHistory h
 --inner join rvlfSchoolMaster sm on sm.geozoneId= h.GeozoneID
 --where BoxMsgInTypeId in (5) and h.GeozoneID =@intGeozoneIDLooping) 
 --and BoxMsgInTypeId in (100) and  RFID =@intRFIDLooping order by OriginDateTime asc
 
 --select  top 1  @SchollExitPunch=OriginDateTime  from @tblHistory where OriginDateTime between 
 --( select top 1 origindatetime from @tblHistory h
 --inner join rvlfSchoolMaster sm on sm.geozoneId= h.GeozoneID
 --where BoxMsgInTypeId in (5)  and h.GeozoneID =@intGeozoneIDLooping) 
 --and
 --(select top 1 origindatetime from @tblHistory h
 --inner join rvlfSchoolMaster sm on sm.geozoneId= dbo.rvlf_fn_GetParamValueWithIndex(customprop,'GeozoneID=',';')
 --where BoxMsgInTypeId in (6,114) and (CustomProp like '%geozone%')  and h.GeozoneID =@intGeozoneIDLooping)
 --and BoxMsgInTypeId in (100)  and  RFID =@intRFIDLooping order by OriginDateTime asc
 
  
 select top 1 @SchoolEntryPunch=OriginDateTime from @tblHistory where GeozoneID = @intGeozoneIDLooping and BoxmsginTypeId =1 order by OriginDateTime asc
 
 select top 1 @SchollExitPunch=OriginDateTime from @tblHistory where GeozoneID = @intGeozoneIDLooping and BoxmsginTypeId =2 order by OriginDateTime desc
 
 insert into @tblStudentHistory
  select distinct sm.StudentMasterID, sm.StudentFirstName,s.SchoolName ,sm.RFID,@SchoolEntryPunch,@SchoolEntryPunch,@SchollExitPunch,
  Case when Not Exists (Select * from rvlfStudentVehicleAssignment svm
  inner join rvlfStudentMaster sm on sm.StudentMasterID =svm.StudentMasterId
   where VehicleId = @intVehicleId and sm.RFID = @intRFIDLooping) then 1 else 0 end
  from rvlfStudentMaster sm
  inner join rvlfSchoolMaster s on s.SchoolID = sm.SchoolID
 where sm.RFID =@intRFIDLooping
 
 
 select @intRFIDLooping = MIN(RFID) from @tblHistory where RFID > @intRFIDLooping            
 End
 
 select @intGeozoneIDLooping = MIN(GeozoneID) from @tblHistory where GeozoneID > @intGeozoneIDLooping            
 End
   
   select  sm.StudentID, sh.StudentMasterID ,sh.StudentFirstName ,SchoolName,sh.RFID ,(CONVERT(VARCHAR,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@intUserid,@HoursToBeAdded,@MinsToBeAdded,DateTimePunch),@DefaultDateFormat)) as  DateTimePunch,
   (CONVERT(VARCHAR,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@intUserid,@HoursToBeAdded,@MinsToBeAdded,SchoolEntryPunch),@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@intUserid,@HoursToBeAdded,@MinsToBeAdded,SchoolEntryPunch)),22)) as SchoolEntryPunch , 
   (CONVERT(VARCHAR,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@intUserid,@HoursToBeAdded,@MinsToBeAdded,SchoolExitPunch),@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@intUserid,@HoursToBeAdded,@MinsToBeAdded,SchoolExitPunch)),22)) as SchoolExitPunch ,
   (case when (SchoolEntryPunch is not null and SchoolExitPunch is null) then 'Reached to School'   
   when (SchoolEntryPunch is not null and SchoolExitPunch is not null) then 'Started from School' else '' end
   ) as ActiveStatusDisp,sh.IsMapped,sm.Grade from @tblStudentHistory sh
   inner join rvlfStudentMaster  sm on sm.StudentMasterID = sh.StudentMasterID  
   
                                  
 --DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                            
 -- @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit,@Lang varchar(50),  @LangSetting varchar(20)                               
                               
 --SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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')                                   
 -- FROM rvlfUserPreferences up                             
 --  INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                             
 -- WHERE up.UserId = @intUserid                                                            
                                
 --SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                                    
 --SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))   
 
 --select sm.StudentMasterID, sm.StudentFirstName,sm.StudentFirstName as DisplayName,sm.Active as ActiveStatus,sm.Active as ActiveStatusDisp, sm.RFID,
 --(CONVERT(VARCHAR,h.OriginDateTime,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,h.OriginDateTime),22)) as DateTimePunch,
 --s.StationName as SchoolName
 
 -- from rvlfMsgInHst h
 --inner join rvlfStudentMaster sm on sm.RFID = SUBSTRING (CustomProp,CHARINDEX('RF_ID=',CustomProp,1)+6,CHARINDEX(';',CustomProp,            
 --CHARINDEX('RF_ID=',CustomProp,1)) - (CHARINDEX('RF_ID=',CustomProp,1)+6))
 --left outer join rvlfSchoolMaster s on s.SchoolMID = sm.SchoolCode
 --inner join rvlfVehicleAssignment va on va.BoxId = h.BoxId
 --inner join rvlfStudentVehicleAssignment SVM on SVM.VehicleId =va.VehicleId
 --where --(@StudentMasterID IS NULL OR @StudentMasterID='' OR StudentMasterID = @StudentMasterID) and 
 --(@intVehicleID IS NULL OR @intVehicleID='' OR va.VehicleId = @intVehicleID) and 
 --OriginDateTime between @dtStartDate and @dtEndDate and CustomProp like '%rf_id%' order by OriginDateTime desc
 
 SET NOCOUNT OFF;   
 
End


GO
/****** Object:  StoredProcedure [dbo].[rvlf_SP_GetStudentHistory_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_SP_GetStudentHistory_PhoneGap]              
@bigQueryingUser bigint = 0,        
@intStudentId varchar(max) = null,                 
@dtStartDate Datetime = null,
@dtEndDate Datetime = null
AS          
/******************************************************************************/          
-- Name  : rvlf_SP_GetStudentHistory_PhoneGap 11,49,'09/07/2015 12:00:00 AM','9/12/2015 8:00:00 AM'
-- Description : Getting Student History          
-- Author  : N.Ranjith
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : 12-Sep-2014          
/******************************************************************************/     
BEGIN               
 SET NOCOUNT ON;   
 DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                            
  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit,@Lang varchar(50),  @LangSetting varchar(20)                               
                               
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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')                                   
  FROM rvlfUserPreferences up                             
   INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                             
  WHERE up.UserId = @bigQueryingUser                                                            
                                
 --SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                                    
 --SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))   
  
  DECLARE @tblHistory table  
  (  
  Boxid bigint,
  Origindatetime datetime,
  CustomProp varchar(max),
  BoxmsginTypeId bigint,
  RFID varchar(max),
  GeozoneID bigint
  )
  insert into @tblHistory
 -- select h.BoxId,OriginDateTime,CustomProp,BoxMsgInTypeId,dbo.rvlf_fn_GetParamValueWithIndex(customprop,'RF_ID=',';'),dbo.rvlf_fn_GetParamValueWithIndex(customprop,'GeozoneID=',';') from rvlfMsgInHst h
 -- inner join rvlfVehicleAssignment va on va.BoxId = h.BoxId 
 -- inner join rvlfVehicle v on v.VehicleId =va.VehicleId
 -- left outer join rvlfStudentVehicleAssignment SVM on SVM.VehicleId =va.VehicleId
 -- where  (@intVehicleID IS NULL OR @intVehicleID='' OR va.VehicleId = @intVehicleID) and v.OrganizationId = @bigOrganizationID and
 ----(h.OriginDateTime between @dtStartDate and @dtEndDate) 
 --(convert(date,h.OriginDateTime) = convert(date,@dtStartDate)) 
 --and BoxMsgInTypeId in (5,6,114,100) and (CustomProp like '%geozone%' or CustomProp like '%RF_ID%') order by Origindatetime 
  select h.BoxId,EntryExit,null,StatusType,s.RFID,h.GeozoneID  
  from rvlf_StudentRFIDSMSMessegeInIDLog h
  inner join rvlfVehicleAssignment va on va.BoxId = h.BoxId 
  inner join rvlfVehicle v on v.VehicleId =va.VehicleId
  left outer join rvlfStudentVehicleAssignment SVM on SVM.VehicleId =va.VehicleId  
      INNER JOIN rvlfStudentMaster s on s.StudentMasterId = SVM.StudentMasterId    
    INNER JOIN rvlfParentMaster p on p.MobileNo =  s.ContactNo   
  where  p.UserId = @bigQueryingUser  and h.StudentID = @IntStudentId and
 --(h.OriginDateTime between @dtStartDate and @dtEndDate) 
 (convert(date,h.EntryExit) between convert(date,@dtStartDate) and  convert(date,@dtEndDate)) 
 and StatusType in (1,2)  order by EntryExit 
 
 --select * from @tblHistory  order by Origindatetime 
  
 DECLARE @tblStudentHistory table  
  (  
   StudentMasterID Bigint,  
   StudentFirstName varchar(max),
   SchoolName varchar(max),      
   RFID varchar(max),    
   DateTimePunch DateTime,
   SchoolEntryPunch DateTime,  
   SchoolExitPunch DateTime,
   IsMapped bit
  )  

Declare @dtDateTimePunch DateTime,@SchoolEntryPunch DateTime,@SchollExitPunch DateTime

   
 
 DECLARE @intRFIDLooping varchar(max) =(SELECT MIN(RFID) FROM @tblHistory)  
    
  WHILE @intRFIDLooping IS NOT NULL  
   BEGIN 

   DECLARE @intDateLooping date =(SELECT MIN(cast(Origindatetime as Date)) FROM @tblHistory)  
    
  WHILE @intDateLooping IS NOT NULL  
   BEGIN 
   
 select top 1 @SchoolEntryPunch=OriginDateTime from @tblHistory where cast(Origindatetime as Date) = @intDateLooping and BoxmsginTypeId =1  and RFID = @intRFIDLooping order by Origindatetime asc
 
 select top 1 @SchollExitPunch=OriginDateTime from @tblHistory where cast(Origindatetime as Date) = @intDateLooping and BoxmsginTypeId =2 and RFID = @intRFIDLooping order by Origindatetime Desc
 
 insert into @tblStudentHistory
  select distinct sm.StudentMasterID, sm.StudentFirstName,s.SchoolName ,sm.RFID,cast( t.Origindatetime as date),@SchoolEntryPunch,@SchollExitPunch,
  Case when Not Exists (Select * from rvlfStudentVehicleAssignment svm
  inner join rvlfStudentMaster sm on sm.StudentMasterID =svm.StudentMasterId
   where 
   --VehicleId = @intVehicleId and 
   sm.RFID = @intRFIDLooping) then 1 else 0 end
  from rvlfStudentMaster sm
  inner join rvlfSchoolMaster s on s.SchoolID = sm.SchoolID
  inner join @tblHistory t on t.RFID = sm.RFID
 
 where sm.RFID =@intRFIDLooping and cast(Origindatetime as Date) = @intDateLooping 

 
 select @intDateLooping = MIN(cast(Origindatetime as Date)) from @tblHistory where cast(Origindatetime as Date) > @intDateLooping            
 End
  select @intRFIDLooping = MIN(RFID) from @tblHistory where RFID > @intRFIDLooping            
 End

 --select * from @tblStudentHistory
   
   select distinct sm.StudentID, sh.StudentMasterID ,sh.StudentFirstName  as StudentName,SchoolName,(CONVERT(VARCHAR,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,DateTimePunch),@DefaultDateFormat)) as  DateTimePunch,
   (CONVERT(VARCHAR,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SchoolEntryPunch),@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SchoolEntryPunch)),22)) as SchoolEntryPunch , 
   isnull((CONVERT(VARCHAR,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SchoolExitPunch),@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SchoolExitPunch)),22)) ,0)as SchoolExitPunch ,
   (case when (SchoolEntryPunch is not null and SchoolExitPunch is null) then 'Reached to School'   
   when (SchoolEntryPunch is not null and SchoolExitPunch is not null) then 'Started from School' else '' end   
   ) as ActiveStatusDisp,  v.VehicleDescription   from @tblStudentHistory sh
   inner join rvlfStudentMaster  sm on sm.StudentMasterID = sh.StudentMasterID  
   inner join @tblHistory t on t.RFID = sh.RFID
    inner join rvlfVehicleAssignment va on va.BoxId = t.Boxid
  inner join rvlfVehicle v on v.VehicleId= va.VehicleId
   order by (CONVERT(VARCHAR,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,DateTimePunch),@DefaultDateFormat))
   
                                  
 --DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                            
 -- @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit,@Lang varchar(50),  @LangSetting varchar(20)                               
                               
 --SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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')                                   
 -- FROM rvlfUserPreferences up                             
 --  INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                             
 -- WHERE up.UserId = @intUserid                                                            
                                
 --SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                                    
 --SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))   
 
 --select sm.StudentMasterID, sm.StudentFirstName,sm.StudentFirstName as DisplayName,sm.Active as ActiveStatus,sm.Active as ActiveStatusDisp, sm.RFID,
 --(CONVERT(VARCHAR,h.OriginDateTime,@DefaultDateFormat)+' '+CONVERT(VARCHAR,CONVERT(TIME,h.OriginDateTime),22)) as DateTimePunch,
 --s.StationName as SchoolName
 
 -- from rvlfMsgInHst h
 --inner join rvlfStudentMaster sm on sm.RFID = SUBSTRING (CustomProp,CHARINDEX('RF_ID=',CustomProp,1)+6,CHARINDEX(';',CustomProp,            
 --CHARINDEX('RF_ID=',CustomProp,1)) - (CHARINDEX('RF_ID=',CustomProp,1)+6))
 --left outer join rvlfSchoolMaster s on s.SchoolMID = sm.SchoolCode
 --inner join rvlfVehicleAssignment va on va.BoxId = h.BoxId
 --inner join rvlfStudentVehicleAssignment SVM on SVM.VehicleId =va.VehicleId
 --where --(@StudentMasterID IS NULL OR @StudentMasterID='' OR StudentMasterID = @StudentMasterID) and 
 --(@intVehicleID IS NULL OR @intVehicleID='' OR va.VehicleId = @intVehicleID) and 
 --OriginDateTime between @dtStartDate and @dtEndDate and CustomProp like '%rf_id%' order by OriginDateTime desc
 
 SET NOCOUNT OFF;   
 
End 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_SP_GetStudentHistory_Report]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_SP_GetStudentHistory_Report]              
--@intVehicleId varchar(max) = null,          
@bigOrganizationID bigint =null,          
@dtStartDate Datetime = null,
@dtEndDate Datetime = null,
@intBoxID varchar(max) = null, 
@bigQueryingUser bigint = NULL,
@bigFleetID bigint=null
AS          
/******************************************************************************/          
-- Name  : rvlf_SP_GetStudentHistory_Report 230,'03/16/2016 1:00:00 AM','03/16/2016 8:00:00 PM','4368',140      
-- Description : Getting Student History          
-- Author  : N.Ranjith
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : 12-Sep-2014          
/******************************************************************************/     
BEGIN               
 SET NOCOUNT ON;   
 DECLARE @dtFDate datetime=@dtStartDate,@dtEDate datetime=@dtEndDate,@HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0,                            
  @ConversionFactor numeric (10,2) = 1.0,@isAnglerAdmin bit,@isPrevileged bit,@Lang varchar(50),  @LangSetting varchar(20)   
   
 DECLARE @tblHistory table  
  (
  Sno int identity(1,1),  
  MessageInId uniqueidentifier,
  Boxid bigint,
  Origindatetime datetime,
  CustomProp varchar(max),
  BoxmsginTypeId bigint,
  RFID varchar(max),
  GeozoneID bigint,vehicleid bigint,
  VehicleDescription varchar(100),Vin varchar(50),
  LicensePlate varchar(50),
  StreetAddress varchar(200)
  ) 
  
 DECLARE @TemptblStudentHistory table  
  (  
   StudentMasterID Bigint,  
   StudentFirstName varchar(max),
   SchoolName varchar(max),      
   RFID varchar(max),    
   DateTimePunch DateTime,
   SchoolEntryPunch DateTime,  
   SchoolExitPunch DateTime,
   IsMapped tinyint,vehicleid bigint,
  VehicleDescription varchar(100),Vin varchar(50),
  LicensePlate varchar(50),
  StreetAddress varchar(200)
  )
  DECLARE @tblStudentHistory table  
  (  
   StudentMasterID Bigint,  
   StudentFirstName varchar(max),
   SchoolName varchar(max),      
   RFID varchar(max),    
   DateTimePunch DateTime,
   SchoolEntryPunch DateTime,  
   SchoolExitPunch DateTime,
   IsMapped tinyint,vehicleid bigint,
  VehicleDescription varchar(100),Vin varchar(50),
  LicensePlate varchar(50),
  StreetAddress varchar(200)
  )
  DECLARE @tblSumStud table  
  ( 
  vehicleid bigint, 
   TotalStudent Bigint,
   TotMappedStud varchar(max),
   TotUnmappedStud varchar(max)
  )
DECLARE @StudentCnt table(vehicleid bigint,AssignedStud int)
DECLARE @dtDateTimePunch DateTime,@SchoolEntryPunch DateTime,@SchollExitPunch DateTime
DECLARE @intGeozoneIDLooping INT =(SELECT MIN(GeozoneID) FROM @tblHistory)  
DECLARE @intRFIDLooping varchar(30),@InOutdatetime datetime,@Sno int
----------------------------------------------------------------------------------------------------------------------------------  
  SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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')                                   
   FROM rvlfUserPreferences up                             
   INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                             
   WHERE up.UserId = @bigQueryingUser                                 
  
  SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                                    
  SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))   
  
  INSERT into @tblHistory  
    select h.MessageInID,h.BoxId,EntryExit,null,StatusType,RFID,GeozoneID,v.vehicleid,V.VehicleDescription,V.Vin,V.LicensePlate,MH.StreetAddress
   from rvlf_StudentRFIDSMSMessegeInIDLog h
    inner join rvlfVehicleAssignment va on va.BoxId = h.BoxId 
    inner join rvlfVehicle v on v.VehicleId =va.VehicleId  
	inner join rvlfMsgInHst MH on h.messageinid=mh.messageinid
    where  --(@intVehicleID IS NULL OR @intVehicleID='' OR va.VehicleId = @intVehicleID) 
    (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR  h.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))
    and v.OrganizationId = @bigOrganizationID and 
    va.vehicleid in (select vehicleid from rvlfstudentvehicleassignment) and
    h.EntryExit between @dtStartDate and @dtEndDate   
   --and RFID in ('00000000e3336435','0000000020276435','00000000b12d6435','000000003bbbe825','00000000009c6335','000000003d696435')
    and StatusType in (1,2)  order by EntryExit 

   INSERT into @studentcnt
     select sva.vehicleid,count(sva.studentmasterid) from rvlfschoolmaster a inner join rvlfstudentmaster stm on a.schoolid=stm.schoolid
     inner join rvlfstudentvehicleassignment sva on stm.studentmasterid=sva.studentmasterid
     inner join rvlfvehicleassignment va on sva.vehicleid=va.vehicleid
     where stm.isdelete=0 and a.organizationid=@bigOrganizationID and 
     (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR  va.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))
     --(@intVehicleID IS NULL OR @intVehicleID='' OR sva.VehicleId = @intVehicleID) 
     group by sva.vehicleid

  --WHILE @intGeozoneIDLooping IS NOT NULL  
  -- BEGIN    
 
  INSERT into @TemptblStudentHistory
    select distinct sm.StudentMasterID, sm.StudentFirstName,s.SchoolName ,sm.RFID,Origindatetime,Origindatetime,null,
    Case when Not Exists (Select * from rvlfStudentVehicleAssignment svm
    inner join rvlfStudentMaster sm on sm.StudentMasterID =svm.StudentMasterId
     where VehicleId = hh.vehicleid and sm.RFID = hh.RFID) then 0 else 1 end,vehicleid,
     hh.VehicleDescription,hh.Vin,hh.LicensePlate,hh.StreetAddress
    from rvlfStudentMaster sm
    inner join rvlfSchoolMaster s on s.SchoolID = sm.SchoolID
    inner join @tblHistory hh on sm.RFID=hh.RFID
   where hh.BoxmsginTypeId=1
   --select * from @TemptblStudentHistory
   
  
  SET @Sno =(SELECT MIN(Sno) FROM @tblHistory where BoxmsginTypeId=2)  
  WHILE @Sno IS NOT NULL  
   BEGIN   
  
  select @intRFIDLooping=RFID,@InOutdatetime=Origindatetime from @tblHistory where sno=@sno 
  set @SchoolEntryPunch=null  
 if exists (select * from @TemptblStudentHistory where RFID=@intRFIDLooping and SchoolExitPunch is null and SchoolEntryPunch <@InOutdatetime and 
 cast(SchoolEntryPunch as date) =cast(@InOutdatetime as date))
 begin
 update @TemptblStudentHistory set SchoolExitPunch=@InOutdatetime where RFID=@intRFIDLooping and SchoolExitPunch is null and SchoolEntryPunch <@InOutdatetime
 and cast(SchoolEntryPunch as date) =cast(@InOutdatetime as date)
 end
 else if not exists (select * from @TemptblStudentHistory where RFID=@intRFIDLooping and SchoolExitPunch=@InOutdatetime and 
 cast(SchoolEntryPunch as date) =cast(@InOutdatetime as date))
 begin
 insert into @TemptblStudentHistory
  select distinct sm.StudentMasterID, sm.StudentFirstName,s.SchoolName ,sm.RFID,Origindatetime,null,Origindatetime,
  Case when Not Exists (Select * from rvlfStudentVehicleAssignment svm
  inner join rvlfStudentMaster sm on sm.StudentMasterID =svm.StudentMasterId
   where VehicleId = hh.vehicleid and sm.RFID = hh.RFID) then 0 else 1 end,vehicleid,
   hh.VehicleDescription,hh.Vin,hh.LicensePlate,hh.StreetAddress
  from rvlfStudentMaster sm
  inner join rvlfSchoolMaster s on s.SchoolID = sm.SchoolID
  inner join @tblHistory hh on sm.RFID=hh.RFID
 where Sno=@Sno
 end
 select @Sno = MIN(Sno) from @tblHistory where Sno > @Sno and BoxmsginTypeId=2
 End
 --select @intGeozoneIDLooping = MIN(GeozoneID) from @tblHistory where GeozoneID > @intGeozoneIDLooping
 --End
   
   INSERT into @tblStudentHistory
   select distinct StudentMasterID, StudentFirstName, SchoolName,RFID,DateTimePunch,SchoolEntryPunch,SchoolExitPunch,IsMapped,vehicleid
   ,VehicleDescription,Vin,LicensePlate,StreetAddress from @TemptblStudentHistory

   INSERT into @tblSumStud
	select vehicleid,count(studentmasterid),sum(ismapped), (count(studentmasterid)- sum(ismapped))from (
   select studentmasterid,ismapped,vehicleid from @TemptblStudentHistory  group by studentmasterid,ismapped,vehicleid) as a group by vehicleid 

   
   --select * from @tblStudentHistory

   SELECT sm.StudentID, sh.StudentMasterID ,sh.StudentFirstName ,SchoolName,sh.RFID ,sh.VehicleDescription,sh.Vin,sh.LicensePlate
   ,(CONVERT(VARCHAR,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,DateTimePunch),@DefaultDateFormat)) as  DateTimePunch,
   (CONVERT(VARCHAR,dbo.rvlf_fn_DayLightSavings_Date(SchoolEntryPunch,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SchoolEntryPunch),@DefaultDateFormat)+' '+
   CONVERT(VARCHAR,CONVERT(TIME,dbo.rvlf_fn_DayLightSavings_Date(SchoolEntryPunch,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SchoolEntryPunch)),22)) as SchoolEntryPunch , 
   (CONVERT(VARCHAR,dbo.rvlf_fn_DayLightSavings_Date(SchoolExitPunch,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SchoolExitPunch),@DefaultDateFormat)+' '
   +CONVERT(VARCHAR,CONVERT(TIME,dbo.rvlf_fn_DayLightSavings_Date(SchoolExitPunch,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SchoolExitPunch)),22)) as SchoolExitPunch ,
   (case when (SchoolEntryPunch is not null and SchoolExitPunch is null) then 'Reached to School'   
   when (SchoolEntryPunch is not null and SchoolExitPunch is not null) then 'Started from School' else '' end
   ) as ActiveStatusDisp,sh.IsMapped,sm.Grade,
   Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,            
 Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,            
 Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate    
    ,TotalStudent,TotMappedStud,TotUnmappedStud,AssignedStud,sh.StreetAddress
	from @tblStudentHistory sh
   inner join rvlfStudentMaster  sm on sm.StudentMasterID = sh.StudentMasterID  
   inner join @tblSumStud sst on sh.vehicleid=sst.vehicleid
   inner join @StudentCnt ssc on sh.vehicleid=ssc.vehicleid                  
  
 SET NOCOUNT OFF;   
 
End


GO
/****** Object:  StoredProcedure [dbo].[rvlf_SP_GetStudentInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================                                
-- Author:  Selvakumar.S.V                                
-- Create date: 08-Jun-2012                                
-- Description: Manage Student information                               
-- =============================================                                
CREATE PROCEDURE [dbo].[rvlf_SP_GetStudentInfo]                                
@StudentMasterID varchar(max) = null,                            
@OrganizationID bigint = null,                            
@Mode tinyint =0,                            
@StudentID varchar(25) = null,                            
@StudentFirstName nvarchar(100)=null,                             
@StudentMiddleName nvarchar(30) =null,                            
@StudentLastName nvarchar(30) =null,                             
@FleetName nvarchar(50) =null,                             
@StationID nvarchar(50) =null,                             
@SchoolID nvarchar(20)=null,                             
@Grade nvarchar(15)=null,                             
@Gender bit =null,                             
@GuardianFirstName nvarchar(50)=null,                            
@Relationship nvarchar(30)=null,                             
@ContactNo varchar(15) =null,                            
@AlternateContactNo varchar(20) =null,                             
@EmailAddress nvarchar(100)=null,                             
@LandmarkName nvarchar(100)=null,                              
@PickupTime varchar(15) =null,                             
@DropOffTime varchar(15) =null,                             
@AddressLine1 nvarchar(200)=null,                             
@AddressLine2 nvarchar(200)=null,                             
@City nvarchar(50)=null,                             
@Region nvarchar(50)=null,                             
@Street nvarchar(100)=null,                             
@Country nvarchar(50)=null,                              
@CreatedBy bigint=0,                             
@CreatedDateTime datetime=null,                             
@Active bit=0,                             
@FutureUse1 nvarchar(50)=null,                            
@FutureUse2 nvarchar(50)=null,                             
@FutureUse3 nvarchar(50)=null,                            
@ModifiedBy bigint =0,                            
@ModifiedDate Datetime = null,                
@RFID varchar(500) = null,            
@SMSSettings int = null,                                       
@GeozoneId bigint= null,      
@NotificationType int =null,  
@Photo varchar(1000) = null, 
@ParentUserId bigint =null,
@AllowmobAccess int =null                                 
AS                                
BEGIN                                 
 SET NOCOUNT ON;                                 
                              
IF(@Mode = 1)                            
 BEGIN                            
                             
 SELECT sm.StudentFirstName +' ' + ISnull(sm.StudentMiddleName,'') +' ' + ISnull(sm.StudentLastName,'') as StudentName,f.FleetName,CASE WHEN  sm.Gender = 1 Then 'Male' ELSE 'Female' END as 'GenderN' , Case  WHEN Sm.Active  = 1 THEN 'Active' ELSE          


  
   
 'InActive' END as 'ActiveN' ,            
(case when SMSSettings = 0 then 'None' when SMSSettings = 1 then 'Onward Trip' when SMSSettings = 2 then 'Return Trip'            
when SMSSettings = 3 then 'Both' else 'None' end) as SMSSettings, OG.GeozoneName,          
* FROM rvlfStudentMaster sm                  
inner join rvlfSchoolMaster s on s.SchoolID=sm.SchoolID                        
  inner JOIN rvlfFleet f on f.FleetName = sm.FleetName and f.OrganizationId = @OrganizationID            
  left outer join rvlfOrganizationGeozone OG on OG.GeozoneId = sm.GeozoneId and OG.OrganizationId = @OrganizationID                        
 where sm.OrganizationID = @OrganizationID --and Active = 1                            
                      
  SELECT  SM.StudentFirstName +' ' + ISnull(SM.StudentMiddleName,'') +' ' + ISnull(SM.StudentLastName,'') as StudentName,SM.*,SL.SchoolID as SchoolCodeID,FL.StationID as Station_ID FROM rvlfStudentMaster SM                     
         inner JOIN rvlfSchoolMaster SL on SL.SchoolID = SM.SchoolID                    
         left outer JOIN rvlfFleet Fl on Fl.FleetName = SM.FleetName and Fl.OrganizationId = @OrganizationID                      
         Where SM.OrganizationID =@OrganizationID --and SM.Active =1               
        and(@StudentMasterID is null or @StudentMasterID ='' or StudentMasterID = @StudentMasterID)                    

DECLARE @tblParentAppDetails table              
  (
    MobileNo varchar(50),
	StudentName varchar(max),
	Email varchar(max),
	Username varchar(max),
	MobAppAccess varchar(max),
	AllowMobApp int,
	UserId bigint

  )              
  DECLARE @temp VARCHAR(MAX)
  insert into @tblParentAppDetails (MobileNo,Email ,Username ,	MobAppAccess ,	AllowMobApp,	UserId,StudentName)
SELECT PM.MobileNo,Email ,Username ,	CASE WHEN PM.AllowMobApp  = 1 THEN 'Allowed' ELSE 'Blocked' END AS 'MobAppAccess' ,	AllowMobApp,	UserId,
(SELECT ', ' + cast(StudentFirstName as varchar(max)) + '(' + StudentID + ') - ' + Grade  FROM rvlfStudentMaster where ContactNo =PM.MobileNo    FOR XML PATH('') ) 
  FROM rvlfParentMaster  PM  WHERE PM.OrganizationId =@OrganizationID

  Select MobileNo,Email ,Username ,	MobAppAccess ,	AllowMobApp,	UserId,substring(StudentName,2,len(StudentName)) as StudentName from @tblParentAppDetails
              
 --SELECT  StudentFirstName +' ' + ISnull(StudentMiddleName,'') +' ' + ISnull(StudentLastName,'') as StudentName,* FROM rvlfStudentMaster where OrganizationID = 107  and (StudentMasterID = 9688) and  Active =1                             
                             
   --SELECT  StudentFirstName +' ' + ISnull(StudentMiddleName,'') +' ' + ISnull(StudentLastName,'') as StudentName, * FROM rvlfStudentMaster where OrganizationID = @OrganizationID                             
                             
 END                              
ELSE IF(@Mode = 2)                            
 BEGIN                              
 --Update rvlfStudentMaster set Active = 0 where  StudentMasterID in(select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@StudentMasterID,',')) and OrganizationID =@OrganizationID               
 DELETE FROM rvlfStudentMaster WHERE  StudentMasterID in(select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@StudentMasterID,',')) and OrganizationID =@OrganizationID                              
 END                            
                       
ELSE IF(@Mode = 3)                            
 BEGIN                            
 insert into rvlfStudentMaster(StudentFirstName,StudentMiddleName,StudentLastName,Grade,Gender,GuardianFirstName,Relationship,ContactNo,AlternateContactNo,EmailAddress,                            
 AddressLine1,AddressLine2,City,Region,Street,Country,StudentID,FleetName,StationID,Active,LandmarkName,PickupTime,DropOffTime,FutureUse1,FutureUse2,FutureUse3,OrganizationID,CreatedBy,CreatedDateTime,                
 SchoolID,IsDelete,RFID,SMSSettings,GeozoneId)                            
 Values(@StudentFirstName,@StudentMiddleName,@StudentLastName,@Grade,@Gender,@GuardianFirstName,@Relationship,@ContactNo,@AlternateContactNo,@EmailAddress,                            
 @AddressLine1,@AddressLine2,@City,@Region,@Street,@Country,@StudentID,@FleetName,@StationID,@Active,@LandmarkName,@PickupTime,@DropOffTime,@FutureUse1,@FutureUse2,@FutureUse3,@OrganizationID,@CreatedBy,                
 GETUTCDATE(),@SchoolID,0,@RFID,@SMSSettings,@GeozoneId)                            
END                            
ELSE IF(@Mode = 4)                            
 BEGIN                            
 Update rvlfStudentMaster set StudentFirstName =@StudentFirstName,StudentMiddleName=@StudentMiddleName,StudentLastName=@StudentLastName,                            
 Grade=@Grade,Gender=@Gender,GuardianFirstName=@GuardianFirstName,                           
 Relationship=@Relationship,ContactNo=@ContactNo,AlternateContactNo=@AlternateContactNo,EmailAddress=@EmailAddress,SchoolID=@SchoolID,                            
 AddressLine1=@AddressLine1,AddressLine2=@AddressLine2,City=@City,Region=@Region,Street=@Street,Country=@Country,StudentID=@StudentID,                            
 FleetName=@FleetName,StationID=@StationID,Active=@Active,LandmarkName=@LandmarkName,PickupTime=@PickupTime,DropOffTime=@DropOffTime,                            
 FutureUse1=@FutureUse1,FutureUse2=@FutureUse2,FutureUse3=@FutureUse3,OrganizationID=@OrganizationID,ModifiedBy=@ModifiedBy,ModifiedDate=GETUTCDATE(),isDelete = 0,                
 RFID=@RFID,SMSSettings=@SMSSettings,GeozoneId=@GeozoneId               
 Where StudentMasterID =@StudentMasterID              
END                            
ELSE IF(@Mode =5)                            
 BEGIN                            
  SELECT COUNT(*) as 'Result' FROM rvlfStudentMaster                                 
  WHERE                         
   ((@StudentID IS NULL OR @StudentID='') OR StudentID = @StudentID)                                 
   AND StudentMasterID <> @StudentMasterID  and Active =1                             
                                  
-- SELECT * from rvlfschoolMAster where StudentID = @StudentID and StudentMasterID <> @StudentMasterID                            
 END        
-- ELSE IF(@Mode =7)                            
-- BEGIN                            
--  SELECT COUNT(*) as 'Result' FROM rvlfStudentMaster                                 
--  WHERE                                
--   ((RFID IS NULL OR @RFID='') OR RFID = @RFID)                                 
--   AND StudentMasterID <> @StudentMasterID  and Active =1                             
                                  
---- SELECT * from rvlfschoolMAster where StudentID = @StudentID and StudentMasterID <> @StudentMasterID                            
-- END                            
 ELSE IF(@Mode =6)                            
 BEGIN                            
 Update rvlfStudentMaster set Active =@Active where StudentMasterID =@StudentMasterID                            
 END     
 ELSE IF(@Mode =7)                              
 BEGIN                              
 Update rvlfStudentMaster set Photo =@Photo where StudentMasterID =@StudentMasterID                              
 END
 --checking whether the RFID is assigned to any Driver.  
 ELSE IF(@Mode =8)     
 BEGIN  
 SELECT COUNT(*) as 'RFID_Existence'  
 FROM rvlfIButtonMapping  
 WHERE ((@RFID IS NULL OR @RFID='') OR IButtonKey = @RFID)     
 END 
 ELSE IF(@Mode =9)                            
 BEGIN                            
 Update rvlfParentMaster set AllowMobApp =@AllowmobAccess where UserId =@ParentUserId                            
 END 
END                            
                    
                    
                           
                          
                            
   --SELECT  SM.StudentFirstName +' ' + ISnull(SM.StudentMiddleName,'') +' ' + ISnull(SM.StudentLastName,'') as StudentName,*,SL.SchoolID,FL.StationID FROM rvlfStudentMaster SM                     
      --   INNER JOIN rvlfSchoolMaster SL on SL.SchoolMID = SM.SchoolCode             
      --   LEFT OUTER JOIN rvlfFleet Fl on Fl.StationID = SM.StationID                     
      --   Where SM.OrganizationID =107 and SM.Active =1 and(@StudentMasterID is null or @StudentMasterID ='' or StudentMasterID = @StudentMasterID) 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetStudentswithParentApp]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 28-07-2015
-- Description:	Get list of Students whose parents are registered with ParentApp.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetStudentswithParentApp] -- rvlf_sp_GetStudentswithParentApp 6
	-- Add the parameters for the stored procedure here
	@bigOrganizationId				bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here	
	 SELECT * FROM (
	 SELECT  sm.StudentMasterID,sm.StudentID,sm.StudentFirstName +' ' + ISnull(sm.StudentMiddleName,'') +' ' + ISnull(sm.StudentLastName,'') as StudentName,
			 sm.RFID,sm.Grade,sm.AddressLine1,sm.ContactNo,sm.AlternateContactNo,sm.EmailAddress,
			 CASE  WHEN sm.Gender = 1 Then 'Male' ELSE 'Female' END AS 'GenderN',
			 CASE WHEN Sm.Active  = 1 THEN 'Active' ELSE 'InActive' END AS 'ActiveN',
			 (CASE WHEN SMSSettings = 0 THEN 'None' WHEN SMSSettings = 1 THEN 'Onward Trip' WHEN SMSSettings = 2 THEN 'Return Trip'
				  WHEN SMSSettings = 3 THEN 'Both' ELSE 'None' END) AS SMSSettings,
			 (CASE WHEN NotificationType = 0 THEN 'None' WHEN NotificationType = 1 THEN 'SMS' WHEN NotificationType = 2 THEN 'Email'
				  WHEN NotificationType = 3 THEN 'Both' ELSE 'None' END) AS NotificationType,
			 v.VehicleDescription,sm.LandmarkName,s.SchoolName,OG.GeozoneName
	 FROM rvlfStudentMaster sm
	 INNER JOIN rvlfSchoolMaster s ON s.SchoolID=sm.SchoolID
	 INNER JOIN rvlfParentMaster pm ON sm.ContactNo = pm.MobileNo and pm.DevRegID IS NOT NULL --and pm.DevOS = 'A'
	 LEFT OUTER JOIN rvlfStudentVehicleAssignment sva ON sm.StudentMasterID = sva.StudentMasterId 
	 LEFT OUTER JOIN rvlfVehicle v ON sva.VehicleId = v.VehicleId
	 LEFT OUTER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId = sm.GeozoneId and OG.OrganizationId = @bigOrganizationId 
	 WHERE sm.OrganizationID = @bigOrganizationId	 
	 UNION ALL
	 SELECT  sm.StudentMasterID,sm.StudentID,sm.StudentFirstName +' ' + ISnull(sm.StudentMiddleName,'') +' ' + ISnull(sm.StudentLastName,'') as StudentName,
			 sm.RFID,sm.Grade,sm.AddressLine1,sm.ContactNo,sm.AlternateContactNo,sm.EmailAddress,
			 CASE  WHEN sm.Gender = 1 Then 'Male' ELSE 'Female' END AS 'GenderN',
			 CASE WHEN Sm.Active  = 1 THEN 'Active' ELSE 'InActive' END AS 'ActiveN',
			 (CASE WHEN SMSSettings = 0 THEN 'None' WHEN SMSSettings = 1 THEN 'Onward Trip' WHEN SMSSettings = 2 THEN 'Return Trip'
				  WHEN SMSSettings = 3 THEN 'Both' ELSE 'None' END) AS SMSSettings,
			 (CASE WHEN NotificationType = 0 THEN 'None' WHEN NotificationType = 1 THEN 'SMS' WHEN NotificationType = 2 THEN 'Email'
				  WHEN NotificationType = 3 THEN 'Both' ELSE 'None' END) AS NotificationType,
			 v.VehicleDescription,sm.LandmarkName,s.SchoolName,OG.GeozoneName
	 FROM rvlfStudentMaster sm
	 INNER JOIN rvlfSchoolMaster s ON s.SchoolID=sm.SchoolID
	 INNER JOIN rvlfParentMaster pm1 ON sm.AlternateContactNo = pm1.MobileNo and pm1.DevRegID IS NOT NULL --and pm1.DevOS = 'A'	 
	 LEFT OUTER JOIN rvlfStudentVehicleAssignment sva ON sm.StudentMasterID = sva.StudentMasterId 
	 LEFT OUTER JOIN rvlfVehicle v ON sva.VehicleId = v.VehicleId
	 LEFT OUTER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId = sm.GeozoneId and OG.OrganizationId = @bigOrganizationId
	 WHERE sm.OrganizationID = @bigOrganizationId
	 ) PrntApp
	 Group By	PrntApp.StudentMasterID,PrntApp.StudentID,PrntApp.RFID,PrntApp.StudentName,PrntApp.Grade,PrntApp.AddressLine1,
				PrntApp.ContactNo,PrntApp.AlternateContactNo,PrntApp.EmailAddress,PrntApp.GEnderN,PrntApp.ActiveN,PrntApp.SMSSettings,
				PrntApp.NotificationType,PrntApp.VehicleDescription,PrntApp.LandmarkName,PrntApp.SchoolName,PrntApp.GeozoneName
				
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetSubProduct]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE proc [dbo].[rvlf_sp_GetSubProduct] 
(      
--@OrgID bigint ,    
@ProductId tinyint    
)      
as      
/******************************************************************************/                                              
-- Name  : rvlf_sp_GetSubProduct 
-- Description : Get Product and serial / boxid                                             
-- Author  : Gopal.R      
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--Created Date -19-jun-2014       
/******************************************************************************/        
begin      
select SubtypeId,SubTypeDesc  from rvlfmaksubproducts SP inner join rvlfVehicleType MP on SP.ProductId=MP.VehicleTypeId
 where --MD.OrganizationId=@OrgID  and    
(@ProductId is null or @ProductId ='' or SP.ProductId=@ProductId)  and SP.Isdelete=0  
    
end


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTemperatures]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetTemperatures]                  
 @bigFleetID bigint = null,                  
 @intBoxID varchar(max)=Null,                  
 @dtStartDate datetime = null,                   
 @dtEndDate datetime = null,                  
 @bigOrganizationID bigint = null,                  
 @bigQueryingUser bigint = 0,                   
 @vcBoxMsgTypeIDs varchar(max) = NULL                   
AS                  
/******************************************************************************/                  
-- Name  : rvlf_sp_GetTemperatures 407,'5240','23-Sep-2016 03:00:00 AM','23-Sep-2016 09:00:00 PM',212,303,NULL
-- Description : To get the temperature messages                  
--    :   Pass the valu 0 (Zero) to @bigQueryingUser if the user is angler admin                  
-- Author  : S. Jeyanthi.                  
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>>  Initial Reason                  
--          : 08-Oct-2010 Jeyanthi   Created Intial Version                   
--          : 03-Nov-2010 Jeyanthi - Modified  'Low Temp' to 'Low Temp1' and 'High Temp' to 'High Temp1'                    
--          : 13-Aug-2011 Ranjith Date formar Code included              
--   : 10-Feb-2011 Gopal.R Included Summary for temperature           
--   : 23-May-2014 Kapil Included @vcBoxMsgTypeIDs static values        
/******************************************************************************/                  
BEGIN                  
 Declare @dtFDate datetime =@dtStartDate                
 Declare @dtEDate datetime =@dtEndDate                
                 
DECLARE @HoursToBeAdded INT = 0                  
DECLARE @MinsToBeAdded INT = 0                  
DECLARE @DefaultDateFormat INT = 0                
                   
SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                
@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 = @bigQueryingUser                  
SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                  
SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))        
              
 if(@vcBoxMsgTypeIDs is null)       
 SET @vcBoxMsgTypeIDs ='106,107,10,29,24,5,9,1,2,3,12,152,169,174'         
    
      
if exists(Select OperationID from rvlfPackageOperations where PackageId in             
    (SELECT PackageId from rvlfOrganizationPackage             
    WHERE OrganizationID=@bigOrganizationID and IsActive=1) and OperationID in (396,397) )
	Begin
	SET @vcBoxMsgTypeIDs ='1' 
    END
                  
DECLARE @tbl Table                  
(                  
 BoxId bigint,BoxMsgInTypeId int,VehicleId bigint, VehicleDescription nvarchar(50),CustomProp varchar(max),Vin nvarchar(20),LicensePlate nvarchar(20),                  
 OriginDateTime DateTime,FleetId bigint,FleetName nvarchar(50),StreetAddress nvarchar(200),TemperatureDetails1 nvarchar(100),                  
 --TemperatureDetails2 nvarchar(100),Temperature1 numeric(7,2),Temperature2 numeric(7,2)    
  TemperatureDetails2 nvarchar(100),TemperatureDetails3 nvarchar(100),TemperatureDetails4 nvarchar(100),Temperature1 numeric(7,2),Temperature2 numeric(7,2) 
 ,Temperature3 numeric(7,2),Temperature4 numeric(7,2)                
)                  
              
 INSERT INTO @tbl                  
  SELECT BoxId,BoxMsgInTypeId,VehicleId,VehicleDescription,CustomProp,Vin,LicensePlate,OriginDateTime,FleetId,FleetName,StreetAddress,                  
  (CASE WHEN BoxMsgInTypeId IN (83,106) THEN             
  dbo.rvlf_fn_GetAlarmDetails_New(Customprop,BoxMsgInTypeID, BoxId, MessageInID, OriginDateTime,'LanguageEn')              
  WHEN Temperature1 IS NULL THEN 'NA' ELSE CAST(Temperature1 as nvarchar(50)) END) As TemperatureDetails1,                  
  (CASE WHEN BoxMsgInTypeId IN (87,107) THEN               
  dbo.rvlf_fn_GetAlarmDetails_New(Customprop,BoxMsgInTypeID, BoxId, MessageInID, OriginDateTime,'LanguageEn')               
  WHEN Temperature2 IS NULL THEN 'NA' ELSE CAST(Temperature2 as nvarchar(50)) END) As TemperatureDetails2,                  
  (CASE WHEN BoxMsgInTypeId IN (168,169) THEN               
  dbo.rvlf_fn_GetAlarmDetails_New(Customprop,BoxMsgInTypeID, BoxId, MessageInID, OriginDateTime,'LanguageEn')               
  WHEN Temperature3 IS NULL THEN 'NA' ELSE CAST(Temperature3 as nvarchar(50)) END) As TemperatureDetails3,                  
  (CASE WHEN BoxMsgInTypeId IN (173,174) THEN               
  dbo.rvlf_fn_GetAlarmDetails_New(Customprop,BoxMsgInTypeID, BoxId, MessageInID, OriginDateTime,'LanguageEn')               
  WHEN Temperature4 IS NULL THEN 'NA' ELSE CAST(Temperature4 as nvarchar(50)) END) As TemperatureDetails4,                  
  (CASE WHEN Temperature1 IS NOT NULL THEN CAST(SUBSTRING(Temperature1,CHARINDEX('=',Temperature1,1)+2,(Len(Temperature1)-CHARINDEX('=',Temperature1,1)+2)) AS Numeric(7,2))  END) AS Temperature1,                  
  (CASE WHEN Temperature2 IS NOT NULL THEN CAST(SUBSTRING(Temperature2,CHARINDEX('=',Temperature2,1)+2,(Len(Temperature2)-CHARINDEX('=',Temperature2,1)+2)) AS Numeric(7,2)) END) AS Temperature2,
  (CASE WHEN Temperature3 IS NOT NULL THEN CAST(SUBSTRING(Temperature3,CHARINDEX('=',Temperature3,1)+2,(Len(Temperature3)-CHARINDEX('=',Temperature3,1)+2)) AS Numeric(7,2)) END) AS Temperature3,
  (CASE WHEN Temperature4 IS NOT NULL THEN CAST(SUBSTRING(Temperature4,CHARINDEX('=',Temperature4,1)+2,(Len(Temperature4)-CHARINDEX('=',Temperature4,1)+2)) AS Numeric(7,2)) END) AS Temperature4                    
  FROM                  
  (SELECT h.BoxId,h.BoxMsgInTypeId,v.VehicleId, v.VehicleDescription,v.Vin, v.LicensePlate,DateAdd(n,@MinsToBeAdded,DateAdd(hh,
  @HoursToBeAdded,h.OriginDateTime)) OriginDateTime,                  
  F.FleetId,f.FleetName,h.CustomProp,h.MessageInID,                   
  CASE WHEN (h.LandMarkID IS NULL or h.LandMarkID = 0) THEN ISNULL(h.StreetAddress,'Address is not resolved')                   
  ELSE ISNULL(L.LandmarkName, ISNULL(h.StreetAddress,'Address is not resolved'))END as StreetAddress,                   
  CASE                 
 WHEN H.CustomProp LIKE '%Temperature Sensor-1 Value=Disconnected;%' THEN NULL                
 WHEN h.CustomProp like '%Temperature Sensor-1 Value=%' THEN dbo.rvlf_fn_GetTemperatureDetails(h.CustomProp,h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime,'Temp1') END As Temperature1,                  
  CASE                 
 WHEN H.CustomProp LIKE '%Temperature Sensor-2 Value=Disconnected;%' THEN NULL                
 WHEN h.CustomProp like '%Temperature Sensor-2 Value=%' THEN dbo.rvlf_fn_GetTemperatureDetails(h.CustomProp,h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime,'Temp2') END As Temperature2                  ,
 CASE                 
 WHEN H.CustomProp LIKE '%Temperature Sensor-3 Value=Disconnected;%' THEN NULL                
 WHEN h.CustomProp like '%Temperature Sensor-3 Value=%' THEN dbo.rvlf_fn_GetTemperatureDetails(h.CustomProp,h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime,'Temp3') END As Temperature3                  ,
 CASE                 
 WHEN H.CustomProp LIKE '%Temperature Sensor-4 Value=Disconnected;%' THEN NULL                
 WHEN h.CustomProp like '%Temperature Sensor-4 Value=%' THEN dbo.rvlf_fn_GetTemperatureDetails(h.CustomProp,h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime,'Temp4') END As Temperature4                  
  FROM rvlfMsgInHst h                  
  INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                  
  INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.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 va.VehicleId = v.VehicleId                  
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId                  
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId                   
  WHERE                  
  (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID)                  
  AND(@intBoxID  IS NULL OR @intBoxID='' OR @intBoxID='0' OR h.BoxId in (select FieldValue from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))                  
  AND ((@vcBoxMsgTypeIDs IS NULL) OR (@vcBoxMsgTypeIDs='') OR (h.BoxMsgInTypeId IN (SELECT * from dbo.rvlf_fn_ConvertArrayToTable(@vcBoxMsgTypeIDs,','))))                  
  AND(v.OrganizationId = @bigOrganizationID)                      
  AND((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)                   
  AND ((h.CustomProp like '%Temperature Sensor-1 Value=%') OR (h.CustomProp like '%Temperature Sensor-2 Value=%')OR
   (h.CustomProp like '%Temperature Sensor-3 Value=%')OR (h.CustomProp like '%Temperature Sensor-4 Value=%'))
  AND ((CustomProp NOT LIKE '%Temperature Sensor-1 Value=Disconnected;%'))                
  --AND  (CustomProp NOT LIKE '%Temperature Sensor-2 Value=Disconnected;%')      
  and h.BoxMsgInTypeId not in (12,83,87,168,173)                
  )                  
  A                   
                   
      select * into #tempTbl from  (select T.Boxid,(select COUNT(BoxMsgInTypeId) from @tbl where BoxId=T.BoxId and BoxMsgInTypeId=81 ) as Low1,                
 (select COUNT(BoxMsgInTypeId) from @tbl where BoxId=T.BoxId and BoxMsgInTypeId=82 ) as High1,                
 (select COUNT(BoxMsgInTypeId) from @tbl where BoxId=T.BoxId and BoxMsgInTypeId=83 ) as Disconnected1,              
 (select COUNT(BoxMsgInTypeId) from @tbl where BoxId=T.BoxId and BoxMsgInTypeId=85 ) as Low2,                
 (select COUNT(BoxMsgInTypeId) from @tbl where BoxId=T.BoxId and BoxMsgInTypeId=86 ) as High2,                
 (select COUNT(BoxMsgInTypeId) from @tbl where BoxId=T.BoxId and BoxMsgInTypeId=87 ) as Disconnected2,
 (select COUNT(BoxMsgInTypeId) from @tbl where BoxId=T.BoxId and BoxMsgInTypeId=165 ) as Low3,
 (select COUNT(BoxMsgInTypeId) from @tbl where BoxId=T.BoxId and BoxMsgInTypeId=166 ) as High3,
 (select COUNT(BoxMsgInTypeId) from @tbl where BoxId=T.BoxId and BoxMsgInTypeId=169 ) as Disconnected3,      
 (select COUNT(BoxMsgInTypeId) from @tbl where BoxId=T.BoxId and BoxMsgInTypeId=170 ) as Low4,      
 (select COUNT(BoxMsgInTypeId) from @tbl where BoxId=T.BoxId and BoxMsgInTypeId=171 ) as High4,      
 (select COUNT(BoxMsgInTypeId) from @tbl where BoxId=T.BoxId and BoxMsgInTypeId=174 ) as Disconnected4,                      
 (select MAX(Temperature1) from @tbl where BoxId=T.BoxId) as MaxTemp1,                
 (select Min(Temperature1) from @tbl where BoxId=T.BoxId) as MinTemp1,              
 (select MAX(Temperature2) from @tbl where BoxId=T.BoxId) as MaxTemp2,                
 (select Min(Temperature2) from @tbl where BoxId=T.BoxId) as MinTemp2 ,
 (select MAX(Temperature3) from @tbl where BoxId=T.BoxId) as MaxTemp3,      
 (select Min(Temperature3) from @tbl where BoxId=T.BoxId) as MinTemp3,  
 (select MAX(Temperature4) from @tbl where BoxId=T.BoxId) as MaxTemp4,      
 (select Min(Temperature4) from @tbl where BoxId=T.BoxId) as MinTemp4  
   from @tbl T group by BoxId) as a              
          
 SELECT T.BoxId ,t.BoxMsgInTypeId ,t.VehicleId , t.VehicleDescription ,t.Vin ,t.LicensePlate , t.CustomProp,                 
 t.OriginDateTime ,t.FleetId ,t.FleetName ,t.StreetAddress ,
 t.TemperatureDetails1 as TempDetails1, t.TemperatureDetails2 as TempDetails2,
 t.TemperatureDetails3 as TempDetails3, t.TemperatureDetails4 as TempDetails4,
 isnull(t.Temperature1,0) as Temperature1 ,isnull(t.Temperature2,0) as Temperature2 ,      
 isnull(t.Temperature3,0) as Temperature3 ,isnull(t.Temperature4,0) as Temperature4 ,      
 case when  @bigOrganizationID=209 then          
 case when t.Temperature1<>0 or t.Temperature1<>0.00 then cast(CAST(t.Temperature1 AS decimal(3,1))as varchar(50))+ '°C' else '0°C' end       
 else t.TemperatureDetails1 end      
 TemperatureDetails1,          
 case when  @bigOrganizationID=209 then       
 case when t.Temperature2<>0 or t.Temperature2<>0.00 then cast(CAST(t.Temperature2 AS decimal(3,1))as varchar(50))+ '°C' else '0°C' end      else t.TemperatureDetails2 end      
 TemperatureDetails2,     
 case when  @bigOrganizationID=209 then       
 case when t.Temperature3<>0 or t.Temperature3<>0.00 then cast(CAST(t.Temperature3 AS decimal(3,1))as varchar(50))+ '°C' else '0°C' end      else t.TemperatureDetails3 end      
 TemperatureDetails3, 
 case when  @bigOrganizationID=209 then       
 case when t.Temperature4<>0 or t.Temperature4<>0.00 then cast(CAST(t.Temperature4 AS decimal(3,1))as varchar(50))+ '°C' else '0°C' end      else t.TemperatureDetails4 end      
 TemperatureDetails4,        
 isnull(Tp.High1,0) as High1, isnull(Tp.Low1,0) as Low1 ,            
 --isnull(Tp.Disconnected1,0) as Disconnected1,            
 --(cast(isnull(Tp.MaxTemp1,0) as varchar(50))+ '°C') as MaxTemp1 ,             
 --(cast(isnull(Tp.MinTemp1,0) as varchar(50))+ '°C') as MinTemp1 ,    
 (cast(isnull(Tp.MaxTemp1,0) as varchar(50))) as MaxTemp1 ,            
 (cast(isnull(Tp.MinTemp1,0) as varchar(50))) as MinTemp1 ,            
 isnull(Tp.High2,0) as High2 ,  isnull(Tp.Low2,0) as Low2 ,            
 --isnull(Tp.Disconnected2,0) as Disconnected2 ,            
 --(cast(isnull(Tp.MaxTemp2,0) as varchar(50))+ '°C') as MaxTemp2 ,            
 --(cast(isnull(Tp.MinTemp2,0) as varchar(50))+ '°C') as MinTemp2 ,     
  (cast(isnull(Tp.MaxTemp2,0) as varchar(50))) as MaxTemp2 ,            
 (cast(isnull(Tp.MinTemp2,0) as varchar(50))) as MinTemp2 ,            
 isnull(Tp.High3,0) as High3 ,  isnull(Tp.Low3,0) as Low3 ,   
 (cast(isnull(Tp.MaxTemp3,0) as varchar(50))) as MaxTemp3 ,            
 (cast(isnull(Tp.MinTemp3,0) as varchar(50))) as MinTemp3 ,            
 isnull(Tp.High4,0) as High4 ,  isnull(Tp.Low2,0) as Low4 ,   
 (cast(isnull(Tp.MaxTemp4,0) as varchar(50))) as MaxTemp4 ,            
 (cast(isnull(Tp.MinTemp4,0) as varchar(50))) as MinTemp4 ,            
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,
 @DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                
 PasGenerateddate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())                
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate        
 


  
         
 from @tbl as T left join #temptbl as Tp on T.BoxId=Tp.Boxid where T.BoxMsgInTypeId not in (12,83,87,168,173) Order By OriginDateTime desc  
                              
 SELECT CASE WHEN (ABS(CAST((BINARY_CHECKSUM(*) *  RAND()) as int))%100) < 5 THEN 1 ELSE 1 END AS IsCheck, temp.* FROM              
 (SELECT distinct VehicleId,VehicleDescription,Convert(varchar,OriginDateTime,@DefaultDateFormat) as  OriginDateTime,OriginDateTime AS 'OriginDateTimeSort',                
 isnull(Min(Temperature1),0) MinTemperature1,isnull(Max(Temperature1),0) MaxTemperature1,  
 isnull(Min(Temperature2),0) MinTemperature2,isnull(Max(Temperature2),0) MaxTemperature2 ,                
 isnull(Min(Temperature3),0) MinTemperature3,isnull(Max(Temperature3),0) MaxTemperature3 ,        
 isnull(Min(Temperature4),0) MinTemperature4,isnull(Max(Temperature4),0) MaxTemperature4 ,                
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,
 @DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                
 PasGenerateddate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())                
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate  
 FROM  @tbl  where BoxMsgInTypeId not in (12,83,87,168,173) GROUP BY VehicleId, VehicleDescription,Convert(varchar,OriginDateTime,
 @DefaultDateFormat),OriginDateTime) temp                
 Order By temp.VehicleDescription,temp.OriginDateTimeSort ASC              
                   
 Select OperationID OperationTypeID from rvlfPackageOperations where PackageId in                   
    (SELECT PackageId from rvlfOrganizationPackage                   
    WHERE OrganizationID=@bigOrganizationID and IsActive=1)                  
                   
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTemperatures_New]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetTemperatures_New]  
 @bigOrganizationID bigint = null,  
 @bigFleetID bigint = null,  
 @bigVehicleId int = null,  
 @dtStartDate datetime = null,  
 @dtEndDate datetime = null,  
 @tiBoxMsgInType tinyint = null,   
 @bigQueryingUser bigint = 0,  
 @intBoxID int=Null,  
 @cReportType char(1) =NULL   
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetTemperatures_New 40,61,null,'11/27/2010 08:00:00 AM','11/27/2010 20:00:00 PM',78,17,166,'B'  
-- Description : To get the temperature messages  
--    :   Pass the valu 0 (Zero) to @bigQueryingUser if the user is angler admin  
-- Author  : S. Jeyanthi.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>>  Initial Reason  
--    : 08-Oct-2010 Jeyanthi   Created Intial Version   
--    :   03-Nov-2010 Jeyanthi - Modified  'Low Temp' to 'Low Temp1' and 'High Temp' to 'High Temp1'    
/******************************************************************************/  
BEGIN  
DECLARE @HoursToBeAdded INT = 0  
DECLARE @MinsToBeAdded INT = 0  
  
SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded   
FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz  
ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser  
SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))  
SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))  
  
  
SET @tiBoxMsgInType=78  
  
DECLARE @bigLowTemperature1 Decimal(18,2) --= 25  
DECLARE @bigHighTemperature1 Decimal(18,2) --= 35  
  
DECLARE @bigLowTemperature2 Decimal(18,2) --= 25  
DECLARE @bigHighTemperature2 Decimal(18,2) --= 35  
  
   SELECT Top 1 @bigLowTemperature1 = CASE WHEN CustomProp Like '%Low Temp1=%' THEN   
          CAST(SUBSTRING(CustomProp,CHARINDEX('Low Temp1=',CustomProp,1)+10,CHARINDEX(';',CustomProp,CHARINDEX('Low Temp1=',CustomProp,1)) - (CHARINDEX('Low Temp1=',CustomProp,1)+10))as Decimal(18,2))END,  
    @bigLowTemperature2 = CASE WHEN CustomProp Like '%Low Temp2=%' THEN   
          CAST(SUBSTRING(CustomProp,CHARINDEX('Low Temp2=',CustomProp,1)+10,CHARINDEX(';',CustomProp,CHARINDEX('Low Temp2=',CustomProp,1)) - (CHARINDEX('Low Temp2=',CustomProp,1)+10))as Decimal(18,2))END,  
   @bigHighTemperature1 = CASE WHEN CustomProp Like '%High Temp1=%' THEN    
        CAST(SUBSTRING (CustomProp,CHARINDEX('High Temp1=',CustomProp,1)+11,  
           CHARINDEX('|',CustomProp,CHARINDEX('High Temp1=',CustomProp,1)) - (CHARINDEX('High Temp1=',CustomProp,1)+11)) as Decimal(18,2))END,  
   @bigHighTemperature2 = CASE WHEN CustomProp Like '%High Temp2=%' THEN    
        CAST(SUBSTRING (CustomProp,CHARINDEX('High Temp2=',CustomProp,1)+11,  
           CHARINDEX('|',CustomProp,CHARINDEX('High Temp2=',CustomProp,1)) - (CHARINDEX('High Temp2=',CustomProp,1)+11)) as Decimal(18,2))END   
  FROM rvlfMsgInHst h  
  INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
  INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId   
  LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId   
  WHERE h.BoxMsgInTypeId=74 AND  
  (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID)   
  AND(@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID)   
  AND(@intBoxID  IS NULL OR @intBoxID='' OR h.BoxId = @intBoxID)   
  AND((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)   
  order by OriginDateTime Desc  
  
 --SELECT @bigLowTemperature,@bigHighTemperature  
  
 SELECT BoxId,BoxMsgInTypeId,VehicleId,VehicleDescription,Vin,LicensePlate,OriginDateTime,FleetId,FleetName,StreetAddress,  
 --CASE WHEN Temperature1 >= @bigHighTemperature THEN REPLACE(REPLACE(MessageDetails,'Current Temp1','Temperatue High'),'degree Celsius','°C')   
 --WHEN Temperature1 <= @bigLowTemperature THEN REPLACE(REPLACE(MessageDetails,'Current Temp1','Temperatue Low'),'degree Celsius','°C')END TemperatureDetails1,  
 CASE WHEN Temperature1 >= @bigHighTemperature1 THEN 'Temperatue = ' + CAST(Temperature1 as nvarchar) + '°C'   
 WHEN Temperature1 <= @bigLowTemperature1 THEN  'Temperatue = ' + CAST(Temperature1 as nvarchar) + '°C' END TemperatureDetails1,   
 --CASE WHEN Temperature2 >= @bigHighTemperature THEN REPLACE(REPLACE(MessageDetails,'Current Temp1','Temperatue High'),'degree Celsius','°C')   
 --WHEN Temperature2 <= @bigLowTemperature THEN REPLACE(REPLACE(MessageDetails,'Current Temp1','Temperatue Low'),'degree Celsius','°C')END TemperatureDetails2,  
 CASE WHEN Temperature2 >= @bigHighTemperature2 THEN 'Temperatue = ' + CAST(Temperature2 as nvarchar) + '°C'   
 WHEN Temperature2 <= @bigLowTemperature2 THEN  'Temperatue = ' + CAST(Temperature2 as nvarchar) + '°C' END TemperatureDetails2,   
 Temperature1, Temperature2 FROM (SELECT h.BoxId,h.BoxMsgInTypeId,v.VehicleId, v.VehicleDescription,v.Vin, v.LicensePlate,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime))OriginDateTime,   
 F.FleetId,f.FleetName,   
 CASE WHEN (h.LandMarkID IS NULL or h.LandMarkID = 0) THEN ISNULL(h.StreetAddress,'Address is not resolved')   
 ELSE ISNULL(L.LandmarkName, ISNULL(h.StreetAddress,'Address is not resolved'))END as StreetAddress,   
 dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime) as MessageDetails,  
 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 Decimal(18,2)) END As Temperature1,  
 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 Decimal(18,2)) END As Temperature2  
 FROM rvlfMsgInHst h   
 INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
 INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.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 va.VehicleId = v.VehicleId  
 INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
 INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId   
 WHERE  
 (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID)   
 --AND (@tiBoxMsgInType IS NULL OR h.BoxMsgInTypeId = @tiBoxMsgInType)  
 AND(@bigVehicleId IS NULL OR @bigVehicleId='' OR v.VehicleId = @bigVehicleId)   
 AND(@intBoxID  IS NULL OR @intBoxID='' OR h.BoxId = @intBoxID)   
 AND((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)   
 AND ((h.CustomProp like '%Temperature Sensor-1 Value=%') OR (h.CustomProp like '%Temperature Sensor-2 Value=%'))   
 )A   
 WHERE (Temperature1 =   
 ((CASE WHEN @cReportType='B' THEN (CASE WHEN Temperature1 >= @bigHighTemperature1 OR Temperature1<= @bigLowTemperature1 THEN Temperature1 END)   
 WHEN @cReportType='H' THEN (CASE WHEN Temperature1 >= @bigHighTemperature1 THEN Temperature1 END)  
 WHEN @cReportType='L' THEN (CASE WHEN Temperature1 <= @bigLowTemperature1 THEN Temperature1 END)END))   
 OR  
 Temperature2 = ((CASE WHEN @cReportType='B' THEN (CASE WHEN Temperature2 >= @bigHighTemperature2 OR Temperature2<= @bigLowTemperature2 THEN Temperature2 END)   
 WHEN @cReportType='H' THEN (CASE WHEN Temperature2 >= @bigHighTemperature2 THEN Temperature2 END)  
 WHEN @cReportType='L' THEN (CASE WHEN Temperature2 <= @bigLowTemperature2 THEN Temperature2 END)END)))  
  
  
  
 DECLARE @Tbl Table(VehicleId bigint,VehicleDescription nvarchar(50),OriginDateTime Date,MinTemperature1 decimal(18,2),MaxTemperature1 decimal(18,2),MinTemperature2 decimal(18,2),MaxTemperature2 decimal(18,2))  
  
 INSERT INTO @Tbl (VehicleId,VehicleDescription,OriginDateTime,MinTemperature1,MaxTemperature1,MinTemperature2,MaxTemperature2)   
 SELECT distinct vehicleId,VehicleDescription,Convert(Date,OriginDateTime) OriginDateTime,Min(Temperature1),Max(Temperature1),Min(Temperature2),Max(Temperature2)  
 FROM (SELECT v.VehicleId, v.VehicleDescription,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime))OriginDateTime,  
 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 Decimal(18,2)) END As Temperature1,  
 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 Decimal(18,2)) END As Temperature2  
 FROM rvlfMsgInHst h   
 INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
 INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.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 va.VehicleId = v.VehicleId  
 INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
 INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
 WHERE  
 (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID)   
 --AND (@tiBoxMsgInType IS NULL OR h.BoxMsgInTypeId = @tiBoxMsgInType)  
 AND(@bigVehicleId IS NULL OR @bigVehicleId='' OR v.VehicleId = @bigVehicleId)   
 AND(@intBoxID  IS NULL OR @intBoxID='' OR h.BoxId = @intBoxID)   
 AND((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)   
 AND ((h.CustomProp like '%Temperature Sensor-1 Value=%') OR (h.CustomProp like '%Temperature Sensor-2 Value=%'))  
  
 )A   
 WHERE (Temperature1 =   
 ((CASE WHEN @cReportType='B' THEN (CASE WHEN Temperature1 >= @bigHighTemperature1 OR Temperature1<= @bigLowTemperature1 THEN Temperature1 END)   
 WHEN @cReportType='H' THEN (CASE WHEN Temperature1 >= @bigHighTemperature1 THEN Temperature1 END)  
 WHEN @cReportType='L' THEN (CASE WHEN Temperature1 <= @bigLowTemperature1 THEN Temperature1 END)END))   
 OR  
 Temperature2 = ((CASE WHEN @cReportType='B' THEN (CASE WHEN Temperature2 >= @bigHighTemperature2 OR Temperature2<= @bigLowTemperature2 THEN Temperature2 END)   
 WHEN @cReportType='H' THEN (CASE WHEN Temperature2 >= @bigHighTemperature2 THEN Temperature2 END)  
 WHEN @cReportType='L' THEN (CASE WHEN Temperature2 <= @bigLowTemperature2 THEN Temperature2 END)END)))  
 GROUP BY VehicleId, VehicleDescription,Convert(Date,OriginDateTime)  
  
 SELECT * from @Tbl order by VehicleId   
END  
  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTempUserVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetTempUserVehicles]            
	@bigFleetID		bigint	=	null,            
	@bigOrganizationID	bigint	=	null,            
	@bitIsAssigned		bit		=	0,            
	@VehDescPrefix		nVarchar(50) = null,        
	@bigQueryingUser	bigint	=	null              
AS           
/******************************************************************************/            
-- Name  :	rvlf_sp_GetTempUserVehicles 8,6,0,null,219
--			rvlf_sp_GetTempUserVehicles 8,6,1,null,219
-- Description : To get assinged and unassinged vehicles            
-- Author  : N.Ranjith
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--    : 21-Jul-2016 N.Ranjith Created Intial Version             
/******************************************************************************/            
BEGIN            
 SET NOCOUNT ON             
  declare @Lang varchar(50)             
  select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser          
             
 IF @bitIsAssigned = 0             
 BEGIN

	SELECT	v.VehicleId,  v.VehicleDescription  as VehicleDescription,
			m.ModelName, k.MakeName, v.Color,v.ModelYear, t.VehicleTypeName, v.Vin, v.ModelId, v.MakeId, v.VehicleTypeId, v.VehicleDescription as VehicleName, 
			v.Location, v.DisplayName, (select count(*) from rvlfVehicleTempUserAssignment where v.VehicleId in (SELECT * FROM rvlf_fn_ConvertArrayToTable(VehicleID,','))  and isAssign = 0 ) as UserAssignedCount             
	FROM	rvlfVehicle v             
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId       
   INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId      
   LEFT OUTER JOIN rvlfModel m ON v.ModelId = m.ModelId      
   LEFT OUTER JOIN rvlfMake k ON v.MakeId = k.MakeId      
   LEFT OUTER JOIN rvlfVehicleType t ON v.VehicleTypeId = t.VehicleTypeId      
  WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR f.OrganizationId = @bigOrganizationID)      
      AND (@VehDescPrefix IS NULL OR @VehDescPrefix='' OR v.VehicleDescription LIKE @VehDescPrefix + '%')      
   AND f.IsDefault = 1 AND v.VehicleId IN      
    ( SELECT rfv.VehicleId FROM rvlfFleetVehicles rfv WHERE FleetId = @bigFleetID)      
  ORDER BY v.VehicleDescription asc      
              
 END                   
 ELSE            
 BEGIN            
	
	-- SELECT the vehicles assinged to the Vendor            
	--SELECT	ROW_NUMBER () over (order by v.vehicledescription asc) as SlNo, v.VehicleId,va.BoxId,vvs.TAutoTokenID, 
	--	 	(case when @Lang='LanguageArNew' then isnull(v.VehicleDescription_Ar,v.VehicleDescription) else v.VehicleDescription end) as VehicleDescription,            
	--		m.ModelName, k.MakeName, v.Color,v.ModelYear, t.VehicleTypeName, v.Vin, v.ModelId, v.MakeId, v.VehicleTypeId, v.VehicleDescription as VehicleName,
	--		v.Location, v.DisplayName,vvs.TokenId,vvs.Email, convert(varchar(50),vvs.ExpiresFrom,106) + ' - ' + convert(varchar(50),vvs.ExpiresTo,106)as ContractTo,			
	--		vvs.TokenID,vvs.MobileNo,u.UserName as CreatedBy,vvs.CreatedDatetime,	vvs.Remarks,vvs.DeletedBy,vvs.DeletedBy,vvs.UnAssignedBy,
 --           vvs.UnAssignedDateTime,vvs.UnAssignedRemarks,vvs.DeletedDateTime,
	--		CEILING(convert(DECIMAL(5, 2), DATEDIFF(dd,vvs.ExpiresFrom,getutcdate()))/ convert(DECIMAL(5, 2), DATEDIFF(dd,vvs.ExpiresFrom,vvs.ExpiresTo))*100) as ContractStatus,
	--		(case when vvs.ExpiresTo <= getutcdate() then 1 else 0 end) as ExpireStatus
	Select 
	distinct vvs.TAutoTokenID, vvs.VehicleId,VehicleDescription = 
    STUFF((SELECT ', ' + VehicleDescription
           FROM rvlfVehicle b 
           WHERE b.VehicleID in (SELECT * FROM rvlf_fn_ConvertArrayToTable(vvs.VehicleID,','))  FOR XML PATH('')), 1, 2, ''),	
			vvs.TokenId,vvs.Email, convert(varchar(50),vvs.ExpiresFrom,106) + ' - ' + convert(varchar(50),vvs.ExpiresTo,106)as ContractTo,			
			vvs.MobileNo,u.UserName as CreatedBy,vvs.CreatedDatetime,	vvs.Remarks,vvs.DeletedBy,vvs.DeletedBy,vvs.UnAssignedBy,
            vvs.UnAssignedDateTime,vvs.UnAssignedRemarks,vvs.DeletedDateTime,
			--CEILING(convert(DECIMAL(5, 2), DATEDIFF(dd,vvs.ExpiresFrom,getutcdate()))/ convert(DECIMAL(5, 2), DATEDIFF(dd,vvs.ExpiresFrom,vvs.ExpiresTo))*100) as ContractStatus,
			(Case when Convert(date,getutcdate()) = Convert(date,vvs.ExpiresTo) then 100		
			else 
			CEILING(convert(DECIMAL(5, 2), DATEDIFF(dd,vvs.ExpiresFrom,getutcdate()))/ convert(DECIMAL(5, 2), DATEDIFF(dd,vvs.ExpiresFrom,vvs.ExpiresTo))*100) end) as ContractStatus,
			(case when convert(date,vvs.ExpiresTo) < convert(date, getutcdate())   then 1 else 0 end) as ExpireStatus
	FROM	rvlfVehicle v     
	inner join rvlfVehicleAssignment va on va.VehicleId =v.VehicleId        		
	INNER	JOIN rvlfVehicleTempUserAssignment vvs on v.VehicleID   in (SELECT * FROM rvlf_fn_ConvertArrayToTable(vvs.VehicleID,','))    
	--vvs.VehicleID =v.VehicleID                
	inner join rvlfUser u on u.UserId = vvs.CreatedBy
	LEFT	OUTER JOIN rvlfModel m ON v.ModelId = m.ModelId            
	LEFT	OUTER JOIN rvlfMake k ON v.MakeId = k.MakeId            
	LEFT	OUTER JOIN rvlfVehicleType t ON v.VehicleTypeId = t.VehicleTypeId            
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)            
	AND		(@VehDescPrefix IS NULL OR @VehDescPrefix='' OR v.VehicleDescription LIKE @VehDescPrefix + '%') and VVS.isDelete = 0  
	AND     vvs.isAssign = 0 and convert(date,vvs.ExpiresTo) >= convert(date, getutcdate())        	
	ORDER	BY vvs.TAutoTokenID asc            

 END            
             
 SET NOCOUNT OFF            
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTipsDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetTipsDetails]  
(  
  @bigOrganizationId bigint=null,  
  @bigTipsId bigint=null    
)  
AS  
/****************************************************************************************/  
-- Name    : rvlf_sp_GetTipsDetails 6,1  
-- Description   : To get the Tips details  
-- Author    : Jeyanthi.S  
-- Created Date  : 21-Oct-2010  
--  Modified Date :  
/***************************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
 SELECT NewsId As 'TipsId', NewsName As 'TipsName', NewsDescription As 'TipsDescription'  
 FROM rvlfNews WHERE --(@bigOrganizationId IS NULL OR OrganizationID=@bigOrganizationId) AND     
   (@bigTipsId IS NULL OR @bigTipsId='' OR NewsId=@bigTipsId) AND  
   [Type] = 'Tips'  
 ORDER BY NewsId desc   
 SET NOCOUNT OFF  
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTransitMixerDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetTransitMixerDetails]      
 @bigFleetID bigint = null,      
 @intBoxID int = null,      
 @dtStartDate datetime = null,      
 @dtEndDate datetime = null,    
 @bigOrganizationID bigint = null,      
 @bigQueryingUser bigint = 0      
AS      
/******************************************************************************/      
-- Name        : rvlf_sp_GetTransitMixerDetails 72,Null, '2009-11-01 08:00:00:00', '2010-12-10 08:00:00', 49,62      
-- Description : To get Door Sensor details to display in Report      
-- Author      : S. Jeyanthi      
-- Company     : Angler Technologies      
-- History     : <<Date(dd-MON-yyyy)>> Initial Reason      
--             : 19-Aug-2010       
--             : 16-Aug-2011 Ranjith Date Format Included
/******************************************************************************/      
BEGIN      
      
SET NOCOUNT ON   
 Declare @dtFDate datetime =@dtStartDate
 Declare @dtEDate datetime =@dtEndDate     
 IF @bigFleetID IS NULL      
  BEGIN      
   SELECT @bigFleetID=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)  
  DECLARE @DefaultDateFormat INT = 0
      
    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,
     @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 = @bigQueryingUser      
       
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))      
       
 DECLARE @tblTripDetailsForTD TABLE(      
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,      
  [BoxId] [int] NOT NULL,      
  [StartDate] [datetime] NOT NULL,      
  [EndDate] [datetime] NULL,      
  [StartAddress] varchar(300) NULL  
 )      
      
 DECLARE @intDuration int      
 DECLARE @dtOriginDateTime datetime      
 DECLARE @bigOdoMeterReading int      
 DECLARE @bitDoorStatus bit      
 DECLARE @vcStreetAddress varchar(250)      
 DECLARE @tiBoxMsgInTypeId tinyint  
 DECLARE @bigTripID bigint      
 DECLARE @intIterator int      
 DECLARE @canShowFuelMessage bit = 0     
     
      
 IF EXISTS (SELECT * FROM rvlfPackageOperations r      
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId      
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId      
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)      
   BEGIN      
    SET @canShowFuelMessage = 1      
   END      
      
 DECLARE  @tblMessageForProcessingTrip TABLE(      
  [ProcessorID] [bigint] identity(1,1) NOT NULL,    
  [Boxid] [int] NOT NULL,      
  [OriginDateTime] [datetime] NOT NULL,      
  [BoxMsgInTypeId] [tinyint] NULL,    
  [IgnitionStatus] [bit] NULL,      
  [StreetAddress] [varchar](250) NOT NULL,  
  [SensorMask] varchar(250) NULL,      
  [TripId] [bigint] NULL,      
  [Duration] [int] NULL,      
  [SensorNo] [tinyint] NULL      
        
 )      
       
 DECLARE @tblBoxes TABLE (BoxID int)      
        
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId  
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or BoxId = @intBoxID) AND V.OrganizationId=@bigOrganizationID  
   ORDER BY BoxId      
       
 DECLARE @intBoxLooping int   
        
   SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes      
   WHILE @intBoxLooping IS NOT NULL      
   BEGIN   
  DECLARE @DTFIRST DATETIME=NULL,@DTEND DATETIME=NULL  
    --FIND THE FIRST IGNITION ON TIME BETWEEN THE FROM AND TO TIME  
   SELECT TOP 1 @DTFIRST=OriginDateTime FROM rvlfMsgInHst WHERE Boxid=@intBoxLooping AND BoxMsgInTypeId = 2 AND   
        OriginDateTime BETWEEN @dtStartDate and @dtEndDate AND CAST(SUBSTRING(CustomProp ,CHARINDEX('=',CustomProp)+1,      
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint)=2 ORDER BY OriginDateTime asc      
   SELECT TOP 1 @DTEND=OriginDateTime FROM rvlfMsgInHst WHERE Boxid=@intBoxLooping AND BoxMsgInTypeId=3 AND   
        OriginDateTime BETWEEN @dtStartDate and @dtEndDate AND CAST(SUBSTRING(CustomProp ,CHARINDEX('=',CustomProp)+1,      
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint)=2      
        ORDER BY OriginDateTime desc         
    
  INSERT INTO @tblMessageForProcessingTrip (      
   Boxid, OriginDateTime, BoxMsgInTypeId,       
   IgnitionStatus, StreetAddress,              
   SensorMask, Duration, SensorNo)      
    SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,     
     CAST( SUBSTRING(h.sensormask,8,1) as bit) as IgnitionStatus,             
   CASE WHEN (h.LandMarkID IS NULL or h.LandMarkID = 0) THEN ISNULL(h.StreetAddress,'Address is not resolved')   
     ELSE ISNULL(L.LandmarkName, ISNULL(h.StreetAddress,'Address is not resolved'))END as StreetAddress,  
   Case WHEN h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc       
   WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +      
    CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +      
    dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'      
   ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID,       
   h.OriginDateTime, @canShowFuelMessage)END,       
     CASE WHEN h.BoxMsgInTypeID = 9 THEN       
   CAST(dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeID, h.BoxId,0) as int) ELSE 0 END,      
     CASE WHEN h.BoxMsgInTypeId = 2 THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,      
   CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END      
   from rvlfMsgInHst h       
    INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId      
    INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId      
    INNER JOIN rvlfFleetVehicles fv ON va.VehicleId = fv.VehicleId      
    INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId      
    INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
    LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID       
   WHERE h.BoxMsgInTypeId in(2,3) AND CAST(SUBSTRING(CustomProp ,CHARINDEX('=',CustomProp)+1,      
   CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint)=2       
   AND 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 ( @bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID)                
     AND h.OriginDateTime between @DTFIRST and @DTEND               
     AND h.BoxID = @intBoxLooping      
    order by h.origindatetime asc, h.MessageInID asc       
                
  SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes WHERE BoxID < @intBoxLooping      
   END      
      
      
  SELECT @intIterator = MIN(ProcessorID) FROM @tblMessageForProcessingTrip       
        
  WHILE @intIterator IS NOT NULL      
  BEGIN      
   SET @intBoxID = NULL; SET @dtOriginDateTime = NULL; SET @tiBoxMsgInTypeId = NULL;      
   SET @vcStreetAddress = NULL; SET @intDuration = NULL;    
   SET @intDuration = NULL;    
    
   DECLARE @dtNextStartTime datetime=null;   
   DECLARE @bitIsTripClosed bit=0;  
     
   SELECT  @intBoxID = Boxid, @dtOriginDateTime = OriginDateTime,      
     @tiBoxMsgInTypeId = BoxMsgInTypeId,       
     @vcStreetAddress = StreetAddress,       
     @intDuration = Duration  
   FROM @tblMessageForProcessingTrip WHERE ProcessorID=@intIterator and  TripId is NULL   
        
 IF( @tiBoxMsgInTypeId=2)  
    BEGIN  
     DECLARE @DTENDTIME DATETIME=NULL  
    --NEXT IGNITION TIME       
     SELECT TOP 1 @dtNextStartTime=OriginDateTime,@bitIsTripClosed=1 FROM @tblMessageForProcessingTrip   
      WHERE BoxMsgInTypeId=2 AND Boxid =@intBoxID AND OriginDateTime>@dtOriginDateTime   
      
     IF(@dtNextStartTime IS NOT NULL)       
      BEGIN       
       SELECT TOP 1 @DTENDTIME=OriginDateTime,@bitIsTripClosed=1           
        FROM @tblMessageForProcessingTrip   
        WHERE BoxMsgInTypeId=3 AND Boxid =@intBoxID AND OriginDateTime >= @dtOriginDateTime   
         AND OriginDateTime < @dtNextStartTime  
      END  
     ELSE  
      BEGIN        
       SELECT TOP 1 @DTENDTIME=OriginDateTime,@bitIsTripClosed=1  
        FROM @tblMessageForProcessingTrip   
        WHERE BoxMsgInTypeId=3 AND Boxid =@intBoxID AND OriginDateTime > @dtOriginDateTime  
          
      END  
     
     
    INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress)    
     VALUES(@intBoxID,@dtOriginDateTime,@DTENDTIME, @vcStreetAddress)   
         
     
                      
    SET @bigTripID=@@IDENTITY   
    END   
    UPDATE @tblMessageForProcessingTrip SET TripId = @bigTripID where Boxid=@intBoxID AND OriginDateTime>=@dtOriginDateTime AND OriginDateTime<=@DTENDTIME   
     
    SELECT @intIterator = MIN(ProcessorID) FROM @tblMessageForProcessingTrip WHERE ProcessorID > @intIterator and TripId is NULL   
     
   END  
  
      
  SELECT t.TripId,t.BoxId, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)) as 'StartDate',      
     DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as 'EndDate',    
     dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,StartDate,EndDate)) as Duration,      
     ABS(DateDiff(SS,StartDate,EndDate)) as TripDuration,   
     (Select top 1 dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,StartDate,EndDate)) from @tblTripDetailsForTD tt order by ABS(DateDiff(SS,StartDate,EndDate)) Desc) MaxDuration,      
     (Select top 1 dbo.rvlf_fn_getTimeFromSeconds(ISNULL(DateDiff(SS,StartDate,EndDate),0)) from @tblTripDetailsForTD tt order by ABS(DateDiff(SS,StartDate,EndDate)) Asc) MinDuration,          
      StartAddress, Vin, LicensePlate, VehicleDescription, MakeName, ModelName,ModelYear,
      Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,
       PasGenerateddate =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())
      --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate   
      
   FROM @tblTripDetailsForTD t     
   INNER JOIN rvlfVehicleAssignment va ON t.BoxId = va.BoxId      
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId      
   LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId      
   LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId   
   Where StartDate IS NOT NULL and EndDate IS NOt Null  
   Order by TripId   
 SET NOCOUNT OFF    
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTripDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetTripDetails]      
 @bigFleetID bigint = null,      
 @intBoxID int = null,      
 --@bigTripID tinyint = null,      
 @dtStartDate DateTime = null,      
 @dtEndDate DateTime = null,      
 @bitTripStatus bit = 1,      
 @bigOrganizationID bigint = null,      
 @bigQueryingUser bigint = 0      
AS      
/******************************************************************************/      
-- Name  : rvlf_sp_GetTripDetails 39,54, '2011-03-29 08:00:00', '2011-03-29 12:00:00',null, 36,62      
-- Description : To get the trip details i.e messages got within a trip      
--    :   Pass the valu 0 (Zero) to @bigQueryingUser if the user is angler admin      
-- Author  : M. Jebamalai Jaya Chitra.      
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--    : 28-May-2009 MJJC Created Intial Version       
--    : Updated by Narayanasamy on 3-Nov-09 for convert date as GMT format      
--    : 11-Dec-2009 MJJC Included the message restrictions      
--    : 25-Jan-2010 MJJC Changed the alarm details function, gets all the sns mask info from it.      
--           Message restriction based on the organization and not on user.      
--    : 29-Jan-2010 MJJC Got the organization ID based on the user      
--    : 02-Feb-2010 MJJC Changed getting of msg details for send geozone IDs      
--    : 26-Apr-2010 MJJC Done the related change for shoing speed with violation      
--    : 28-Jun-2010 MJJC Dynamic trip generation      
--    : 06-Jul-2010 MJJC Included the complete trip on start and ongoing trip too.      
--    : 05-Aug-2010 SJ  Retrieved Odometer Values    
--    : 02-Feb-2011 TSK Included NOLOCK condition to avoid deadlock   
--    : 04-Feb-2011 TSK Modified to show Landmark Name instead of StreetAddress    
/******************************************************************************/      
BEGIN      
      
SET NOCOUNT ON      
 --IF @bigOrganizationID IS NULL      
 -- BEGIN      
 --  SELECT @bigOrganizationID = OrganizationID from rvlfUser where UserId = @bigQueryingUser      
 -- END      
        
 IF @bigFleetID IS NULL      
  BEGIN      
   SELECT @bigFleetID=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 '(in Miles)' ELSE '(in Kms)' END,      
     --@SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(in MPH)' ELSE '(in KMPH)' 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 = @bigQueryingUser      
       
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))      
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))      
       
 CREATE TABLE #tblTripDetailsForTD(      
  [TripId] [bigint] NOT NULL,      
  [BoxId] [int] NOT NULL,      
  [StartDate] [datetime] NOT NULL,      
  [EndDate] [datetime] NULL,      
  [OdometerStart] [bigint] NOT NULL,      
  [OdometerEnd] [bigint] NULL,      
  [IsTripClosed] [bit] NULL,      
  [IdlingDuration] [int] NULL,      
  [StopTime] [int] NULL,      
  [StartAddress] nvarchar(300) NULL,      
  [EndAddress] nvarchar(300) NULL,      
  [VIN] [varchar](20) NULL,      
  [LicensePlate] [varchar](20) NULL,      
  [VehDispName] [varchar](50) NULL,      
  [MakeName] [varchar](200) NULL,      
  [ModelName] [varchar](200) NULL,    
  [ModelYear] [smallint] null      
 )      
      
 DECLARE @intDuration int      
 DECLARE @dtOriginDateTime datetime      
 DECLARE @bigOdoMeterReading int      
 DECLARE @bitIgnitionStatus bit      
 DECLARE @vcStreetAddress nvarchar(250)      
 DECLARE @tiBoxMsgInTypeId tinyint      
 DECLARE @lastIdlingDuration int       
 DECLARE @lastIdlingTime DateTime      
 DECLARE @tiSensorNo tinyint      
 DECLARE @bigTripID bigint      
 DECLARE @intIterator int      
 DECLARE @canShowFuelMessage bit = 0      
 DECLARE @bigPreviousTripID bigint      
 DECLARE @vcVIN varchar(20) = NULL      
 DECLARE @vcLicensePlate varchar(20) =NULL      
 DECLARE @vcVehDispName varchar(50) = NULL      
 DECLARE @vcMakeName varchar (200) = NULL      
 DECLARE @vcModelName varchar(200) = NULL    
 DECLARE @intModelYear smallint = NULL    
      
 IF EXISTS (SELECT * FROM rvlfPackageOperations r      
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId      
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId      
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)      
   BEGIN      
    SET @canShowFuelMessage = 1      
   END      
      
 CREATE TABLE #tblMessageForProcessingTrip (      
  [ProcessorID] [bigint] identity(1,1) NOT NULL,      
  [MessageInId] [uniqueidentifier] NOT NULL,      
  [Boxid] [int] NOT NULL,      
  [OriginDateTime] [datetime] NOT NULL,      
  [BoxMsgInTypeId] [tinyint] NULL,      
  [OdoMeterReading] [int] NULL,      
  [IgnitionStatus] [bit] NULL,      
  [StreetAddress] [nvarchar](250) NOT NULL,      
  [VehicleId] [bigint] NOT NULL,      
  [VIN] [varchar](20) NULL,      
  [LicensePlate] [varchar](20) NULL,      
  [VehDispName] [varchar](50) NULL,      
  [MakeName] [varchar](200) NULL,      
  [ModelName] [varchar](200) NULL,      
  [ModelYear] [smallint] null,    
  [CustomProp] [varchar](600) NULL,      
  [BoxMsgInTypeDesc] varchar(100) NULL,      
  [Speed] int NULL,      
  [SensorMask] varchar(250) NULL,      
  [TripId] [bigint] NULL,      
  [Duration] [int] NULL,      
  [SensorNo] [tinyint] NULL       
 )      
      
 CREATE INDEX IDX_RVLT_Processor on #tblMessageForProcessingTrip(ProcessorID)      
      
 CREATE INDEX IDX_RVLT_Trips On #tblTripDetailsForTD (BoxId,IsTripClosed)      
 DECLARE @tblBoxes TABLE (BoxID int, StartDate DateTime, EndDate DateTime)      
        
  INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va       
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId      
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId      
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or BoxId = @intBoxID)      
         
 DECLARE @intBoxLooping int      
  DECLARE @dtFirstDate datetime      
  DECLARE @dtLastDate datetime      
  SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes      
  WHILE @intBoxLooping IS NOT NULL      
   BEGIN      
    SELECT TOP 1 @bitIgnitionStatus = cast( SUBSTRING(SensorMask,6,1) as bit), @tiBoxMsgInTypeId = BoxMsgInTypeId,      
     @dtOriginDateTime = OriginDateTime, @tiSensorNo = CASE WHEN BoxMsgInTypeId = 2       
      THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,      
       CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END      
    FROM rvlfMsgInHst where BoxId= @intBoxLooping and OriginDateTime between @dtStartDate and @dtEndDate      
     AND CustomProp like '%Odometer%' and BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)      
    ORDER BY OriginDateTime asc      
    SET @dtFirstDate = NULL; SET @dtLastDate= NULL      
    IF @bitIgnitionStatus = 1 and @tiBoxMsgInTypeId <> 2      
     BEGIN      
      SELECT TOP 1 @dtOriginDateTime = OriginDateTime FROM rvlfMsgInHst       
       WHERE BoxId= @intBoxLooping and BoxMsgInTypeId = 2       
        and SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,      
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) = '3'       
        AND OriginDateTime <= @dtOriginDateTime      
      ORDER BY OriginDateTime desc      
      SET @dtFirstDate =  @dtOriginDateTime      
     END      
    ELSE IF @tiBoxMsgInTypeId = 2 AND @tiSensorNo = 3      
     BEGIN      
      SET @dtFirstDate = @dtOriginDateTime      
     END      
    ELSE       
     BEGIN      
      SELECT TOP 1 @dtOriginDateTime = OriginDateTime FROM rvlfMsgInHst       
       WHERE BoxId= @intBoxLooping and BoxMsgInTypeId = 2       
        and SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,      
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) = '3'       
        AND OriginDateTime >= @dtStartDate      
       ORDER BY OriginDateTime asc      
      SET @dtFirstDate =  @dtOriginDateTime      
     END      
          
    SELECT TOP 1 @bitIgnitionStatus = cast( SUBSTRING(SensorMask,6,1) as bit), @tiBoxMsgInTypeId = BoxMsgInTypeId,      
     @dtOriginDateTime = OriginDateTime      
    FROM rvlfMsgInHst where BoxId= @intBoxLooping and OriginDateTime between @dtStartDate and @dtEndDate      
     AND CustomProp like '%Odometer%' and BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)      
    ORDER BY OriginDateTime desc      
          
    IF @bitIgnitionStatus = 1      
     BEGIN      
      SELECT TOP 1 @dtOriginDateTime = OriginDateTime FROM rvlfMsgInHst       
       WHERE BoxId= @intBoxLooping and BoxMsgInTypeId = 3       
        AND OriginDateTime >= @dtOriginDateTime      
       ORDER BY OriginDateTime asc      
      SET @dtLastDate =  @dtOriginDateTime      
     END      
    ELSE IF @bitIgnitionStatus = 0 or @tiBoxMsgInTypeID = 3      
     BEGIN      
      SET @dtLastDate = @dtOriginDateTime      
     END      
    ELSE       
     BEGIN      
      SELECT TOP 1 @dtOriginDateTime = OriginDateTime FROM rvlfMsgInHst       
       WHERE BoxId= @intBoxLooping and BoxMsgInTypeId = 3       
        AND OriginDateTime <= @dtEndDate      
       ORDER BY OriginDateTime desc      
      SET @dtLastDate =  @dtOriginDateTime      
     END      
          
    INSERT INTO #tblMessageForProcessingTrip (      
     MessageInId, Boxid, OriginDateTime, BoxMsgInTypeId, OdoMeterReading, IgnitionStatus, StreetAddress,      
     VehicleId, VIN, LicensePlate, VehDispName, MakeName, ModelName, ModelYear,CustomProp, BoxMsgInTypeDesc, Speed,      
     SensorMask, Duration, SensorNo)      
      SELECT h.MessageInId,h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,      
       CAST( SUBSTRING (h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)+9,CHARINDEX(';',h.CustomProp,      
        CHARINDEX('Odometer=',h.CustomProp,1)) - (CHARINDEX('Odometer=',h.CustomProp,1)+9)) as int) as OdoMeterReading,      
       cast( SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,      
       --ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,  
       CASE WHEN (H.LandMarkID IS NULL OR H.LandMarkID = 0) THEN   
       Replace(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''') ELSE L.LandmarkName END AS StreetAddress,  
       v.VehicleId,v.VIN,v.LicensePlate,       
       v.VehicleDescription,mk.MakeName, md.ModelName, ModelYear,h.CustomProp, m.BoxMsgInTypeDesc, Speed       
       ,Case WHEN h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc       
        WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +      
        CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +      
        dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'      
        ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID,       
        h.OriginDateTime, @canShowFuelMessage)END,       
       CASE WHEN h.BoxMsgInTypeID = 9 THEN       
        CAST(dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeID, h.BoxId,0) as int) ELSE 0 END,      
       CASE WHEN h.BoxMsgInTypeId = 2 THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,      
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END      
        from rvlfMsgInHst h       
         INNER JOIN rvlfBoxMsgInType m WITH (NOLOCK)   
         ON h.BoxMsgInTypeId = m.BoxMsgInTypeId      
         INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId      
         INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId      
         LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId      
         LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId      
         INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId      
         INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId      
         INNER JOIN rvlfOrganization g ON v.OrganizationId = g.OrganizationId  
         LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID      
        where h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)      
        AND 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 ( @bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID)       
          --AND v.OrganizationID = @bigOrganizationID      
          --Commented by Jeyanthi on 11-Aug-2010    
          --AND h.OriginDateTime between @dtFirstDate and @dtLastDate      
          AND h.OriginDateTime between @dtStartDate and @dtEndDate      
          --End    
          AND h.BoxID = @intBoxLooping      
         order by h.origindatetime asc, h.MessageInID asc      
    SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes WHERE BoxID < @intBoxLooping      
   END      
      
  SELECT @intIterator = MIN(ProcessorID) FROM #tblMessageForProcessingTrip WHERE TripId is NULL      
  WHILE @intIterator IS NOT NULL      
  BEGIN      
   SET @intBoxID = NULL; SET @dtOriginDateTime = NULL; SET @tiBoxMsgInTypeId = NULL; SET @bigOdoMeterReading = NULL;       
   SET @bitIgnitionStatus = NULL; SET @vcStreetAddress = NULL; SET @intDuration = NULL; SET @tiSensorNo = NULL      
   SELECT  @intBoxID = Boxid, @dtOriginDateTime = OriginDateTime,       
     @tiBoxMsgInTypeId = BoxMsgInTypeId, @bigOdoMeterReading = OdoMeterReading,      
     @bitIgnitionStatus = IgnitionStatus,@vcStreetAddress = StreetAddress,       
     @intDuration = Duration, @tiSensorNo = SensorNo,      
     @vcVIN = VIN, @vcLicensePlate  = LicensePlate, @vcVehDispName  = VehDispName, @vcMakeName = MakeName,      
     @vcModelName = ModelName , @intModelYear=ModelYear    
   FROM #tblMessageForProcessingTrip WHERE ProcessorID=@intIterator      
     
   DECLARE @bigEndOdoMeterReading bigint;  
   SET @bigEndOdoMeterReading = NULL;   
     
    SELECT top 1 @bigEndOdoMeterReading =OdoMeterReading from #tblMessageForProcessingTrip where Boxid=@intBoxID order by ProcessorID desc  
     
      
   SELECT @bigTripID = ISNULL(MAX(TripID),0) FROM #tblTripDetailsForTD WHERE BoxID = @intBoxID       
    AND IsTripClosed = 0      
    IF (@bitIgnitionStatus = 1 AND @tiBoxMsgInTypeId=2)   
      BEGIN    
       DECLARE @dtENDTIME DATETIME=NULL,@dtSTARTTIME DATETIME=NULL  
       SELECT TOP 1 @dtENDTIME=OriginDateTime,@dtSTARTTIME=@dtOriginDateTime  FROM #tblMessageForProcessingTrip WHERE OriginDateTime>@dtOriginDateTime AND BoxMsgInTypeId=3 AND boxId=@intBoxId  
      END    
      
    IF @intDuration > 0       
     BEGIN      
      UPDATE #tblTripDetailsForTD SET IdlingDuration = IdlingDuration + @intDuration       
       WHERE TripID = @bigTripID       
     END      
          
    IF @bitIgnitionStatus = 1 AND @bigTripID = 0 AND @tiBoxMsgInTypeId = 2 AND @tiSensorNo = 3      
     BEGIN      
      SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM #tblTripDetailsForTD       
       WHERE BoxId = @intBoxID       
      SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM #tblTripDetailsForTD      
      INSERT INTO #tblTripDetailsForTD       
        (TripId, BoxId, StartDate, OdometerStart, OdometerEnd,      
         IsTripClosed, IdlingDuration, StartAddress, VIN, LicensePlate, VehDispName,       
         MakeName, ModelName,ModelYear)      
        VALUES       
        (@bigTripID, @intBoxID, @dtOriginDateTime, @bigOdoMeterReading ,       
         @bigEndOdoMeterReading,0,0, @vcStreetAddress, @vcVIN, @vcLicensePlate, @vcVehDispName, @vcMakeName, @vcModelName,@intModelYear)      
             
      UPDATE #tblTripDetailsForTD SET StopTime = DATEDIFF(ss, EndDate, @dtOriginDateTime)       
      WHERE BoxId = @intBoxID   
     AND TripID = @bigPreviousTripID             
     END      
    ELSE IF @bitIgnitionStatus = 0 AND @tiBoxMsgInTypeId = 3      
     BEGIN      
  --set @lastIdlingDuration = 1      
      select TOP 1 @lastIdlingDuration = CAST(dbo.rvlf_fn_GetDuration(CustomProp,       
       BoxMsgInTypeID, BoxID, 0)as int) , @lastIdlingTime = OriginDateTime      
        FROM rvlfmsginhst where BoxId = @intBoxID      
         AND OriginDateTime <= @dtOriginDateTime  AND OriginDateTime>=@dtSTARTTIME AND OriginDateTime<=@dtENDTIME     
         AND BoxMsgInTypeId = 9 order by Origindatetime desc--, MessageInID asc      
           
      IF @lastIdlingDuration = 0       
       BEGIN      
         SET @lastIdlingDuration = ISNULL(DATEDIFF (SS, @lastIdlingTime, @dtOriginDateTime),0)      
         --SET @lastIdlingDuration = 0  
       END      
      ELSE      
       BEGIN      
        SET @lastIdlingDuration = 0  
       END      
             
      DECLARE @nextTripStart Datetime = null      
      SELECT TOP 1 @nextTripStart = OrigindateTime      
       from rvlfMsgInHst where OriginDateTime > @dtOriginDateTime      
       AND BoxMsgInTypeId = 2 AND CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,      
       CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) = 3      
       AND BoxId= @intBoxID      
       Order by OriginDateTime asc      
             
      UPDATE #tblTripDetailsForTD SET       
       EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL       
       THEN OdometerEnd ELSE @bigOdoMeterReading END,      
       IsTripClosed = 1, EndAddress = @vcStreetAddress,       
       IdlingDuration = IdlingDuration + @lastIdlingDuration,  
       StopTime = DATEDIFF(ss,@dtOriginDateTime, @nextTripStart)      
      WHERE TripID = @bigTripID AND BoxId = @intBoxID      
     END      
    UPDATE #tblMessageForProcessingTrip SET TripId = @bigTripID where ProcessorID=@intIterator      
    SELECT @intIterator = MIN(ProcessorID) FROM #tblMessageForProcessingTrip WHERE ProcessorID > @intIterator and TripId is NULL      
  END      
        
UPDATE #tblTripDetailsForTD SET StopTime = DATEDIFF(ss, EndDate, @dtEndDate) WHERE TripId=(SELECT MAX(TripId) FROM #tblTripDetailsForTD)        
        
DECLARE @TBLSUMMARY TABLE  
(  
 TripId bigint,  
 AvgSpeed numeric(8,2)  
)        
INSERT INTO @TBLSUMMARY (TripId,AvgSpeed)  
SELECT tripid,(((CAST(OdometerEnd as Int)-CAST(OdometerStart as int)))/  
CASE WHEN CAST(CAST(((CAST(DATEDIFF(SECOND,StartDate,EndDate) as int)))/60 as numeric(8,2))/60 as numeric(8,2))=0 THEN 1  
ELSE CAST(CAST(((CAST(DATEDIFF(SECOND,StartDate,EndDate) as int)))/60 as numeric(8,2))/60 as numeric(8,2)) END)*@ConversionFactor  from #tblTripDetailsForTD group by TripId,OdometerStart,OdometerEnd,EndDate,StartDate  
            
             
        
Select TripId,VehicleDescription,VIN,LicensePlate,MakeName,ModelName,ModelYear,BoxId,OriginDateTime,  
SensorMask,CEILING(Speed) Speed,StreetAddress,StartAddress,ISNULL(EndAddress,'Ongoing trip')EndAddress,StartDate,EndDate,  
CASE WHEN Cast(OdometerEnd as Int) < Cast(OdometerStart as int) Then 0  
ELSE Cast((Cast(OdometerEndReading as Int)-Cast(OdometerStartReading as int)) as nvarchar(20)) END Distance,  
Duration,  
(Case When IdlingTime = 0 Then '-' ELSE IdilingDuration END) IdilingDuration,IdlingTime,StopTime,DistanceCaption,SpeedCaption,/*OdometerStart,*/Odometer As OdometerStart,OdometerEnd,  
CAST(A.OdometerStartReading as nvarchar(10)) + ' - ' +  CAST(A.OdometerEndReading as nvarchar(10)) As OdometerReading,  
CAST(ROUND(ISNULL(AvgSpeed,0),0) AS INT)AS AvgSpeed    
FROM   
(SELECT t.TripId,t.VehDispName as VehicleDescription, p.Vin, p.LicensePlate , p.MakeName, p.ModelName,P.ModelYear,t.BoxId,       
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,p.OriginDateTime)) as OriginDateTime, p.SensorMask,CAST(p.Speed * @ConversionFactor as numeric(7,2)) AS Speed, p.StreetAddress,      
   t.StartAddress, t.EndAddress,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,t.StartDate)) as StartDate,      
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,t.EndDate)) as EndDate,      
   CAST(CAST((ABS(t.OdometerEnd - t.OdometerStart)*@ConversionFactor) AS numeric(7,2)) as varchar(20)) as Distance,       
   Convert(varchar,t.EndDate - t.StartDate,108) as Duration, dbo.rvlf_fn_GetTimeFromSeconds(t.IdlingDuration) AS IdilingDuration,      
   t.IdlingDuration as IdlingTime,           
   CASE WHEN t.StopTime IS NULL THEN       
     dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SS,t.EndDate, @dtEndDate))       
    ELSE dbo.rvlf_fn_GetTimeFromSeconds(t.StopTime) END AS StopTime,      
    @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,      
    CEILING(CAST((ABS(ISNULL(t.OdometerStart, 0)) * @ConversionFactor) as varchar(20)))as OdometerStart,      
    CEILING(CAST((ABS(ISNULL(t.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)))as OdometerEnd,   
    --CASE WHEN t.OdometerEnd IS NULL THEN CEILING(CAST((ABS(ISNULL(p.OdoMeterReading, 0)) * @ConversionFactor)as varchar(20)))  
    --ELSE CEILING(CAST((ABS(ISNULL(t.OdometerEnd, 0)) * @ConversionFactor) as varchar(20))) END as OdometerEnd,  
   (SELECT TOP 1 CEILING(CAST((ABS(ISNULL(tt.OdometerStart, 0)) * @ConversionFactor) as varchar(20))) FROM #tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId  and tt.TripId=p.TripId  ORDER BY OdometerStart ASC) As OdometerStartReading,       
   (SELECT TOP 1 CEILING(CAST((ABS(ISNULL(tt.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)))FROM #tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId and tt.TripId=p.TripId ORDER BY OdometerEnd DESC) AS OdometerEndReading,          
    --(SELECT TOP 1 CASE WHEN tt.OdometerEnd IS NULL THEN CEILING(CAST((ABS(ISNULL(p.OdoMeterReading, 0)) * @ConversionFactor) as varchar(20)))   
    -- ELSE CEILING(CAST((ABS(ISNULL(tt.OdometerEnd, 0)) * @ConversionFactor) as varchar(20))) END FROM #tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId and tt.TripId=p.TripId ORDER BY OdometerEnd DESC) AS OdometerEndReading,      
 CEILING(CAST((ABS(ISNULL(p.OdoMeterReading, 0)) * @ConversionFactor) as varchar(20)))as Odometer,S.AvgSpeed   
  FROM #tblMessageForProcessingTrip p      
 INNER JOIN @TBLSUMMARY S ON S.TripId=P.TripId       
   LEFT OUTER JOIN #tblTripDetailsForTD t   
   WITH (NOLOCK)   
   ON p.TripId = t.TripId where t.TripId is not null-- IsTripClosed = 1     
      )A  
  ORDER BY A.TripId, OriginDateTime      
    
    
   SELECT Distinct t.TripId,t.VehDispName as VehicleDescription,       
   Convert(Date,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,p.OriginDateTime))) as OriginDateTime,   
   CEILING(CAST(p.Speed * @ConversionFactor as numeric(7,2))) AS Speed       
   FROM #tblMessageForProcessingTrip p     
   --INNER JOIN @TBLSUMMARY S ON S.Boxid=P.Boxid        
   LEFT OUTER JOIN #tblTripDetailsForTD t ON p.TripId = t.TripId where t.TripId is not null-- IsTripClosed = 1     
   ORDER BY t.TripId, OriginDateTime    
   
  DROP Table #tblMessageForProcessingTrip      
  DROP Table #tblTripDetailsForTD      
        
 SET NOCOUNT OFF      
END   

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTripDetails_Opt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetTripDetails_Opt]                
 @bigFleetID bigint = null,                
 @intBoxID varchar(max) = null,                 
 @dtStartDate DateTime = null,                
 @dtEndDate DateTime = null,                
 @bitTripStatus bit = 1,                
 @bigOrganizationID bigint = null,                
 @bigQueryingUser bigint = 0,  
 @locationUpdate bit=1                
AS                
/***************************************************************************************************************/            
-- Name  : [rvlf_sp_GetTripDetails_Opt] 8,null, '2012-06-15 08:00:00 AM', '2012-06-18 08:00:00 PM',1, 6,303        
-- Description : To get the trip summary details            
--    :   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin            
-- Author  : V.Narayanasamy            
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--          : 01-Apr-2011 VN Created Intial Version           
--          : 09-Aug-2011 Ranjith Date Format Included           
--          : 22-Aug-2011 Ranjith null checking and arithimetic overflow issue fixed for odometerstart        
--          : 30-Nov-2011 Sakthi Distance calculation based on organization        
/******************************************************************************************************************/               
BEGIN            
              
 SET NOCOUNT ON              
  Declare @dtFDate datetime =@dtStartDate            
     Declare @dtEDate datetime =@dtEndDate              
 IF @bigFleetID IS NULL            
  BEGIN            
   SELECT @bigFleetID=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)         
 DECLARE @DefaultDateFormat INT = 0           
 DECLARE @Lang varchar(50),  @LangSetting varchar(20)                       
             
    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 ,        
     @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)=0 then 107 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            
             
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))            
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))            
             
 Create Table #tblTripDetailsForTD (            
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,            
  [BoxId] [int] NOT NULL,            
  [StartDate] [datetime] NOT NULL,            
  [EndDate] [datetime] NULL,            
  [OdometerStart] [bigint] NOT NULL,            
  [OdometerEnd] [bigint] NULL,            
  [IsTripClosed] [bit] NULL,            
  [IdlingDuration] [int] NULL,            
  [StopTime] [int] NULL,            
  [StartAddress] nvarchar(300) NULL,            
  [EndAddress] nvarchar(300) NULL,            
  [Speed] int NULL,            
  [RunningTime] int null            
 )            
             
 Create Table #tblTripDetails (            
  [TripId] [bigint] NOT NULL,            
  [BoxId] [int] NOT NULL,            
  [Messageinfo] nvarchar(300),            
  [OriginDate] [datetime] NOT NULL,              
  [Odometer] [bigint] NOT NULL,              
  [StreetAddress] nvarchar(300) NULL,              
  [Speed] int NULL            
 )            
             
 Create Table #TBLSTART         
 (            
  Processid bigint identity(1,1),            
  Boxid int,            
  StartTime datetime,            
  OdoStart bigint,            
  StartAddress nvarchar(300),            
  Running int,            
  idling int,            
  Speed int,            
  StopInterval int,            
  tripId int            
 )            
             
 Create Table #TBLSTOP         
 (            
  Boxid int,            
  StopTime datetime,            
  OdoEnd bigint,            
  EndAddress nvarchar(300),            
  tripId int            
)             
            
 DECLARE @intDuration int            
 DECLARE @dtOriginDateTime datetime            
 DECLARE @bigOdoMeterReading int            
 DECLARE @bitIgnitionStatus bit            
 DECLARE @vcStreetAddress nvarchar(250)            
 DECLARE @tiBoxMsgInTypeId tinyint            
 DECLARE @bigTripID bigint            
 DECLARE @intIterator int            
 DECLARE @canShowFuelMessage bit = 0            
             
 IF EXISTS (SELECT * FROM rvlfPackageOperations r            
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId            
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId            
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)            
   BEGIN            
    SET @canShowFuelMessage = 1            
   END            
            
 Create Table #tblMessageForProcessingTrip (            
  [OriginDateTime] [datetime] NOT NULL,            
  [BoxMsgInTypeId] [tinyint] NULL,            
  [CustomProp] [varchar](600) NULL,              
  [Speed] int NULL,            
  [Ignition] bit null,              
  [Address] nvarchar(300) null,            
  [OdoMeter] bigint null,            
  [MsgInfo] nvarchar(300) null            
            
 )            
            
 DECLARE @tblBoxes TABLE (BoxID int)            
              
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va             
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId            
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or @intBoxID='0' or BoxId  in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID            
   ORDER BY BoxId             
            
 DECLARE @intBoxLooping int            
             
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes            
 WHILE @intBoxLooping IS NOT NULL            
   BEGIN             
    -- GET THE MSGS FOR THE BOXID            
    DELETE FROM #tblMessageForProcessingTrip                 
    INSERT INTO #tblMessageForProcessingTrip(OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,OdoMeter,MsgInfo)            
      SELECT  h.OriginDateTime,h.CustomProp,CASE WHEN H.BoxMsgInTypeId IN(9,14,15,16,17,24,51,90) THEN 0 ELSE Speed END,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 (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 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,            
      CASE WHEN h.BoxMsgInTypeId = 28 THEN case when @Lang='LanguageArNew' then ISNULL(m.BoxMsgInTypeDesc_Ar, m.BoxMsgInTypeDesc) else m.BoxMsgInTypeDesc end                  
       WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +                
       CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +                
       dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'     
       ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips_New(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID,                 
       h.OriginDateTime, @canShowFuelMessage,@Lang)END                             
       FROM rvlfMsgInHst H            
           INNER JOIN rvlfBoxMsgInType m ON M.BoxMsgInTypeId=H.BoxMsgInTypeId             
        LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID                                            
       WHERE h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                      
          AND h.BoxID = @intBoxLooping            
          AND  h.BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)    
          and (@locationUpdate is null or @locationUpdate='' or H.BoxMsgInTypeId !=@locationUpdate)                                     
        ORDER BY h.origindatetime ASC             
                    
    -- GET THE IGNITION ON DETAILS            
    DELETE FROM #TBLSTART                 
    INSERT INTO #TBLSTART (Boxid,StartTime,OdoStart,StartAddress)            
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address             
     FROM #tblMessageForProcessingTrip                   
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
      AND BoxMsgInTypeId IN(2)            
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)            
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)              
      AND Ignition=1 AND CustomProp LIKE '%SENSOR_NUM=3%'    
                 
                 
                 
    --GET THE IGNITION OFF DETAILS               
    DELETE FROM #TBLSTOP             
    INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress)            
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address               
     FROM #tblMessageForProcessingTrip              
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
      AND BoxMsgInTypeId IN(3)            
      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)            
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)    
       AND CustomProp LIKE '%SENSOR_NUM=3%'              
                
    --PREPARE THE TRIPS AND DETAILS            
                
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM #TBLSTART )             
    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 #TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                
                     
      IF @DTSTOPSTART IS NOT NULL                     
       UPDATE top(1) #TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART             
                  
      SET @DTSTOPSTART=@DTSTART             
                  
      SELECT TOP 1 @DTEND=StopTime   FROM #TBLSTOP WHERE StopTime >@DTSTART             
                  
      UPDATE top(1) #TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART             
      UPDATE top(1) #TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND              
      UPDATE top(1) #TBLSTART SET Speed =(SELECT MAX(SPEED) FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),            
      idling=(SELECT SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,            
       (CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT))       
       FROM #tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9             
        AND CustomProp NOT LIKE '%Idling:0;%'),            
       --Running=(SELECT (SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,            
       --(CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60)                         
       --FROM #tblMessageForProcessingTrip             
       --WHERE OriginDateTime BETWEEN @DT AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =3)            
      Running=DATEDIFF(S,@DTSTART,@DTEND)            
       WHERE tripId=@INC AND StartTime=@DTSTART             
                   
      DECLARE @bigTrip bigint=(SELECT MAX(TripId) FROM #tblTripDetails)            
                   
      INSERT INTO #tblTripDetails (TripId,BoxId,Messageinfo,OriginDate,Speed,StreetAddress,Odometer)            
       SELECT ISNULL(@bigTrip,0)+1,@intBoxLooping,MsgInfo,OriginDateTime,Speed,Address,OdoMeter              
        FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND                     
                   
      SET @INC =@INC +1            
                  
      SELECT @LOOP =MIN(Processid) FROM #TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART            
                  
     END             
                
              
    --INSERT THE DETAILS IN THE MASTER TABLE            
    INSERT INTO #tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,            
     OdometerEnd,IdlingDuration,Speed,IsTripClosed,StopTime,RunningTime)             
    SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,S.idling,            
     S.Speed,1,S.StopInterval,S.Running               
      FROM #TBLSTART S            
       INNER JOIN #TBLSTOP ST ON ST.tripId=S.tripId                      
               
   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping            
   END            
 UPDATE #tblTripDetailsForTD SET StopTime = DATEDIFF(ss, EndDate, @dtEndDate) WHERE TripId=(SELECT MAX(TripId) FROM #tblTripDetailsForTD)            
            
          
            
DECLARE @TBLSUMMARY TABLE            
(            
 Boxid int,            
 RunningTime int,            
 IdlingTime int,            
 StopTime int,            
 TripId bigint,            
 AvgSpeed bigint           
)            
--Ranjith Null checking Done        
INSERT INTO @TBLSUMMARY (Boxid,RunningTime,IdlingTime,StopTime,TripId,AvgSpeed)            
 SELECT BoxId,SUM(isnull(RunningTime,0)),SUM(isnull(IdlingDuration,0)),SUM(isnull(StopTime,0)),tripid,(((CAST(OdometerEnd as Int)-CAST(OdometerStart as bigint)))/            
CASE WHEN CAST(CAST(((CAST(DATEDIFF(SECOND,StartDate,EndDate) as int)))/60 as numeric(8,2))/60 as numeric(8,2))=0 THEN 1            
ELSE CAST(CAST(((CAST(DATEDIFF(SECOND,StartDate,EndDate) as int)))/60 as numeric(8,2))/60 as numeric(8,2)) END)*@ConversionFactor FROM #tblTripDetailsForTD GROUP BY BoxId,TripId,OdometerStart,OdometerEnd,EndDate,StartDate             
        
--SELECT * FROM #tblTripDetailsForTD  ORDER BY BoxId DESC                   
--SELECT * FROM @TBLSUMMARY        
            
SELECT TD.TripId, V.VehicleId,V.VehicleDescription,V.Vin,V.LicensePlate,        
StartDate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,StartDate),        
EndDate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,EndDate),        
--Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)),@DefaultDateFormat) + ' '+ Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate))as Time),22) as StartDate,            
 --Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate))as Time),22) as EndDate,        
 TD.StartAddress,TD.EndAddress,            
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,ROUND((CASE WHEN CAST(OdometerEnd AS INT) < CAST(OdometerStart AS INT) THEN 0 ELSE(CAST(OdometerEnd AS INT)-           
 
 CAST(OdometerStart AS INT))END) * @ConversionFactor,0))) AS Distance,        
 dbo.rvlf_fn_getTimeFromSeconds(TS.IdlingTime) AS IdlingSummary,            
 dbo.rvlf_fn_getTimeFromSeconds(TS.RunningTime) as RunningSummary,CAST(ROUND(ISNULL(AvgSpeed,0),0) AS INT)AS AvgSpeed,            
 dbo.rvlf_fn_getTimeFromSeconds(TS.StopTime) as StopSummary,        
 OriginDateTime = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,T.OriginDate),        
 --Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,T.OriginDate)),@DefaultDateFormat)+ ' ' + Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,T.OriginDate)) as time),22) as OriginDateTime,            
 CAST(T.OriginDate AS DATETIME) AS OriginDateTimeSort,        
 T.Messageinfo,T.Speed,T.StreetAddress,        
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(T.Odometer * @ConversionFactor))) AS Odometer,        
 @DistanceCaptionPrefix as DistanceCaption,            
 CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(TD.OdometerStart * @ConversionFactor))) as nvarchar(10)) + ' - ' +    
 CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(TD.OdometerEnd * @ConversionFactor)))  as nvarchar(10)) As OdometerReading,  
 @SpeedCaptionPrefix as SpeedCaption,        
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,        
  PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())        
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate         
  
FROM #tblTripDetailsForTD TD            
 INNER JOIN #tblTripDetails T ON T.TripId=TD.TripId             
 INNER JOIN @TBLSUMMARY TS ON TS.TripId =TD.TripId             
 INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =TD.BoxId             
 INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId             
             
            
   SELECT Distinct t.TripId,V.VehicleDescription,           
    Convert(Date,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,P.OriginDate)) as OriginDateTime,                 
   --Convert(Date,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,P.OriginDate))) as OriginDateTime,             
   CEILING(CAST(p.Speed * @ConversionFactor as numeric(7,2))) AS Speed                 
   FROM #tblTripDetails  p                     
  INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=p.BoxId             
  INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId             
  LEFT OUTER JOIN #tblTripDetailsForTD  t ON p.TripId = t.TripId where t.TripId is not null            
   ORDER BY t.TripId, OriginDateTime               
            
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTripDetails_Opt_TestOptmz]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetTripDetails_Opt_TestOptmz]                    
 @bigFleetID bigint = null,                    
 @intBoxID varchar(max) = null,                     
 @dtStartDate DateTime = null,                    
 @dtEndDate DateTime = null,                    
 @bitTripStatus bit = 1,                    
 @bigOrganizationID bigint = null,                    
 @bigQueryingUser bigint = 0,      
 @locationUpdate bit=1                    
AS                    
/***************************************************************************************************************/                
-- Name  : [rvlf_sp_GetTripDetails_Opt_TestOptmz] 178,661, '2014-05-22 08:00:00 AM', '2014-05-23 08:00:00 PM',1, 118,502  
-- Description : To get the trip summary details                
--    :   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin                
-- Author  : V.Narayanasamy                
-- Company  : Angler Technologies                
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                
--          : 01-Apr-2011 VN Created Intial Version               
--          : 09-Aug-2011 Ranjith Date Format Included               
--          : 22-Aug-2011 Ranjith null checking and arithimetic overflow issue fixed for odometerstart            
--          : 30-Nov-2011 Sakthi Distance calculation based on organization            
/******************************************************************************************************************/                   
BEGIN                
                  
 SET NOCOUNT ON                  
  Declare @dtFDate datetime =@dtStartDate                
     Declare @dtEDate datetime =@dtEndDate                  
 IF @bigFleetID IS NULL                
  BEGIN                
   SELECT @bigFleetID=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)             
 DECLARE @DefaultDateFormat INT = 0               
 DECLARE @Lang varchar(50),  @LangSetting varchar(20)                           
                 
    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 ,            
     @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)=0 then 107 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                
                 
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                
                 
 Create Table #tblTripDetailsForTD (                
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,                
  [BoxId] [int] NOT NULL,                
  [StartDate] [datetime] NOT NULL,                
  [EndDate] [datetime] NULL,                
  [OdometerStart] [bigint] NOT NULL,                
  [OdometerEnd] [bigint] NULL,                
  [IsTripClosed] [bit] NULL,                
  [IdlingDuration] [int] NULL,                
  [StopTime] [int] NULL,                
  [StartAddress] nvarchar(300) NULL,                
  [EndAddress] nvarchar(300) NULL,                
  [Speed] int NULL,                
  [RunningTime] int null     
  unique(TripId,Boxid)  
 )                
                 
 Create Table #tblTripDetails (                
  [TripId] [bigint] NOT NULL,                
  [BoxId] [int] NOT NULL,                
  [Messageinfo] nvarchar(300),                
  [OriginDate] [datetime] NOT NULL,                  
  [Odometer] [bigint] NOT NULL,                  
  [StreetAddress] nvarchar(300) NULL,                  
  [Speed] int NULL     
  --unique(TripId,Boxid)             
 )                
                 
 Create Table #TBLSTART             
 (                
  Processid bigint identity(1,1),                
  Boxid int,                
  StartTime datetime,                
  OdoStart bigint,                
  StartAddress nvarchar(300),                
  Running int,                
  idling int,                
  Speed int,                
  StopInterval int,                
  tripId int                
 )                
                 
 Create Table #TBLSTOP             
 (                
  Boxid int,                
  StopTime datetime,                
  OdoEnd bigint,                
  EndAddress nvarchar(300),                
  tripId int                
)                 
                
 DECLARE @intDuration int                
 DECLARE @dtOriginDateTime datetime                
 DECLARE @bigOdoMeterReading int                
 DECLARE @bitIgnitionStatus bit                
 DECLARE @vcStreetAddress nvarchar(250)                
 DECLARE @tiBoxMsgInTypeId tinyint                
 DECLARE @bigTripID bigint                
 DECLARE @intIterator int                
 DECLARE @canShowFuelMessage bit = 0                
                 
 IF EXISTS (SELECT * FROM rvlfPackageOperations r                
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId                
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId                
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)                
   BEGIN                
    SET @canShowFuelMessage = 1                
   END                
                
 Create Table #tblMessageForProcessingTrip (                
  [OriginDateTime] [datetime] NOT NULL,                
  [BoxMsgInTypeId] [tinyint] NULL,                
  [CustomProp] [varchar](600) NULL,                  
  [Speed] int NULL,                
  [Ignition] bit null,                  
  [Address] nvarchar(300) null,                
  [OdoMeter] bigint null,                
  [MsgInfo] nvarchar(300) null              
 )                
                
 DECLARE @tblBoxes TABLE (BoxID int)                
                  
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM dbo.rvlfVehicleAssignment va                 
   INNER JOIN dbo.rvlfVehicle v ON va.VehicleId = v.VehicleId                
   INNER JOIN dbo.rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or @intBoxID='0' or BoxId  in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID                
   ORDER BY BoxId                 
                
 DECLARE @intBoxLooping int                
                 
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes                
 WHILE @intBoxLooping IS NOT NULL                
   BEGIN            
    -- GET THE MSGS FOR THE BOXID                
    DELETE FROM #tblMessageForProcessingTrip                     
    INSERT INTO #tblMessageForProcessingTrip(OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,OdoMeter,MsgInfo)                
      SELECT  h.OriginDateTime,h.CustomProp,CASE WHEN H.BoxMsgInTypeId IN(9,14,15,16,17,24,51,90) THEN 0 ELSE Speed END,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 (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 L.LandmarkName END,          
      H.Odometer,
      --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, 
                      
      CASE WHEN h.BoxMsgInTypeId = 28 THEN case when @Lang='LanguageArNew' then ISNULL(m.BoxMsgInTypeDesc_Ar, m.BoxMsgInTypeDesc) else m.BoxMsgInTypeDesc end                      
       WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +                    
       CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +                    
       dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'         
       ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips_New(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID,                     
       h.OriginDateTime, @canShowFuelMessage,@Lang)END                                 
       FROM rvlfMsgInHst H                
           INNER JOIN rvlfBoxMsgInType m ON M.BoxMsgInTypeId=H.BoxMsgInTypeId                 
        LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID                                                
       WHERE h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                          
          AND h.BoxID = @intBoxLooping                
          AND  h.BoxMsgInTypeId NOT IN (20,35,19,0,52,53,54,55,56,5,6)        
          and (@locationUpdate is null or @locationUpdate='' or H.BoxMsgInTypeId !=@locationUpdate)                                         
        ORDER BY h.origindatetime ASC                 
                        
    -- GET THE IGNITION ON DETAILS                
    DELETE FROM #TBLSTART                     
    INSERT INTO #TBLSTART (Boxid,StartTime,OdoStart,StartAddress)                
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address                 
     FROM #tblMessageForProcessingTrip                       
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                 
      AND BoxMsgInTypeId IN(2)                
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip                 
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip                 
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                  
      AND Ignition=1 AND CustomProp LIKE '%SENSOR_NUM=3%'        
                     
    --GET THE IGNITION OFF DETAILS                   
    DELETE FROM #TBLSTOP                 
    INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress)                
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address                   
     FROM #tblMessageForProcessingTrip                  
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                 
      AND BoxMsgInTypeId IN(3)                
      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip                 
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip                 
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)        
       AND CustomProp LIKE '%SENSOR_NUM=3%'                  
                    
    --PREPARE THE TRIPS AND DETAILS                
                    
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM #TBLSTART )                 
    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 #TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                    
                         
      IF @DTSTOPSTART IS NOT NULL                         
       UPDATE top(1) #TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART                 
                      
      SET @DTSTOPSTART=@DTSTART                 
                      
      SELECT TOP 1 @DTEND=StopTime   FROM #TBLSTOP WHERE StopTime >@DTSTART                 
                      
      UPDATE top(1) #TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART                 
      UPDATE top(1) #TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND                  
      UPDATE top(1) #TBLSTART SET Speed =(SELECT MAX(SPEED) FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),                
      idling=(SELECT SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,                
       (CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT))           
       FROM #tblMessageForProcessingTrip                 
       WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9                 
        AND CustomProp NOT LIKE '%Idling:0;%'),                
       --Running=(SELECT (SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,                
       --(CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60)                             
       --FROM #tblMessageForProcessingTrip                 
       --WHERE OriginDateTime BETWEEN @DT AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =3)                
      Running=DATEDIFF(S,@DTSTART,@DTEND)                
       WHERE tripId=@INC AND StartTime=@DTSTART                 
                       
      DECLARE @bigTrip bigint=(SELECT top 1 TripId FROM #tblTripDetails order by TripId desc)                
                       
      INSERT INTO #tblTripDetails (TripId,BoxId,Messageinfo,OriginDate,Speed,StreetAddress,Odometer)                
       SELECT ISNULL(@bigTrip,0)+1,@intBoxLooping,MsgInfo,OriginDateTime,Speed,Address,OdoMeter                  
        FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND                         
                       
      SET @INC =@INC +1                      
      SELECT @LOOP =MIN(Processid) FROM #TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART                                    
     END            
                  
    --INSERT THE DETAILS IN THE MASTER TABLE                
    INSERT INTO #tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,                
     OdometerEnd,IdlingDuration,Speed,IsTripClosed,StopTime,RunningTime)                 
    SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,S.idling,                
     S.Speed,1,S.StopInterval,S.Running                   
     FROM #TBLSTART S                
       INNER JOIN #TBLSTOP ST ON ST.tripId=S.tripId                          
                   
   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping                
   END                
 UPDATE #tblTripDetailsForTD SET StopTime = DATEDIFF(ss, EndDate, @dtEndDate) WHERE TripId=(SELECT top 1 TripId FROM #tblTripDetailsForTD order by TripId)                
                
DECLARE @TBLSUMMARY TABLE                
(                
 Boxid int,                
 RunningTime int,                
 IdlingTime int,                
 StopTime int,                
 TripId bigint,                
 AvgSpeed bigint               
)                
--Ranjith Null checking Done            
INSERT INTO @TBLSUMMARY (Boxid,RunningTime,IdlingTime,StopTime,TripId,AvgSpeed)                
 SELECT BoxId,SUM(isnull(RunningTime,0)),SUM(isnull(IdlingDuration,0)),SUM(isnull(StopTime,0)),tripid,(((CAST(OdometerEnd as Int)-CAST(OdometerStart as bigint)))/                
CASE WHEN CAST(CAST(((CAST(DATEDIFF(SECOND,StartDate,EndDate) as int)))/60 as numeric(8,2))/60 as numeric(8,2))=0 THEN 1                
ELSE CAST(CAST(((CAST(DATEDIFF(SECOND,StartDate,EndDate) as int)))/60 as numeric(8,2))/60 as numeric(8,2)) END)*@ConversionFactor FROM #tblTripDetailsForTD GROUP BY BoxId,TripId,OdometerStart,OdometerEnd,EndDate,StartDate                 
            
--SELECT * FROM #tblTripDetailsForTD  ORDER BY BoxId DESC                       
--SELECT * FROM @TBLSUMMARY            
                
SELECT TD.TripId, V.VehicleId,V.VehicleDescription,V.Vin,V.LicensePlate,            
StartDate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,StartDate),            
EndDate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,EndDate),            
--Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)),@DefaultDateFormat) + ' '+ Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate))as Time),22) as StartDate,                
 --Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate))as Time),22) as EndDate,            
 TD.StartAddress,TD.EndAddress,                
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,ROUND((CASE WHEN CAST(OdometerEnd AS INT) < CAST(OdometerStart AS INT) THEN 0 ELSE(CAST(OdometerEnd AS INT)-           
  
 CAST(OdometerStart AS INT))END) * @ConversionFactor,0))) AS Distance,            
 dbo.rvlf_fn_getTimeFromSeconds(TS.IdlingTime) AS IdlingSummary,                
 dbo.rvlf_fn_getTimeFromSeconds(TS.RunningTime) as RunningSummary,CAST(ROUND(ISNULL(AvgSpeed,0),0) AS INT)AS AvgSpeed,                
 dbo.rvlf_fn_getTimeFromSeconds(TS.StopTime) as StopSummary,            
 OriginDateTime = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,T.OriginDate),            
 --Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,T.OriginDate)),@DefaultDateFormat)+ ' ' + Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,T.OriginDate)) as time),22) as OriginDateTime,                
 CAST(T.OriginDate AS DATETIME) AS OriginDateTimeSort,            
 T.Messageinfo,T.Speed,T.StreetAddress,            
 (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(T.Odometer * @ConversionFactor))) AS Odometer,            
 @DistanceCaptionPrefix as DistanceCaption,                
 CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(TD.OdometerStart * @ConversionFactor))) as nvarchar(10)) + ' - ' +        
 CAST((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,CEILING(TD.OdometerEnd * @ConversionFactor)))  as nvarchar(10)) As OdometerReading,      
 @SpeedCaptionPrefix as SpeedCaption,            
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,            
  PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())            
 --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate        
   
    
      
FROM #tblTripDetailsForTD TD                
 INNER JOIN #tblTripDetails T ON T.TripId=TD.TripId                 
 INNER JOIN @TBLSUMMARY TS ON TS.TripId =TD.TripId                 
 INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId =TD.BoxId                 
 INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId                 
                 
                
  SELECT Distinct t.TripId,V.VehicleDescription,               
  Convert(Date,dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,P.OriginDate)) as OriginDateTime,                     
  --Convert(Date,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,P.OriginDate))) as OriginDateTime,                 
  CEILING(CAST(p.Speed * @ConversionFactor as numeric(7,2))) AS Speed                     
  FROM #tblTripDetails  p                         
  INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=p.BoxId                 
  INNER JOIN rvlfVehicle V ON V.VehicleId =VA.VehicleId                 
  LEFT OUTER JOIN #tblTripDetailsForTD  t ON p.TripId = t.TripId where t.TripId is not null                
  ORDER BY t.TripId, OriginDateTime                   
    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTripDetails_ROI]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetTripDetails_ROI]
@currDate datetime = null,
@bigOrganizationID int = null
/******************************************************************************************************************/        
-- Name			: rvlf_sp_GetTripDetails_ROI '2012-07-01',138
-- Description	: Automatically calculate the trip details and maintained in the table
-- Author		: Sakthi        
-- Company		: Angler Technologies        
-- History		: <<Date(dd-MON-yyyy)>> Initial Reason        
--				: 11-Jun-2013 Sakthi Created Intial Version       
/******************************************************************************************************************/    
AS
BEGIN
SET NOCOUNT ON

	DECLARE @stExecutionTime DATETIME
	DECLARE @endExecutionTime DATETIME

	BEGIN TRY

		SELECT @currDate = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
		
		SELECT @stExecutionTime = GETUTCDATE();

		DELETE RO FROM rvlfTripDetails_ROI RO INNER JOIN rvlfBoxId b ON b.BoxId=RO.BoxID 
		INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId
		INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId
		WHERE RO.IsMonthStart=1 AND CONVERT(DATE,ISNULL(v.InstalledDate,'2015-01-01')) > CONVERT(DATE,RO.InstalledDate)

		DECLARE @tblBoxes TABLE
		(
			BoxID int,
			OdoStart bigint,
			OdoEnd bigint,
			Distance bigint,
			EndDate datetime,
			Idling bigint null,
			Running bigint null,
			NoOfDays tinyint null,
			InsDate datetime,
			IsStartMonth bit 
		)
		
		DECLARE @tblMessages TABLE
		(
			BoxID int,
			OriginDatetime datetime,
			BoxMsgInTypeId int,
			CustomProp varchar(500),
			Duration int null
		)
		
		INSERT INTO @tblBoxes (BoxID,OdoStart,OdoEnd,Distance,EndDate,InsDate,IsStartMonth)
		SELECT b.BoxId,MIN(h.Odometer),MAX(h.Odometer),(MAX(h.odometer)-MIN(h.Odometer)),
		DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,CONVERT(DATE,ISNULL(v.InstalledDate,'2015-01-01')))+1,0)),CONVERT(DATE,ISNULL(v.InstalledDate,'2015-01-01')),1
		FROM rvlfMsgInHst h INNER JOIN rvlfBoxId b ON h.BoxId = b.BoxId 
		INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId=v.VehicleId
		INNER JOIN rvlfOrganization o ON o.OrganizationId=v.OrganizationId
		WHERE --b.OrganizationId=@bigOrganizationID AND 
		CONVERT(DATE,OriginDateTime) BETWEEN CONVERT(DATE,ISNULL(v.InstalledDate,'2015-01-01')) 
		AND DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,CONVERT(DATE,ISNULL(v.InstalledDate,'2015-01-01')))+1,0)) 
		AND b.BoxId NOT IN (SELECT BoxId FROM rvlfTripDetails_ROI) AND h.Odometer > 0 AND LEN(h.Odometer) < 7
		AND ISNULL(v.InstalledDate,'2015-01-01') IS NOT NULL
		GROUP BY b.BoxId,v.InstalledDate 
		UNION ALL
		SELECT b.BoxId,MIN(h.Odometer),MAX(h.Odometer),(MAX(h.odometer)-MIN(h.Odometer)),
		DATEADD(month, DATEDIFF(month, -1, @currDate) - 1, 0),
		--DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,CONVERT(DATE,@currDate))+1,0)),
		NULL,0
		FROM rvlfMsgInHst h INNER JOIN rvlfBoxId b ON h.BoxId = b.BoxId 
		INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId=v.VehicleId
		INNER JOIN rvlfOrganization o ON o.OrganizationId=v.OrganizationId
		WHERE --b.OrganizationId=@bigOrganizationID AND 
		h.Odometer <> 0 AND CONVERT(DATETIME,OriginDateTime) BETWEEN 
		DATEADD(mm, DATEDIFF(m,0,@currDate),0) AND DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@currDate)+1,0)) 
		--AND b.BoxId IN (SELECT DISTINCT BoxId FROM rvlfTripDetails_ROI) 
		AND h.Odometer > 0 AND LEN(h.Odometer) < 7
		GROUP BY b.BoxId
		
		--SELECT * FROM @tblBoxes 
		
		DECLARE @intBoxLooping int        
		DECLARE @idling bigint
		DECLARE @running bigint
		DECLARE @noofdays tinyint
		DECLARE @insDate datetime
		SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes        
		WHILE @intBoxLooping IS NOT NULL        
		BEGIN 
		
			DELETE FROM @tblMessages
			SELECT @insDate=ISNULL(InsDate,@currDate) FROM @tblBoxes WHERE BoxID=@intBoxLooping
			
			INSERT INTO @tblMessages(BoxID,BoxMsgInTypeId,OriginDatetime,CustomProp,Duration)
			SELECT BoxId,BoxMsgInTypeId,OriginDateTime,CustomProp,duration FROM rvlfMsgInHst WHERE 
			CONVERT(DATE,OriginDateTime) BETWEEN @insDate AND DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@insDate)+1,0))
			AND BoxMsgInTypeId IN (3,9)
			
			SELECT @running=SUM(Duration) FROM @tblMessages WHERE BoxID=@intBoxLooping AND BoxMsgInTypeId=3 AND CustomProp like 'SENSOR_NUM=3;%'
			SELECT @idling=SUM(Duration) FROM @tblMessages WHERE BoxID=@intBoxLooping AND BoxMsgInTypeId=9 
			SELECT @noofdays=COUNT(A.Date) FROM 
			(SELECT CONVERT(DATE,OriginDateTime) [Date] FROM @tblMessages GROUP BY CONVERT(DATE,OriginDateTime)) A
		
			Update @tblBoxes SET Idling=@idling,Running=@running,NoOfDays=@noofdays WHERE BoxID=@intBoxLooping
			SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping       
		END

		INSERT INTO rvlfTripDetails_ROI(BoxId,OdoStart,OdoEnd,Distance,Idling,Running,NoOfDays,StartDate,IsMonthStart,InstalledDate)
		SELECT BoxID,OdoStart,ISNULL(OdoEnd,0),ISNULL(Distance,0),ISNULL(Idling,0),ISNULL(Running,0),ISNULL(NoOfDays,0),EndDate,
		IsStartMonth,InsDate FROM @tblBoxes


		--Frame mail template for deleted records
		DECLARE @rowCount varchar(25)
		SELECT @rowCount = CAST(@@ROWCOUNT AS VARCHAR(25))
		
		SELECT @endExecutionTime = GETUTCDATE();
		
		DECLARE @bodytag varchar(max) = '<div style="font-family: Verdana; font-size: 12px;">
		<p><span style="color: rgb(0, 102, 153);"><strong>Dear All,</strong></span></p>
		<p><span style="color: rgb(0, 102, 153);"><u><em><strong>Last month data''s are moved successfully from ''FMS'' database for ROI analysis report.</strong></em></u></span></p>
		<table border="0" cellpadding="1" cellspacing="1" style="width: 439px; color: rgb(0, 102, 153);font-family: Verdana;">
		<tbody>
		<tr>
		<td align="left" nowrap="nowrap" style="font-family: Verdana; font-size: 12px;" valign="top"><strong>Details</strong></td>
		<td>&nbsp;</td>
		<td>&nbsp;</td>
		</tr>
		<tr style="font-family: Verdana; font-size: 12px;">
		<td align="left" valign="top">
		<strong>Source Database Name</strong>
		</td>
		<td align="left" valign="top">
		:
		</td>
		<td>
		TRINETRA_Pilot
		</td>
		</tr>
		<tr style="font-family: Verdana; font-size: 12px;">
		<td align="left" valign="top">
		<strong>No of inserted records</strong>
		</td>
		<td align="left" valign="top">
		:
		</td>
		<td>
		'+@rowCount+' 
		</td>
		</tr>
		<tr style="font-family: Verdana; font-size: 12px;">
		<td align="left" valign="top">
		<strong>Execution Time (hh:mm:ss)</strong>
		</td>
		<td align="left" valign="top">
		:
		</td>
		<td>'+
		ISNULL(dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SECOND,@stExecutionTime,@endExecutionTime)),'-')
		+'</td>
		</tr>
		</tbody>
		</table>
		<hr />
		<p>
		<span style="color: rgb(0, 102, 153);"><b>Best Regards,<br />
		</b></span><a href="http://www.trinetrawireless.com">
		<img alt="trinetrawireless" src="http://www.trinetrawireless.com/images/logo.png"
		style="border: 0px none; width: 94px; height: 34px;" /></a></p>
		<p>
		<span style="font-size: 10px;"><span style="color: rgb(0, 102, 153);">This is a system generated mail</span><br />
		</span>
		</p>
		<p>
		<b><b>&nbsp;</b></b></p>
		</div>'
		
		--Triggering mail once the delete process completed
		--EXEC msdb.dbo.sp_send_dbmail @profile_name='TRINETRA',@recipients='sakthigopinath@angleritech.com',
		--@subject='TRINETRA | Reg : Data moved for ROI analysis - FMS',@body= @bodytag,@body_format = 'HTML'
		
	END TRY
	BEGIN CATCH
	
		DECLARE @errLine VARCHAR(10),@errMsg VARCHAR(250)
		SELECT @errLine = ERROR_LINE(),@errMsg = ERROR_MESSAGE()
		SET @bodytag = '<div> Line No : '+ CAST(@errLine AS VARCHAR) +' , Message : '+CAST(@errMsg AS VARCHAR)+'</div>'
	--	EXEC msdb.dbo.sp_send_dbmail @profile_name='TRINETRA',@recipients='sakthigopinath@angleritech.com',
		--@subject='TRINETRA - ERROR | Reg : Reg : Data moved for ROI analysis - FMS ARCHIVE',@body= @bodytag,@body_format = 'HTML'
		
	END CATCH

SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTripSummary]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetTripSummary]  
 @bigFleetID bigint = null,  
 @intBoxID int = null,  
 @dtStartDate datetime = null,  
 @dtEndDate datetime = null,  
 @bitTripStatus bit = 1,  
 @bigOrganizationID bigint = null,  
 @bigQueryingUser bigint = 0  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetTripSummary 82,null, '2011-01-01 08:00:00 AM', '2011-01-18 08:00:00 AM',1, 57,62  
-- Description : To get the trip summary details  
--    :   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 28-May-2009 MJJC Created Intial Version   
--    : 29-Jan-2010 MJJC Changed the No address message  
--    : 28-Jun-2010 MJJC Included the Trip Processing directly from history.  
--    : 06-Jul-2010 MJJC Included the complete trip on start and ongoing trip too.  
--    : 03-Feb-2011 TSK  Included NOLOCK to avoiad deadlock issue.  
--    : 04-Feb-2011 TSK  Modified to show Landmark Name instead of StreetAddress  
/******************************************************************************/  
  
BEGIN  
    
 SET NOCOUNT ON    
   
 IF @bigFleetID IS NULL  
  BEGIN  
   SELECT @bigFleetID=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 = @bigQueryingUser  
   
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))  
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))  
   
 DECLARE @tblTripDetailsForTD TABLE(  
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,  
  [BoxId] [int] NOT NULL,  
  [StartDate] [datetime] NOT NULL,  
  [EndDate] [datetime] NULL,  
  [OdometerStart] [bigint] NOT NULL,  
  [OdometerEnd] [bigint] NULL,  
  [IsTripClosed] [bit] NULL,  
  [IdlingDuration] [int] NULL,  
  [StopTime] [int] NULL,  
  [StartAddress] nvarchar(300) NULL,  
  [EndAddress] nvarchar(300) NULL,  
  Speed int NULL  
 )  
  
 DECLARE @intDuration int  
 DECLARE @dtOriginDateTime datetime  
 DECLARE @bigOdoMeterReading int  
 DECLARE @bitIgnitionStatus bit  
 DECLARE @vcStreetAddress nvarchar(250)  
 DECLARE @tiBoxMsgInTypeId tinyint  
 DECLARE @bigTripID bigint  
 DECLARE @intIterator int  
 DECLARE @canShowFuelMessage bit = 0  
   
 IF EXISTS (SELECT * FROM rvlfPackageOperations r  
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId  
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId  
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)  
   BEGIN  
    SET @canShowFuelMessage = 1  
   END  
  
 DECLARE @tblMessageForProcessingTrip TABLE (  
  [ProcessorID] [bigint] identity(1,1) NOT NULL,    
  [Boxid] [int] NOT NULL,  
  [OriginDateTime] [datetime] NOT NULL,  
  [BoxMsgInTypeId] [tinyint] NULL,  
  [OdoMeterReading] [int] NULL,  
  [IgnitionStatus] [bit] NULL,  
  [StreetAddress] [nvarchar](250) NOT NULL,    
  [CustomProp] [varchar](600) NULL,    
  [Speed] int NULL,  
  [SensorMask] varchar(250) NULL,  
  [TripId] [bigint] NULL,  
  [Duration] [int] NULL,  
  [SensorNo] [tinyint] NULL  
 )  
  
 DECLARE @tblBoxes TABLE (BoxID int)  
    
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId  
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' or BoxId = @intBoxID) AND V.OrganizationId=@bigOrganizationID  
   ORDER BY BoxId   
  
 DECLARE @intBoxLooping int  
  
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes  
 WHILE @intBoxLooping IS NOT NULL  
   BEGIN   
   DECLARE @DTFIRST DATETIME=NULL,@DTEND DATETIME=NULL  
   --FIND THE FIRST IGNITION ON TIME BETWEEN THE FROM AND TO TIME  
    SELECT TOP 1 @DTFIRST=OriginDateTime FROM rvlfMsgInHst WHERE Boxid=@intBoxLooping AND BoxMsgInTypeId=2   
    AND OriginDateTime BETWEEN @dtStartDate and @dtEndDate AND cast( SUBSTRING(sensormask,6,1) as bit) = 1  
    ORDER BY OriginDateTime ASC  
    SELECT TOP 1 @DTEND=OriginDateTime FROM rvlfMsgInHst WHERE Boxid=@intBoxLooping AND BoxMsgInTypeId=3   
    AND OriginDateTime BETWEEN @dtStartDate and @dtEndDate AND cast( SUBSTRING(sensormask,6,1) as bit) = 0  
    ORDER BY OriginDateTime DESC   
      
    IF(@DTEND IS NULL OR @DTEND='')  
     BEGIN       
      SET @DTEND= @dtEndDate  
     END                                     
      
    INSERT INTO @tblMessageForProcessingTrip (  
      Boxid, OriginDateTime, BoxMsgInTypeId, OdoMeterReading, IgnitionStatus, StreetAddress,       
     CustomProp, Speed,  
     SensorMask, Duration, SensorNo)  
      SELECT h.Boxid, h.OriginDateTime, h.BoxMsgInTypeId,  
       CAST( SUBSTRING (h.CustomProp,CHARINDEX('Odometer=',h.CustomProp,1)+9,CHARINDEX(';',h.CustomProp,  
        CHARINDEX('Odometer=',h.CustomProp,1)) - (CHARINDEX('Odometer=',h.CustomProp,1)+9)) as int) as OdoMeterReading,  
       cast( SUBSTRING(h.sensormask,6,1) as bit) as IgnitionStatus,  
       --ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,  
       CASE WHEN (H.LandMarkID IS NULL OR H.LandMarkID = 0) THEN   
       Replace(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''') ELSE L.LandmarkName END AS StreetAddress,  
       h.CustomProp,Speed   
       ,Case WHEN h.BoxMsgInTypeId = 28 THEN m.BoxMsgInTypeDesc   
        WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +  
        CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +  
        dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1)+')'  
        ELSE dbo.rvlf_fn_GetAlarmDetailsForTrips(h.CustomProp,h.BoxMsgInTypeID, h.BoxId, h.MessageInID,   
        h.OriginDateTime, @canShowFuelMessage)END,   
       CASE WHEN h.BoxMsgInTypeID = 9 THEN   
        CAST(dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeID, h.BoxId,0) as int) ELSE 0 END,  
       CASE WHEN h.BoxMsgInTypeId = 2 THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,  
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END  
        from rvlfMsgInHst h   
         INNER JOIN rvlfBoxMsgInType m WITH (NOLOCK) ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
         LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID  
        where h.CustomProp like '%Odometer%' and h.BoxMsgInTypeId IN (2,3,9)  
        AND 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 @DTFIRST and @DTEND           
          AND h.BoxID = @intBoxLooping  
        ORDER BY h.origindatetime ASC   
     
    SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping  
   END  
  
 SELECT @intIterator = MIN(ProcessorID) FROM @tblMessageForProcessingTrip WHERE TripId is NULL  
 WHILE @intIterator IS NOT NULL  
  BEGIN  
   SET @intBoxID = NULL; SET @dtOriginDateTime = NULL; SET @tiBoxMsgInTypeId = NULL;   
   SET @bigOdoMeterReading = NULL;SET @bitIgnitionStatus = NULL; SET @vcStreetAddress = NULL;   
   SET @intDuration = NULL; DECLARE @dtEndTrip datetime=null;  
   Declare @bigOdoEnd bigint=null;declare @bitIsTripClosed bit=0;declare @intIdlingDuration int=0;  
   declare @dtNextStartTime datetime=null;declare @vcEndAddress nvarchar(300)=null  
   SELECT  @intBoxID = Boxid, @dtOriginDateTime = OriginDateTime,   
     @tiBoxMsgInTypeId = BoxMsgInTypeId, @bigOdoMeterReading = OdoMeterReading,  
     @bitIgnitionStatus = IgnitionStatus,@vcStreetAddress = StreetAddress,   
     @intDuration = Duration      
   FROM @tblMessageForProcessingTrip WHERE ProcessorID=@intIterator and TripId is NULL  
  
   IF(@bitIgnitionStatus=1 AND @tiBoxMsgInTypeId=2)  
    BEGIN  
     DECLARE @DTENDTIME DATETIME=NULL  
    --NEXT IGNITION TIME       
     SELECT TOP 1 @dtNextStartTime=OriginDateTime,@bitIsTripClosed=1 FROM @tblMessageForProcessingTrip   
      WHERE BoxMsgInTypeId=2 AND Boxid =@intBoxID AND OriginDateTime>@dtOriginDateTime AND SensorNo = 3  
     IF(@dtNextStartTime IS NOT NULL)  
      BEGIN  
       SELECT TOP 1 @DTENDTIME=OriginDateTime,@bitIsTripClosed=1,@vcEndAddress=StreetAddress,  
        @bigOdoEnd=OdoMeterReading     
        FROM @tblMessageForProcessingTrip   
        WHERE BoxMsgInTypeId=3 AND Boxid =@intBoxID AND OriginDateTime>=@dtOriginDateTime   
         AND OriginDateTime<@dtNextStartTime    
      END  
     ELSE  
      BEGIN  
       SELECT TOP 1 @DTENDTIME=OriginDateTime,@bitIsTripClosed=1,@vcEndAddress=StreetAddress,  
        @bigOdoEnd=OdoMeterReading    
        FROM @tblMessageForProcessingTrip   
        WHERE BoxMsgInTypeId=3 AND Boxid =@intBoxID AND OriginDateTime>@dtOriginDateTime  
      END   
     IF(@DTENDTIME IS NOT NULL AND @dtOriginDateTime IS NOT NULL)  
      BEGIN  
       SET @intIdlingDuration=(SELECT ISNULL(SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp, BoxMsgInTypeID, BoxID, 0)as int)),0)  
        FROM @tblMessageForProcessingTrip   
        WHERE BoxMsgInTypeId=9 AND BoxId=@intBoxID   
         AND OriginDateTime BETWEEN @dtOriginDateTime and @DTENDTIME  
         GROUP BY BoxId)  
       IF EXISTS(SELECT BOXID FROM @tblMessageForProcessingTrip WHERE Boxid=@intBoxID AND OriginDateTime BETWEEN @dtOriginDateTime and @DTENDTIME AND BoxMsgInTypeId=9 AND @intIdlingDuration=0)  
        BEGIN  
         DECLARE @dtIdilingOn datetime=null,@dtTamper datetime=null  
         SELECT @dtIdilingOn= OriginDateTime FROM @tblMessageForProcessingTrip WHERE Boxid=@intBoxID AND OriginDateTime BETWEEN @dtOriginDateTime and @DTENDTIME AND BoxMsgInTypeId=9   
         SELECT @dtTamper= OriginDateTime FROM rvlfMsgInHst WHERE Boxid=@intBoxID AND OriginDateTime BETWEEN @dtOriginDateTime and @DTENDTIME AND BoxMsgInTypeId=41   
         IF(@dtTamper IS NOT NULL)  
          SET @intIdlingDuration=ISNULL(DATEDIFF(SS,@dtIdilingOn,@dtTamper),0)  
         ELSE  
          SET @intIdlingDuration=ISNULL(DATEDIFF(SS,@dtIdilingOn,@DTENDTIME),0)            
        END  
          
      END   
           
    DECLARE @maxSpeed int=0  
    SET @maxSpeed = (SELECT MAX(Speed) from rvlfMsgInHst where BoxId=@intBoxID and OriginDateTime between @dtOriginDateTime and @DTENDTIME)  
      
   --INSERT THE TRIP DETAILS  
    INSERT INTO @tblTripDetailsForTD(BoxId,EndAddress,EndDate,IdlingDuration,IsTripClosed,OdometerEnd,OdometerStart,  
     StartAddress,StartDate,StopTime,Speed)    
     VALUES(@intBoxID,@vcEndAddress,@DTENDTIME,ISNULL(@intIdlingDuration,0),@bitIsTripClosed,@bigOdoEnd,@bigOdoMeterReading,  
       @vcStreetAddress,@dtOriginDateTime,DATEDIFF(S,@DTENDTIME,@dtNextStartTime),@maxSpeed)   
    SET @bigTripID=@@IDENTITY   
    END   
    UPDATE @tblMessageForProcessingTrip SET TripId = @bigTripID where Boxid=@intBoxID AND OriginDateTime>=@dtOriginDateTime AND OriginDateTime<=@DTENDTIME   
     
    SELECT @intIterator = MIN(ProcessorID) FROM @tblMessageForProcessingTrip WHERE ProcessorID > @intIterator and TripId is NULL  
  END  
    
 UPDATE @tblTripDetailsForTD SET StopTime = DATEDIFF(ss, EndDate, @dtEndDate) WHERE TripId=(SELECT MAX(TripId) FROM @tblTripDetailsForTD)  
  
 Select TripId,A.BoxId,Speed,StartDate,EndDate,TripStatus,Duration,TripDuration,    
  case when Cast(OdometerEnd as Int) < Cast(OdometerStart as int) Then 0   
   else Cast((Cast(OdometerEnd as Int)-Cast(OdometerStart as int)) as nvarchar(20)) END Distance,   
  StartAddress,EndAddress,VIN,LicensePlate,VehicleDescription,MakeName,ModelName,ModelYear,  
  (CASE WHEN IdlingDuration = 0 THEN '-' ELSE IdlingTime END) IdlingTime,  
  IdlingDuration,StopDuration,StopTime,DistanceCaption,SpeedCaption, OdometerStart,OdometerEnd,  
  OdometerStartReading,OdometerEndReading,  
  case when Cast(OdometerEndReading as Int) < Cast(OdometerStartReading as int) Then 0   
  ELSE ROUND(OdometerEndReading-OdometerStartReading,0,0) END DistanceSummary  
   from (  
  select t.TripId,Speed,t.BoxId, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)) as StartDate,  
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as EndDate,  
   CASE WHEN IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,  
   dbo.rvlf_fn_getTimeFromSeconds(DateDiff(SS,StartDate,EndDate)) as Duration,  
   ABS(DateDiff(SS,StartDate,EndDate)) as TripDuration,   
   CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20)))as Distance,   
   StartAddress,CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END AS EndAddress  , --Vin, LicensePlate, VehDispName as VehicleDescription, MakeName, ModelName,ModelYear,   
   dbo.rvlf_fn_GetTimeFromSeconds(IdlingDuration) AS IdlingTime, IdlingDuration,  
   CASE WHEN StopTime IS NULL THEN dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SS,EndDate , @dtEndDate))   
    ELSE dbo.rvlf_fn_GetTimeFromSeconds(StopTime) END AS StopDuration,  
   CASE WHEN StopTime IS NULL THEN ABS(DATEDIFF(SS,EndDate ,@dtEndDate)) ELSE StopTime END AS StopTime,  
   @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,  
   CEILING(CAST((ABS(ISNULL(t.OdometerStart, 0)) * @ConversionFactor) as varchar(20)))as OdometerStart,  
   CEILING(CAST((ABS(ISNULL(t.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)))as OdometerEnd,  
   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerStart, 0)) * @ConversionFactor) as varchar(20)),0,0) FROM @tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerStart ASC) As OdometerStartReading,   
   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)),0,0)FROM @tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerEnd DESC) AS OdometerEndReading     
  FROM @tblTripDetailsForTD t) A  
  INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON A.BoxId = va.BoxId  
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
  LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId  
  LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId  
   
       
     SELECT VehicleName, Round(Distance,0)Distance  
     FROM  
     (  
     select v.VehicleDescription VehicleName,  
     CAST((MAX(isnull(OdometerEnd,0))-MIN(ISNULL(OdometerStart,0)))* @ConversionFactor as varchar(20))Distance--,  
    -- CAST((ABS(ISNULL(SUM(OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as numeric(8,2)) as Distance  
     from @tblTripDetailsForTD t  
     INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON t.BoxId = va.BoxId  
     INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
     Group By VehicleDescription  
     )B  
  Where CAST(Distance AS numeric(22,2)) > 0  
   
        
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTripSummary_MFC]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetTripSummary_MFC]            
 @bigFleetID bigint = null,            
 @intBoxID varchar(max) = null,            
 @dtStartDate datetime = null,            
 @dtEndDate datetime = null,            
 @bitTripStatus bit = 1,          
 @bigOrganizationID bigint = null,            
 @bigQueryingUser bigint = 0            
AS            
/**********************************************************************************************************/   -- Name			: rvlf_sp_GetTripSummary_MFC 337,NULL, '2014/03/13 08:00:00 AM', '2014/03/14 08:00:00 PM',1, 190,303
-- Description	: To get the trip summary details based on other sensor except ignition            
-- Author		: V.Narayanasamy            
-- Company		: Angler Technologies            
-- History		: <<Date(dd-MON-yyyy)>> Initial Reason            
-- Created Date	: 05-Mar-2013 Sakthi
--				: 30-Jul-2013 Average speed calculation applied (distance / time)
--				: 05-Nov-2013 Stop Time calculation applied
/********************************************************************************************************/       
BEGIN            
              
 SET NOCOUNT ON              
 Declare @dtFDate datetime =@dtStartDate          
 Declare @dtEDate datetime =@dtEndDate          
 IF @bigFleetID IS NULL            
  BEGIN            
   SELECT @bigFleetID=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)          
 DECLARE @DefaultDateFormat INT = 0;              
    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,@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 = @bigQueryingUser            
             
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))            
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))            
             
 Create TABLE #tblTripDetailsForTD (            
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,            
  [BoxId] [int] NOT NULL,            
  [StartDate] [datetime] NOT NULL,            
  [EndDate] [datetime] NULL,            
  [OdometerStart] [bigint] NOT NULL,            
  [OdometerEnd] [bigint] NULL,            
  [IsTripClosed] [bit] NULL,            
  [IdlingDuration] [int] NULL,            
  [StopTime] [int] NULL,            
  [StartAddress] nvarchar(300) NULL,            
  [EndAddress] nvarchar(300) NULL,            
  [Speed] int NULL,            
  [AvgSpeed] int NULL,    
  [RunningTime] int null,            
  StartLat numeric(10,6),            
  StartLong numeric(10,6),            
  StopLat numeric(10,6),            
  StopLong numeric(10,6),
  MFCStopTime [int] NULL,
  MFCIdlingTime [int] NULL,
  Braking int NULL,
  Acceleration int null    
 )            
 Create Table #TBLSTART             
 (            
  Processid bigint identity(1,1),            
  Boxid int,            
  StartTime datetime,            
  OdoStart bigint,            
  StartAddress varchar(300),            
  Running int,            
  idling int,            
  Speed int,
  AvgSpeed int,            
  StopInterval int,            
  tripId int,            
  Lat numeric(10,6),            
  Long numeric(10,6),
  Braking int null,
  Acceleration int  null
 )            
             
 Create Table #TBLSTOP        
 (            
  Boxid int,            
  StopTime datetime,            
  OdoEnd bigint,            
  EndAddress varchar(300),            
  tripId int,            
  Lat numeric(10,6),            
  Long numeric(10,6),            
 IsTripCompleted bit            
 )             
            
 DECLARE @intDuration int            
 DECLARE @dtOriginDateTime datetime            
 DECLARE @bigOdoMeterReading int            
 DECLARE @bitIgnitionStatus bit          
 DECLARE @vcStreetAddress nvarchar(250)            
 DECLARE @tiBoxMsgInTypeId tinyint            
 DECLARE @bigTripID bigint            
 DECLARE @intIterator int            
DECLARE @canShowFuelMessage bit = 0            
             
 IF EXISTS (SELECT * FROM rvlfPackageOperations r            
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId            
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId            
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)            
   BEGIN            
    SET @canShowFuelMessage = 1            
   END            
            
 Create Table #tblMessageForProcessingTrip (       
  [BoxId] [bigint] NULL,         
  [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 @tblBoxes TABLE (BoxID int unique)            
              
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va             
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId            
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='0' OR @intBoxID='' or BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID            
   ORDER BY BoxId             
            
 DECLARE @intBoxLooping int            
             
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes            
 WHILE @intBoxLooping IS NOT NULL            
   BEGIN             
    -- GET THE MSGS FOR THE BOXID            
    DELETE FROM #tblMessageForProcessingTrip                 
    INSERT INTO #tblMessageForProcessingTrip(BoxId,OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,
    OdoMeter,Lat,Long)            
      SELECT  H.BoxId,h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,
      CASE WHEN @bigOrganizationID IN (23,190) AND BoxMsgInTypeId=2 AND CustomProp like 'SENSOR_NUM=2;%' THEN 1 ELSE CAST(SUBSTRING(sensormask,6,1) as bit) END,
      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.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate    
        ORDER BY h.origindatetime ASC             
                    
    -- GET THE IGNITION ON DETAILS            
    DELETE FROM #TBLSTART                 
    INSERT INTO #TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)            
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long             
     FROM #tblMessageForProcessingTrip                   
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
      AND BoxMsgInTypeId IN(2)            
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)            
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)            AND Ignition=1 AND (@bigOrganizationID IN (23,190) AND CustomProp LIKE '%SENSOR_NUM=2;%')
                 
    --GET THE IGNITION OFF DETAILS               
    DELETE FROM #TBLSTOP             
    INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)            
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                
     FROM #tblMessageForProcessingTrip              
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
      AND BoxMsgInTypeId IN(3)            
      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)            
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip             
       WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)            AND (@bigOrganizationID IN (23,190) AND CustomProp LIKE '%SENSOR_NUM=2;%')
                     
    --PREPARE THE TRIPS AND DETAILS                
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM #TBLSTART )             
    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 #TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                
                  
      IF @DTSTOPSTART IS NOT NULL                     
       UPDATE top(1) #TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART             
                  
      SET @DTSTOPSTART=@DTSTART             
      SET @DTEND=NULL            
      SELECT TOP 1 @DTEND=StopTime FROM #TBLSTOP WHERE StopTime >@DTSTART   
      
      DECLARE @EnableIdling int
      SELECT @EnableIdling = SUM(A.Idling) FROM
      (SELECT CASE WHEN ISNULL(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,            
      (CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT),0) >= 0 THEN 1
      ELSE 0 END AS Idling FROM #tblMessageForProcessingTrip             
      WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND BoxId =@intBoxLooping AND BoxMsgInTypeId =9) A          
                  
      UPDATE top(1) #TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART             
      UPDATE top(1) #TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND
      
      UPDATE top(1) #TBLSTART SET 
      Braking = (SELECT COUNT(BoxId) FROM #tblMessageForProcessingTrip WHERE OriginDateTime 
      BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId IN (14,15)),
      Acceleration = (SELECT COUNT(BoxId) FROM #tblMessageForProcessingTrip WHERE OriginDateTime 
      BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId IN (16,17)),
      Speed =(SELECT MAX(SPEED) FROM #tblMessageForProcessingTrip WHERE 
      OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),            
      AvgSpeed = 
      (SELECT CASE WHEN ((CAST(DATEDIFF(SECOND,MIN(OriginDateTime),MAX(OriginDateTime)) AS DECIMAL(8,2)) * 60.00) /3600.00) = 0 THEN 0 ELSE 
      ISNULL(CAST(ROUND((ROUND((CAST((MAX(OdoMeter)-MIN(Odometer)) AS DECIMAL(6,2))*@ConversionFactor),0) / ((DATEDIFF(SECOND,MIN(OriginDateTime),MAX(OriginDateTime))) / 3600.00)),0) AS INT) ,0) END
      FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId <> 35 AND OdoMeter <> 0 GROUP BY BoxId),
      --(SELECT CASE WHEN (CAST(DATEDIFF(MINUTE,MIN(OriginDateTime),MAX(OriginDateTime)) AS DECIMAL(6,2))/60.0) = 0 THEN 0 ELSE 
      --ISNULL(CAST((MAX(OdoMeter)-MIN(Odometer)) / (CAST(DATEDIFF(MINUTE,MIN(OriginDateTime),MAX(OriginDateTime)) AS DECIMAL(6,2))/60.0) AS INT) ,0) END
      --FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId <> 35 GROUP BY BoxId),
      --(SELECT AVG(SPEED) FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping), 
      idling= CASE WHEN @EnableIdling >=2 THEN
      (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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9             
      AND CustomProp NOT LIKE '%Idling:0;%') ELSE NULL END,             
      Running=DATEDIFF(S,@DTSTART,@DTEND)            
      WHERE tripId=@INC AND StartTime=@DTSTART             
	 
	  
      SET @INC =@INC +1            
                  
      SELECT @LOOP =MIN(Processid) FROM #TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART            
                  
     END             
                       
    --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME            
    UPDATE #TBLSTART SET Running = --CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE 
    Running --END             
     WHERE Running IS NOT NULL            
                
    --INSERT THE DETAILS IN THE MASTER TABLE            
    INSERT INTO #tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,            
     OdometerEnd,IdlingDuration,Speed,AvgSpeed, IsTripClosed,StopTime,RunningTime,StartLat,StartLong,StopLat,
     StopLong,Braking,Acceleration)             
    SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,S.idling,            
    S.Speed,S.AvgSpeed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running,S.Lat,S.Long,ST.Lat,ST.Long,            S.Braking,S.Acceleration
    FROM #TBLSTART S INNER JOIN #TBLSTOP ST ON ST.tripId=S.tripId                      
                 
   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping            
               
   UPDATE #tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM #tblTripDetailsForTD)           
   
               
   END             

UPDATE #tblTripDetailsForTD SET MFCStopTime=dbo.rvlf_fn_GetStopTime_MFC(BoxId,StartDate,EndDate),
MFCIdlingTime=dbo.rvlf_fn_GetIdlingTime_MFC(BoxId,StartDate,EndDate)   
           
DECLARE @TBLSUMMARY TABLE            
(            
 Boxid int,            
 RunningTime int,            
 IdlingTime int,            
 MFCIdlingTime int,
 StopTime int,
 MFCStopTime int,
 Braking VARCHAR(5),
 Acceleration VARCHAR(5)  
)            
INSERT INTO @TBLSUMMARY (Boxid,RunningTime,IdlingTime,MFCIdlingTime,StopTime,MFCStopTime,Braking,Acceleration)            
SELECT BoxId,SUM(RunningTime),SUM(IdlingDuration),SUM(MFCIdlingTime),SUM(StopTime),SUM(MFCStopTime),
CASE WHEN ISNULL(SUM(Braking),0) = 0 OR SUM(Braking) = 0 THEN '-'  ELSE CAST(SUM(Braking) AS VARCHAR) END,
CASE WHEN ISNULL(SUM(Acceleration),0) = 0 OR SUM(Acceleration) = 0 THEN '-' ELSE CAST(SUM(Acceleration) AS VARCHAR) END
FROM #tblTripDetailsForTD GROUP BY BoxId             
 
 Select          
  TripId,A.BoxId,Speed,AvgSpeed,     
  Convert(varchar,StartDate,@DefaultDateFormat)  as StartDate,Convert(varchar,EndDate,@DefaultDateFormat)   as EndDate,TripStatus,Duration,TripDuration,              
  StartDateSort as StartDateSort,--EndDate as EndDate,        
  TripStatus,Duration,TripDuration,CAST(ROUND(Distance,0) AS INT) AS Distance,
  --(SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,(case when Cast(OdometerEnd as Int) < Cast(OdometerStart as int) Then 0          
   --else (Cast(OdometerEnd as Int)-Cast(OdometerStart as int)) END))) AS Distance,   --Cast(  as decimal(10,3))         
  StartAddress,EndAddress,VIN,LicensePlate,VehicleDescription,MakeName,ModelName,ModelYear,            
  --(CASE WHEN IdlingDuration = 0 OR IdlingDuration IS NULL THEN '-' ELSE a.IdlingTime END) IdlingTime,IdlingDuration,
  A.MFCIdlingDuration AS IdlingDuration,A.MFCIdlingTime AS IdlingTime,
  StopDuration,a.StopTime,
  --A.MFCStopTime AS StopTime,
  DistanceCaption,SpeedCaption,         
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStart)) AS OdometerStart,        
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerEnd)) AS OdometerEnd,            
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStartReading)) AS OdometerStartReading,        
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerEndReading)) AS OdometerEndReading,            
  CASE WHEN @bigOrganizationID IN (23,190) THEN MFC.Distance_MFC ELSE (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,(case when Cast(OdometerEndReading as Int) < Cast(OdometerStartReading as int) Then 0             
  ELSE ROUND(OdometerEndReading-OdometerStartReading,0,0) END))) END AS DistanceSummary,            
  --dbo.rvlf_fn_getTimeFromSeconds(TS.IdlingTime) AS IdlingSummary, 
  dbo.rvlf_fn_getTimeFromSeconds(TS.MFCIdlingTime) AS IdlingSummary,           
  dbo.rvlf_fn_getTimeFromSeconds(TS.RunningTime) as RunningSummary,            
  dbo.rvlf_fn_getTimeFromSeconds(TS.StopTime) as StopSummary,
  --dbo.rvlf_fn_getTimeFromSeconds(TS.MFCStopTime) as StopSummary,
  CASE WHEN A.IdlingPercentage = 0 THEN '-' ELSE CAST(A.IdlingPercentage AS VARCHAR) END AS IdlingPercentage,
  CASE WHEN CAST(ISNULL((ISNULL(TS.MFCIdlingTime,0) *1.00) / (CASE WHEN(ISNULL(ISNULL(TS.RunningTime,0) ,0)*1.00)=0 
  THEN 1 ELSE  (ISNULL(ISNULL(TS.RunningTime,0) ,0)* 1.00) END) * 100,0) AS NUMERIC(15,2)) = 0 THEN '-' ELSE
  CAST(CAST(ISNULL((ISNULL(TS.MFCIdlingTime,0) *1.00) / (CASE WHEN(ISNULL(ISNULL(TS.RunningTime,0) ,0)*1.00)=0 
  THEN 1 ELSE  (ISNULL(ISNULL(TS.RunningTime,0) ,0)* 1.00) END) * 100,0) AS NUMERIC(15,2)) AS VARCHAR) END AS
  [S_IdlingPercentage],  StartLat,StartLong,StopLat,StopLong,
  CASE WHEN ISNULL(A.Braking,0)=0 THEN '-' ELSE CAST(A.Braking AS VARCHAR) END AS Braking,
  CASE WHEN ISNULL(A.Acceleration,0)=0 THEN '-' ELSE CAST(A.Acceleration AS VARCHAR) END AS Acceleration,
  TS.Braking AS BSummary,TS.Acceleration AS ASummary,
  Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,        
  Convert(varchar,@dtEDate,@DefaultDateFormat)+' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,        
   PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtEDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())          
   from (            
  select t.TripId,            
   CASE WHEN CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))) > 0 AND 
   t.Speed =0 THEN '-' ELSE CONVERT(VARCHAR,Speed) END Speed,            
   CASE WHEN CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))) > 0 AND 
   t.AvgSpeed =0 THEN '-' ELSE CONVERT(VARCHAR,AvgSpeed) END AvgSpeed,            
   t.BoxId,        
   StartDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,StartDate),          
   EndDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,EndDate),          
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate))  as StartDateSort,           
   CASE WHEN IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,            
   dbo.rvlf_fn_getTimeFromSeconds(RunningTime) as Duration,            
   RunningTime as TripDuration,             
   (ISNULL((OdometerEnd-OdometerStart), 0) * @ConversionFactor) as Distance, -- CAST( as Decimal(10,3))            
   StartAddress,CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END AS EndAddress  , --Vin, LicensePlate, VehDispName as VehicleDescription, MakeName, ModelName,ModelYear,             
   dbo.rvlf_fn_GetTimeFromSeconds(IdlingDuration) AS IdlingTime, IdlingDuration,   
   CASE WHEN MFCIdlingTime IS NULL OR MFCIdlingTime=0 THEN '-' ELSE  MFCIdlingTime END AS MFCIdlingDuration,
   CASE WHEN MFCIdlingTime IS NULL OR MFCIdlingTime=0 THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(MFCIdlingTime) END AS MFCIdlingTime,          
	CAST(ISNULL((ISNULL(MFCIdlingTime,0) *1.00) / (CASE WHEN(ISNULL(ISNULL(RunningTime,0) ,0)*1.00)=0 
  THEN 1 ELSE  (ISNULL(ISNULL(RunningTime,0) ,0)* 1.00) END) * 100,0) AS NUMERIC(15,2)) [IdlingPercentage],
   CASE WHEN StopTime IS NULL THEN dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SS,EndDate , @dtEndDate))             
   WHEN StopTime =0 THEN '-'            
   ELSE dbo.rvlf_fn_GetTimeFromSeconds(StopTime) END AS StopDuration,            
   --CASE WHEN MFCStopTime IS NULL OR MFCStopTime=0 THEN '-' ELSE  dbo.rvlf_fn_GetTimeFromSeconds(MFCStopTime) END AS StopDuration,
   CASE WHEN StopTime IS NULL THEN ABS(DATEDIFF(SS,EndDate ,@dtEndDate)) ELSE StopTime END AS StopTime,MFCStopTime,          
   @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,            
   CEILING(CAST((ABS(ISNULL(t.OdometerStart, 0)) * @ConversionFactor) as varchar(20)))as OdometerStart,            
   CEILING(CAST((ABS(ISNULL(t.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)))as OdometerEnd,            
   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerStart, 0)) * @ConversionFactor) as varchar(20)),0,0) FROM #tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerStart ASC) As OdometerStartReading,             
   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)),0,0)FROM #tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerEnd DESC) AS OdometerEndReading,            
   StartLat,StartLong,StopLat,StopLong,t.Braking,t.Acceleration                
  FROM #tblTripDetailsForTD t) A            
  INNER JOIN @TBLSUMMARY TS ON TS.Boxid =A.BoxId             
  INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON A.BoxId = va.BoxId            
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
  LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId            
  LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId
  INNER JOIN (SELECT AB.BoxId,SUM(ROUND(AB.Distance_MFC,0,0)) AS Distance_MFC FROM 
  (SELECT ts.BoxId,ts.TripId,CAST((MAX(isnull(OdometerEnd,0))-MIN(ISNULL(OdometerStart,0)))* @ConversionFactor as varchar(20))Distance_MFC
  from #tblTripDetailsForTD ts GROUP BY ts.BoxId,ts.TripId) AB GROUP BY AB.BoxId) MFC ON MFC.BoxId=A.BoxId
             
                 
     SELECT VehicleName, CAST(ROUND((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Round(Distance,0))),0) as bigint) AS Distance --Round(Distance,0)Distance            
     FROM            
     (            
     select v.VehicleDescription VehicleName,            
    CAST(SUM((ISNULL(OdometerEnd,0) - ISNULL(OdometerStart,0))) * @ConversionFactor as varchar(20)) Distance 
     --CAST((MAX(isnull(OdometerEnd,0))-MIN(ISNULL(OdometerStart,0)))* @ConversionFactor as varchar(20))Distance--,            
     from #tblTripDetailsForTD t            
     INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON t.BoxId = va.BoxId            
     INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
     Group By VehicleDescription            
     )B            
  Where CAST(Distance AS numeric(22,2)) > 0          
  SET NOCOUNT OFF
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTripSummary_MFC_Bckup]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetTripSummary_MFC_Bckup]
@bigFleetID bigint = null,
@intBoxID varchar(max) = null,
@dtStartDate datetime = null,
@dtEndDate datetime = null,
@bitTripStatus bit = 1,
@bigOrganizationID bigint = null,
@bigQueryingUser bigint = null
AS
/*****************************************************************************************************/            
-- Name			: rvlf_sp_GetTripSummary_MFC_Bckup 337,NULL, '2014/03/07 08:00:00 AM', '2014/03/07 08:00:00 PM',1, 190,303
-- Description	: To get the trip summary details based on other sensor except ignition            
-- Author		: V.Narayanasamy            
-- Company		: Angler Technologies            
-- History		: <<Date(dd-MON-yyyy)>> Initial Reason            
-- Created Date	: 05-Mar-2013 Sakthi
--				: 30-Jul-2013 Average speed calculation applied (distance / time)
--				: 05-Nov-2013 Stop Time calculation applied
/*****************************************************************************************************/            
BEGIN
SET NOCOUNT ON
 Declare @dtFDate datetime =@dtStartDate          
 Declare @dtEDate datetime =@dtEndDate          
 IF @bigFleetID IS NULL            
  BEGIN            
   SELECT @bigFleetID=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)          
 DECLARE @DefaultDateFormat INT = 0;              
    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,@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 = @bigQueryingUser            
             
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))            
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))            
             
 Create TABLE #tblTripDetailsForTD (            
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,            
  [BoxId] [int] NOT NULL,            
  [StartDate] [datetime] NOT NULL,            
  [EndDate] [datetime] NULL,            
  [OdometerStart] [bigint] NOT NULL,            
  [OdometerEnd] [bigint] NULL,            
  [IsTripClosed] [bit] NULL,            
  [IdlingDuration] [int] NULL,            
  [StopTime] [int] NULL,            
  [StartAddress] nvarchar(300) NULL,            
  [EndAddress] nvarchar(300) NULL,            
  [Speed] int NULL,            
  [AvgSpeed] int NULL,    
  [RunningTime] int null,            
  StartLat numeric(10,6),            
  StartLong numeric(10,6),            
  StopLat numeric(10,6),            
  StopLong numeric(10,6),
  MFCStopTime [int] NULL,
  MFCIdlingTime [int] NULL,
  Braking int NULL,
  Acceleration int null  
 )            
 Create Table #TBLSTART             
 (            
  Processid bigint identity(1,1),            
  Boxid int,            
  StartTime datetime,            
  OdoStart bigint,            
  StartAddress varchar(300),            
  Running int,            
  idling int,            
  Speed int,
  AvgSpeed int,            
  StopInterval int,            
  tripId int,            
  Lat numeric(10,6),            
  Long numeric(10,6),
  Braking int null,
  Acceleration int  null
 )            
             
 Create Table #TBLSTOP        
 (            
  Boxid int,            
  StopTime datetime,            
  OdoEnd bigint,            
  EndAddress varchar(300),            
  tripId int,            
  Lat numeric(10,6),            
  Long numeric(10,6),            
 IsTripCompleted bit            
 )             
            
 DECLARE @intDuration int            
 DECLARE @dtOriginDateTime datetime            
 DECLARE @bigOdoMeterReading int            
 DECLARE @bitIgnitionStatus bit          
 DECLARE @vcStreetAddress nvarchar(250)            
 DECLARE @tiBoxMsgInTypeId tinyint            
 DECLARE @bigTripID bigint            
 DECLARE @intIterator int            
DECLARE @canShowFuelMessage bit = 0            
             
 IF EXISTS (SELECT * FROM rvlfPackageOperations r            
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId            
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId            
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)            
   BEGIN            
    SET @canShowFuelMessage = 1            
   END            
            
 Create Table #tblMessageForProcessingTrip (       
  [BoxId] [bigint] NULL,         
  [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 @tblBoxes TABLE (BoxID int unique)            
              
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va             
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId            
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='0' OR @intBoxID='' or BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID            
   ORDER BY BoxId             

  DECLARE @intBoxLooping int            
             
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes            
 WHILE @intBoxLooping IS NOT NULL            
   BEGIN             
    -- GET THE MSGS FOR THE BOXID            
    DELETE FROM #tblMessageForProcessingTrip                 
    INSERT INTO #tblMessageForProcessingTrip(BoxId,OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,
    OdoMeter,Lat,Long)            
      SELECT  H.BoxId,h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,
      CASE WHEN @bigOrganizationID IN (23,190) AND BoxMsgInTypeId=2 AND CustomProp like 'SENSOR_NUM=2;%' THEN 1 ELSE 
      CAST(SUBSTRING(sensormask,6,1) as bit) END,
      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.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate    
        ORDER BY h.origindatetime ASC             

    -- GET THE IGNITION ON DETAILS            
    DELETE FROM #TBLSTART                 
    INSERT INTO #TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)            
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long             
     FROM #tblMessageForProcessingTrip                   
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
      AND BoxMsgInTypeId IN(2)            
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)            
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)              
      AND Ignition=1 AND ((@bigOrganizationID IN (23,190) AND CustomProp LIKE '%SENSOR_NUM=2;%'))
                   
                 
    --GET THE IGNITION OFF DETAILS               
    DELETE FROM #TBLSTOP             
    INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)            
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                
     FROM #tblMessageForProcessingTrip              
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate             
      AND BoxMsgInTypeId IN(3)            
      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip             
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)            
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip             
       WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)              
       AND ((@bigOrganizationID IN (23,190) AND CustomProp LIKE '%SENSOR_NUM=2;%'))
      
    --PREPARE THE TRIPS AND DETAILS                
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM #TBLSTART )             
    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 #TBLSTART WHERE Processid >=@LOOP AND 
      (@DTEND IS NULL OR StartTime >@DTEND)                
                  
      IF @DTSTOPSTART IS NOT NULL                     
       UPDATE top(1) #TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART                           
      SET @DTSTOPSTART=@DTSTART             
      SET @DTEND=NULL            
      SELECT TOP 1 @DTEND=StopTime FROM #TBLSTOP WHERE StopTime >@DTSTART   
      
      DECLARE @EnableIdling int
      SELECT @EnableIdling = SUM(A.Idling) FROM
      (SELECT CASE WHEN ISNULL(CAST(SUBSTRING(CustomProp,CHARINDEX('Idling:',CustomProp,0)+7,            
      (CHARINDEX(';',CustomProp,CHARINDEX('Idling:',CustomProp,0))-(CHARINDEX('Idling:',CustomProp,0)+7))) AS INT),0) >= 0 THEN 1
      ELSE 0 END AS Idling FROM #tblMessageForProcessingTrip             
      WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND BoxId =@intBoxLooping AND BoxMsgInTypeId =9) A          
                  
      UPDATE top(1) #TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART             
      UPDATE top(1) #TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND
      
      UPDATE top(1) #TBLSTART SET 
      Braking = (SELECT COUNT(BoxId) FROM #tblMessageForProcessingTrip WHERE OriginDateTime 
      BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId IN (14,15)),
      Acceleration = (SELECT COUNT(BoxId) FROM #tblMessageForProcessingTrip WHERE OriginDateTime 
      BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId IN (16,17)),
      Speed =(SELECT MAX(SPEED) FROM #tblMessageForProcessingTrip WHERE OriginDateTime 
      BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),            
      AvgSpeed = 
      (SELECT CASE WHEN ((CAST(DATEDIFF(SECOND,MIN(OriginDateTime),MAX(OriginDateTime)) AS DECIMAL(8,2)) * 60.00) /3600.00) = 0 THEN 0 ELSE 
      ISNULL(CAST(ROUND((ROUND((CAST((MAX(OdoMeter)-MIN(Odometer)) AS DECIMAL(6,2))*@ConversionFactor),0) / ((DATEDIFF(SECOND,MIN(OriginDateTime),MAX(OriginDateTime))) / 3600.00)),0) AS INT) ,0) END
      FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId <> 35 AND OdoMeter <> 0 GROUP BY BoxId),
      --(SELECT CASE WHEN (CAST(DATEDIFF(MINUTE,MIN(OriginDateTime),MAX(OriginDateTime)) AS DECIMAL(6,2))/60.0) = 0 THEN 0 ELSE 
      --ISNULL(CAST((MAX(OdoMeter)-MIN(Odometer)) / (CAST(DATEDIFF(MINUTE,MIN(OriginDateTime),MAX(OriginDateTime)) AS DECIMAL(6,2))/60.0) AS INT) ,0) END
      --FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId <> 35 GROUP BY BoxId),
      --(SELECT AVG(SPEED) FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping), 
      idling= CASE WHEN @EnableIdling >=2 THEN
      (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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9             
      AND CustomProp NOT LIKE '%Idling:0;%') ELSE NULL END,             
      Running=DATEDIFF(S,@DTSTART,@DTEND)            
      WHERE tripId=@INC AND StartTime=@DTSTART             
	 
	  
      SET @INC =@INC +1            
                  
      SELECT @LOOP =MIN(Processid) FROM #TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART            
                  
     END             
                       
    
    --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME            
    UPDATE #TBLSTART SET Running = --CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE 
    Running --END             
     WHERE Running IS NOT NULL            
                
    
                
    --INSERT THE DETAILS IN THE MASTER TABLE            
    INSERT INTO #tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,            
     OdometerEnd,IdlingDuration,Speed,AvgSpeed, IsTripClosed,StopTime,RunningTime,StartLat,StartLong,StopLat,StopLong,Braking,Acceleration)             
    SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,S.idling,            
    S.Speed,S.AvgSpeed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running,S.Lat,S.Long,ST.Lat,ST.Long,
    S.Braking,S.Acceleration    
    FROM #TBLSTART S INNER JOIN #TBLSTOP ST ON ST.tripId=S.tripId                      
                 
   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping            
               
   UPDATE #tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM #tblTripDetailsForTD)           
   
               
   END             

UPDATE #tblTripDetailsForTD SET MFCStopTime=dbo.rvlf_fn_GetStopTime_MFC(BoxId,StartDate,EndDate),
MFCIdlingTime=dbo.rvlf_fn_GetIdlingTime_MFC(BoxId,StartDate,EndDate)   
           
DECLARE @TBLSUMMARY TABLE            
(            
 Boxid int,            
 RunningTime int,            
 IdlingTime int,            
 MFCIdlingTime int,
 StopTime int,
 MFCStopTime int,
 Braking VARCHAR(5),
 Acceleration VARCHAR(5) 
)            
INSERT INTO @TBLSUMMARY (Boxid,RunningTime,IdlingTime,MFCIdlingTime,StopTime,MFCStopTime,Braking,Acceleration)            
SELECT BoxId,SUM(RunningTime),SUM(IdlingDuration),SUM(MFCIdlingTime),SUM(StopTime),SUM(MFCStopTime), 
CASE WHEN ISNULL(SUM(Braking),0) = 0 OR SUM(Braking) = 0 THEN '-'  ELSE CAST(SUM(Braking) AS VARCHAR) END,
CASE WHEN ISNULL(SUM(Acceleration),0) = 0 OR SUM(Acceleration) = 0 THEN '-' ELSE CAST(SUM(Acceleration) AS VARCHAR) END
FROM #tblTripDetailsForTD GROUP BY BoxId             
 
 Select          
  TripId,A.BoxId,Speed,AvgSpeed,     
  Convert(varchar,StartDate,@DefaultDateFormat)  as StartDate,Convert(varchar,EndDate,@DefaultDateFormat)   as EndDate,TripStatus,Duration,TripDuration,              
  StartDateSort as StartDateSort,--EndDate as EndDate,        
  TripStatus,Duration,TripDuration,CAST(ROUND(Distance,0) AS INT) AS Distance,
  --(SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,(case when Cast(OdometerEnd as Int) < Cast(OdometerStart as int) Then 0          
   --else (Cast(OdometerEnd as Int)-Cast(OdometerStart as int)) END))) AS Distance,   --Cast(  as decimal(10,3))         
  StartAddress,EndAddress,VIN,LicensePlate,VehicleDescription,MakeName,ModelName,ModelYear,            
  --(CASE WHEN IdlingDuration = 0 OR IdlingDuration IS NULL THEN '-' ELSE a.IdlingTime END) IdlingTime,IdlingDuration,
  A.MFCIdlingDuration AS IdlingDuration,A.MFCIdlingTime AS IdlingTime,
  StopDuration,a.StopTime,
  --A.MFCStopTime AS StopTime,
  DistanceCaption,SpeedCaption,         
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStart)) AS OdometerStart,        
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerEnd)) AS OdometerEnd,            
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStartReading)) AS OdometerStartReading,        
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerEndReading)) AS OdometerEndReading,            
  CASE WHEN @bigOrganizationID IN (23,190) THEN MFC.Distance_MFC ELSE (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,(case when Cast(OdometerEndReading as Int) < Cast(OdometerStartReading as int) Then 0             
  ELSE ROUND(OdometerEndReading-OdometerStartReading,0,0) END))) END AS DistanceSummary,            
  --dbo.rvlf_fn_getTimeFromSeconds(TS.IdlingTime) AS IdlingSummary, 
  dbo.rvlf_fn_getTimeFromSeconds(TS.MFCIdlingTime) AS IdlingSummary,           
  dbo.rvlf_fn_getTimeFromSeconds(TS.RunningTime) as RunningSummary,            
  dbo.rvlf_fn_getTimeFromSeconds(TS.StopTime) as StopSummary,
  --dbo.rvlf_fn_getTimeFromSeconds(TS.MFCStopTime) as StopSummary,
  StartLat,StartLong,StopLat,StopLong,CASE WHEN ISNULL(A.Braking,0)=0 THEN '-' ELSE CAST(A.Braking AS VARCHAR) END AS Braking,
  CASE WHEN ISNULL(A.Acceleration,0)=0 THEN '-' ELSE CAST(A.Acceleration AS VARCHAR) END AS Acceleration,
  TS.Braking AS BSummary,TS.Acceleration AS ASummary,
  Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,        
  Convert(varchar,@dtEDate,@DefaultDateFormat)+' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,        
   PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtEDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())          
   from (            
  select t.TripId,            
   CASE WHEN CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))) > 0 AND t.Speed =0 THEN '-' ELSE CONVERT(VARCHAR,Speed) END Speed,            
   CASE WHEN CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))) > 0 AND t.AvgSpeed =0 THEN '-' ELSE CONVERT(VARCHAR,AvgSpeed) END AvgSpeed,            
   t.BoxId,        
   StartDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,StartDate),          
   EndDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,EndDate),          
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate))  as StartDateSort,           
   CASE WHEN IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,            
   dbo.rvlf_fn_getTimeFromSeconds(RunningTime) as Duration,            
   RunningTime as TripDuration,             
   (ISNULL((OdometerEnd-OdometerStart), 0) * @ConversionFactor) as Distance, -- CAST( as Decimal(10,3))            
   StartAddress,CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END AS EndAddress  , --Vin, LicensePlate, VehDispName as VehicleDescription, MakeName, ModelName,ModelYear,             
   dbo.rvlf_fn_GetTimeFromSeconds(IdlingDuration) AS IdlingTime, IdlingDuration,   
   CASE WHEN MFCIdlingTime IS NULL OR MFCIdlingTime=0 THEN '-' ELSE  MFCIdlingTime END AS MFCIdlingDuration,
   CASE WHEN MFCIdlingTime IS NULL OR MFCIdlingTime=0 THEN '-' ELSE dbo.rvlf_fn_GetTimeFromSeconds(MFCIdlingTime) END AS MFCIdlingTime,          
   CASE WHEN StopTime IS NULL THEN dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SS,EndDate , @dtEndDate))             
   WHEN StopTime =0 THEN '-'            
   ELSE dbo.rvlf_fn_GetTimeFromSeconds(StopTime) END AS StopDuration,            
   --CASE WHEN MFCStopTime IS NULL OR MFCStopTime=0 THEN '-' ELSE  dbo.rvlf_fn_GetTimeFromSeconds(MFCStopTime) END AS StopDuration,
   CASE WHEN StopTime IS NULL THEN ABS(DATEDIFF(SS,EndDate ,@dtEndDate)) ELSE StopTime END AS StopTime,MFCStopTime,          
   @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,            
   CEILING(CAST((ABS(ISNULL(t.OdometerStart, 0)) * @ConversionFactor) as varchar(20)))as OdometerStart,            
   CEILING(CAST((ABS(ISNULL(t.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)))as OdometerEnd,            
   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerStart, 0)) * @ConversionFactor) as varchar(20)),0,0) FROM #tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerStart ASC) As OdometerStartReading,             
   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)),0,0)FROM #tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerEnd DESC) AS OdometerEndReading,            
   StartLat,StartLong,StopLat,StopLong,t.Braking,t.Acceleration                
  FROM #tblTripDetailsForTD t) A            
  INNER JOIN @TBLSUMMARY TS ON TS.Boxid =A.BoxId             
  INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON A.BoxId = va.BoxId            
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
  LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId            
  LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId
  INNER JOIN (SELECT AB.BoxId,SUM(ROUND(AB.Distance_MFC,0,0)) AS Distance_MFC FROM 
  (SELECT ts.BoxId,ts.TripId,CAST((MAX(isnull(OdometerEnd,0))-MIN(ISNULL(OdometerStart,0)))* @ConversionFactor as varchar(20))Distance_MFC
  from #tblTripDetailsForTD ts GROUP BY ts.BoxId,ts.TripId) AB GROUP BY AB.BoxId) MFC ON MFC.BoxId=A.BoxId
             
                 
     SELECT VehicleName, CAST(ROUND((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Round(Distance,0))),0) as bigint) AS Distance --Round(Distance,0)Distance            
     FROM            
     (            
     select v.VehicleDescription VehicleName,            
     CAST((MAX(isnull(OdometerEnd,0))-MIN(ISNULL(OdometerStart,0)))* @ConversionFactor as varchar(20))Distance--,            
     from #tblTripDetailsForTD t            
     INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON t.BoxId = va.BoxId            
     INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
     Group By VehicleDescription            
     )B            
  Where CAST(Distance AS numeric(22,2)) > 0          
  SET NOCOUNT OFF
 END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTripSummary_MobApp]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetTripSummary_MobApp]
@bigFleetID bigint = NULL,
@intBoxID varchar(max) = NULL,
@dtStartDate datetime = NULL,
@dtEndDate datetime = NULL,
@bigOrganizationID bigint = NULL,
@bigQueryingUser bigint = NULL
AS
/******************************************************************************************************************/        
-- Name			: rvlf_sp_GetTripSummary_MobApp 8,999987,'2013-03-22 08:45:00 PM', '2013-03-23 08:00:00 AM',6,94        
--				: rvlf_sp_GetTripSummary_MobApp 8,999998,'2013-04-24 08:00:00 AM', '2013-04-24 08:00:00 PM',6,94				
-- Created Date	: 18-Mar-2013
-- Created By	: Sakthi
-- Description	: To get the trip summary details        
/******************************************************************************************************************/ 
BEGIN
SET NOCOUNT ON   
	DECLARE @Lang varchar(50)     
	SELECT @Lang=isnull(Lang,'LanguageEn') FROM dbo.rvlfUserPreferences WHERE UserId = @bigQueryingUser  
         
	DECLARE @dtFDate DATETIME =@dtStartDate      
	DECLARE @dtEDate DATETIME =@dtEndDate      
	DECLARE @FleetName varchar(150) = NULL
	IF @bigFleetID IS NULL        
	BEGIN        
		SELECT @bigFleetID=FleetID FROM dbo.rvlfFleet WHERE OrganizationId=@bigOrganizationID AND IsDefault=1        
	END        
	SELECT @FleetName=FleetName FROM dbo.rvlfFleet WHERE FleetId=@bigFleetID
	DECLARE @HoursToBeAdded INT = 0        
	DECLARE @MinsToBeAdded INT = 0        
	DECLARE @ConversionFactor numeric (10,2) = 1.0        
	DECLARE @DistanceCaptionPrefix varchar(15)        
	DECLARE @SpeedCaptionPrefix varchar(15)      
	DECLARE @DefaultDateFormat INT = 0;      
	DECLARE @Hours varchar(max) = 0
	DECLARE @Minutes INT = 0
	DECLARE @Sign char =0
	DECLARE @ToDate Datetime = NULL 
	DECLARE @FromDate Datetime = NULL

	DECLARE @tblTripDetailsForMobileDevices TABLE
	(        
		Sno int IDENTITY(1,1) NOT NULL,        
		BoxId int NOT NULL,        
		OriginDateTime datetime NOT NULL,        
		Odometer bigint NOT NULL,        
		StreetAddress nvarchar(300) NULL,        
		Speed int NULL,        
		Lat numeric(10,6),        
		Long numeric(10,6),
		FleetId int,
		FleetName varchar(50),
		VehicleId int,
		VehicleDescription varchar(30),
		Vin varchar(30),
		LicensePlate varchar(30),
		ReportInterval int,
		PollingFreq int,
		ChangingFreq int,
		BatteryPercentage tinyint,
		BoxMsgInTypeId int,
		BoxMsgInTypeDesc varchar(250)
	)      

	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,
	@DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)        
	FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz        
	ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser       
  
	SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))        
	SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))    

	INSERT INTO @tblTripDetailsForMobileDevices (FleetId,FleetName,BoxId,VehicleId,VehicleDescription,Vin,LicensePlate,OriginDateTime,
	Speed,BoxMsgInTypeId,BoxMsgInTypeDesc,ReportInterval,PollingFreq,ChangingFreq,BatteryPercentage,Odometer,StreetAddress)
	SELECT @bigFleetID,@FleetName,h.BoxId,v.VehicleId,v.VehicleDescription,v.Vin,v.LicensePlate,h.OriginDateTime,
	CEILING(CAST((ABS(ISNULL(h.Speed, 0)) * @ConversionFactor) as varchar(20))) AS Speed,--	h.Speed,
	h.BoxMsgInTypeId,CASE 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 
	SUBSTRING(h.CustomProp,CHARINDEX('AlarmMsg=',h.CustomProp,0)+9,LEN(h.CustomProp)-(CHARINDEX(h.CustomProp,'AlarmMsg=',0)+9)) 
	ELSE Bm.BoxMsgInTypeDesc END ,
	--CASE WHEN (SELECT ISNULL(COUNT(*),0) FROM dbo.rvlfAlarm a WHERE a.BoxId=h.BoxId AND a.DateTimeCreated=h.OriginDateTime AND 
	--a.Lat = h.Latitude AND a.Long=h.Longitude)=1 THEN
	--(SELECT TOP 1 [Description] FROM dbo.rvlfAlarm al WHERE al.BoxId=h.BoxId AND al.DateTimeCreated=h.OriginDateTime AND al.Lat = h.Latitude AND al.Long=h.Longitude)
	--ELSE Bm.BoxMsgInTypeDesc END,
	ap.RptInterval,ap.Pollingfreq,ap.ChangingFreq,ap.BattPercentage,CEILING(CAST((ABS(ISNULL(h.Odometer, 0)) * @ConversionFactor) as varchar(20))) AS Odometer,
	--h.odometer,
	CASE WHEN ISNULL(h.LandMarkID,0) <> 0 THEN 
	(SELECT LandmarkName FROM rvlfLandmark WHERE OrganizationId=@bigOrganizationID AND LandmarkID=h.LandMarkID) ELSE
	ISNULL(h.StreetAddress,'NA') END
	FROM dbo.rvlfMsgInHst h INNER JOIN dbo.rvlfVehicleAssignment va ON va.BoxId=h.BoxId
	INNER JOIN dbo.rvlfVehicle v ON v.VehicleId=va.VehicleId
	INNER JOIN dbo.rvlfFleetVehicles fv On fv.VehicleId=v.VehicleId
	INNER JOIN dbo.rvlfFleet f ON f.FleetId = fv.FleetId
	INNER JOIN dbo.rvlfBoxMsgInType Bm ON Bm.BoxMsgInTypeId=h.BoxMsgInTypeId
	INNER JOIN dbo.rvlfModelBoxSettings_App st ON st.BoxID=h.BoxId
	INNER JOIN dbo.rvlfModel_App ap ON ap.ModelId=st.ModelId
	WHERE (@bigFleetID IS NULL OR @bigFleetID ='' OR f.FleetId=@bigFleetID) AND
	(@intBoxID IS NULL OR @intBoxID = '0' OR @intBoxID = '' OR va.BoxId IN (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND 
	h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND
	v.OrganizationId=@bigOrganizationID

	SELECT MD.FleetId,MD.FleetName,MD.BoxId,MD.VehicleId,MD.VehicleDescription,MD.Vin,--Md.StreetAddress,
	MD.LicensePlate,MD.OriginDateTime AS OriginDateTimeSort,MD.Speed,MD.BoxMsgInTypeId,MD.BoxMsgInTypeDesc,
	Convert(varchar,MD.OriginDateTime,@DefaultDateFormat)  as StartDate,
	MD.ReportInterval,MD.PollingFreq,MD.ChangingFreq,MD.BatteryPercentage,MD.Odometer,A.MinOdometer,A.MaxOdometer,
	Distance = (ISNULL(A.MaxOdometer,0) - ISNULL(A.MinOdometer,0)),CASE WHEN LEN(ISNULL(MD.StreetAddress,'-')) =0 THEN 'Address could not be resolved' ELSE ISNULL(MD.StreetAddress,'NA') END AS StreetAddress,
	OdoStartEnd = CAST(ISNULL(A.MinOdometer,0) AS VARCHAR)+' - '+CAST(ISNULL(A.MaxOdometer,0) AS VARCHAR),
	OriginDateTime = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,MD.OriginDateTime),
	@DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,  
	CONVERT(VARCHAR,@dtFDate,@DefaultDateFormat) + ' ' + CONVERT(VARCHAR,CAST(@dtFDate AS TIME),22) AS PasStartDate,
	CONVERT(VARCHAR,@dtEDate,@DefaultDateFormat)+  ' ' + CONVERT(VARCHAR,CAST(@dtEDate AS TIME),22) AS PasEndDate,  
	dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()) AS PasGenerateddate
	FROM @tblTripDetailsForMobileDevices MD INNER JOIN (SELECT BoxId,MIN(Odometer) AS MinOdometer,MAX(Odometer) AS MaxOdometer
	FROM @tblTripDetailsForMobileDevices GROUP BY BoxId) A ON A.BoxId=MD.BoxId
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTripSummary_Opt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetTripSummary_Opt]                
 @bigFleetID bigint = null,                
 @intBoxID varchar(max) = null,                
 @dtStartDate datetime = null,                
 @dtEndDate datetime = null,                
 @bitTripStatus bit = 1,              
 @bigOrganizationID bigint = null,                
 @bigQueryingUser bigint = 0                
AS                
/******************************************************************************/                
-- Name  : rvlf_sp_GetTripSummary_opt 186,NULL, '2015/01/06 02:00:00 AM', '2015/01/06 08:00:00 PM',1, 121,502    
-- Description : To get the trip summary details                
--    :   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin                
-- Author  : V.Narayanasamy                
-- Company  : Angler Technologies                
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                
--    : 01-Apr-2011 VN Created Intial Version               
--    : 09-Aug-2011 Ranjith Date format Included                
--    : 30-Nov-2011 Sakthi Distance calculation based on Organization      
--   : 07-Jan-2013 Sakthi Sensor num changed for trip details - MFC organization           
--   : 18-Sep-2013 Sakthi idling, running and stop time in mins for chart    
/******************************************************************************/                
                
BEGIN                
                  
 SET NOCOUNT ON                  
 Declare @dtFDate datetime =@dtStartDate              
 Declare @dtEDate datetime =@dtEndDate              
 IF @bigFleetID IS NULL                
  BEGIN                
   SELECT @bigFleetID=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)              
 DECLARE @DefaultDateFormat INT = 0;     
  DECLARE @Lang varchar(50),  @LangSetting varchar(20)      
                   
    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,@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                
                 
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                
                 
 Create TABLE #tblTripDetailsForTD (                
  [TripId] [bigint]IDENTITY(1,1) NOT NULL,                
  [BoxId] [int] NOT NULL,                
  [StartDate] [datetime] NOT NULL,                
  [EndDate] [datetime] NULL,                
  [OdometerStart] [bigint] NOT NULL,                
  [OdometerEnd] [bigint] NULL,                
  [IsTripClosed] [bit] NULL,                
  [IdlingDuration] [int] NULL,                
  [StopTime] [int] NULL,                
  [StartAddress] nvarchar(300) NULL,                
  [EndAddress] nvarchar(300) NULL,                
  [Speed] int NULL,        
  [AvgSpeed] int NULL,             
  [RunningTime] int null,                
  StartLat numeric(10,6),    
  StartLong numeric(10,6),                
  StopLat numeric(10,6),                
  StopLong numeric(10,6)                
                  
 )                
                 
 Create Table #TBLSTART                 
 (                
  Processid bigint identity(1,1),                
  Boxid int,                
  StartTime datetime,                
  OdoStart bigint,                
  StartAddress nvarchar(300),                
  Running int,                
  idling int,                
  Speed int,        
  AvgSpeed int,            
  StopInterval int,                
  tripId int,                
  Lat numeric(10,6),                
  Long numeric(10,6)                
 )                
                 
 Create Table #TBLSTOP            
 (                
  Boxid int,                
  StopTime datetime,                
  OdoEnd bigint,                
  EndAddress nvarchar(300),                
  tripId int,                
  Lat numeric(10,6),                
  Long numeric(10,6),                
 IsTripCompleted bit                
 )                 
                
 DECLARE @intDuration int                
 DECLARE @dtOriginDateTime datetime                
 DECLARE @bigOdoMeterReading int                
 DECLARE @bitIgnitionStatus bit              
 DECLARE @vcStreetAddress nvarchar(250)                
 DECLARE @tiBoxMsgInTypeId tinyint                
 DECLARE @bigTripID bigint                
 DECLARE @intIterator int                
DECLARE @canShowFuelMessage bit = 0                
                 
 IF EXISTS (SELECT * FROM rvlfPackageOperations r                
  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId                
  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId                
  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)                
   BEGIN                
    SET @canShowFuelMessage = 1                
   END                
                
 Create Table #tblMessageForProcessingTrip (                
  [OriginDateTime] [datetime] NOT NULL,                
  [BoxMsgInTypeId] [tinyint] NULL,                
  [CustomProp] [varchar](600) NULL,                  
  [Speed] int NULL,                
  [Ignition] bit null,                  
  [Address] nvarchar(300) null,                
  [OdoMeter] bigint null,                
  Lat numeric(10,6),                
  Long numeric(10,6)                
 )                
                
 DECLARE @tblBoxes TABLE (BoxID int unique)                
                  
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va                 
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                
   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='0' OR @intBoxID='' or BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID                
   ORDER BY BoxId                 
                
 DECLARE @intBoxLooping int                
                 
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes                
 WHILE @intBoxLooping IS NOT NULL                
   BEGIN                 
    -- GET THE MSGS FOR THE BOXID                
    DELETE FROM #tblMessageForProcessingTrip                     
    INSERT INTO #tblMessageForProcessingTrip(OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,OdoMeter,Lat,Long)                
      SELECT  h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,    
      CASE WHEN @bigOrganizationID=23 AND BoxMsgInTypeId=2 AND CustomProp like 'SENSOR_NUM=2;%' THEN 1 ELSE CAST(SUBSTRING(sensormask,6,1) as bit) END,    
      --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 (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 L.LandmarkName END,                
   --   Replace(ISNULL( (    
   --   Case WHEN @Lang='LanguageArNew' THEN ISNULL(H.StreetAddress_AR,H.StreetAddress)     
   --When @Lang='LanguageHindi' THEN ISNULL(H.StreetAddress_Hin,H.StreetAddress)     
   --ELSE H.StreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress,     
      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.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
        ORDER BY h.origindatetime ASC                 
                        
    -- GET THE IGNITION ON DETAILS                
    DELETE FROM #TBLSTART                     
    INSERT INTO #TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                 
     FROM #tblMessageForProcessingTrip                       
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                 
      AND BoxMsgInTypeId IN(2)                
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip                 
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip                 
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                  
      AND Ignition=1 AND CustomProp LIKE '%SENSOR_NUM=3%'                
                       
                     
    --GET THE IGNITION OFF DETAILS                   
    DELETE FROM #TBLSTOP                 
    INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)                
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                    
     FROM #tblMessageForProcessingTrip                  
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                 
      AND BoxMsgInTypeId IN(3)                
      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip                 
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip                 
       WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                  
       AND CustomProp LIKE '%SENSOR_NUM=3%'    
                    
    --CHECK THE ONGOING TRIPS                 
    --IF ((SELECT TOP 1 BoxMsgInTypeId FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) ORDER BY OriginDateTime DESC)=2)                
    -- BEGIN                
    --  INSERT INTO #TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                
    --   SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                 
    --    FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC                     
    -- IF EXISTS(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)          
    --    AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                
    --    FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC)                        
    --  BEGIN                        
    --   INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long,IsTripCompleted)                
    --    --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,OdoMeter,Address,Lat,Long,0                 
    --    SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long,0                 
    --    FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                
    --     AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                
    --     FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC                
    --  END                 
    -- ELSE                
    --  BEGIN                
    --   INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)                
    --    --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                         
    --    SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                         
    --  END                  
    -- END                
                         
    --PREPARE THE TRIPS AND DETAILS                    
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM #TBLSTART )                 
    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 #TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                    
                      
      IF @DTSTOPSTART IS NOT NULL                         
       UPDATE top(1) #TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART                 
                      
      SET @DTSTOPSTART=@DTSTART                 
      SET @DTEND=NULL                
      SELECT TOP 1 @DTEND=StopTime   FROM #TBLSTOP WHERE StopTime >@DTSTART                 
                      
      UPDATE top(1) #TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART                 
      UPDATE top(1) #TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND                  
      UPDATE top(1) #TBLSTART SET Speed =(SELECT MAX(SPEED) FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),                
      --AvgSpeed =     
      --(SELECT CASE WHEN ((CAST(DATEDIFF(SECOND,MIN(OriginDateTime),MAX(OriginDateTime)) AS DECIMAL(8,2)) * 60.00) /3600.00) = 0 THEN 0 ELSE     
      --ISNULL(CAST(ROUND((ROUND((CAST((MAX(OdoMeter)-MIN(Odometer)) AS DECIMAL(6,2))*@ConversionFactor),0) / ((DATEDIFF(SECOND,MIN(OriginDateTime),MAX(OriginDateTime))) / 3600.00)),0) AS INT) ,0) END    
      --FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId <> 35 AND OdoMeter <> 0 GROUP BY BoxId),    
      idling=(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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9                 
        AND CustomProp NOT LIKE '%Idling:0;%'),                
       --Running=(SELECT ISNULL(SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,                
       --(CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60,0)                             
       --FROM #tblMessageForProcessingTrip                 
       --WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =3)                
       Running=DATEDIFF(S,@DTSTART,@DTEND)                
       WHERE tripId=@INC AND StartTime=@DTSTART                 
                       
      SET @INC =@INC +1                
                      
      SELECT @LOOP =MIN(Processid) FROM #TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART                
     
     END                 
                           
    --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME                
    UPDATE #TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END                 
     WHERE Running IS NOT NULL                
                    
    --INSERT THE DETAILS IN THE MASTER TABLE                
    INSERT INTO #tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,                
     OdometerEnd,IdlingDuration,Speed,AvgSpeed,IsTripClosed,StopTime,RunningTime,StartLat,StartLong,StopLat,StopLong)                 
    SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,S.idling,                
     S.Speed,S.AvgSpeed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running,S.Lat,S.Long,ST.Lat,ST.Long                
      FROM #TBLSTART S                
       INNER JOIN #TBLSTOP ST ON ST.tripId=S.tripId                          
                     
   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping                
                   
   UPDATE #tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM #tblTripDetailsForTD)           




   
   
       
                   
   END                 
                
               
DECLARE @TBLSUMMARY TABLE                
(                
 Boxid int,                
 RunningTime int,                
 IdlingTime int,                
 StopTime int                
)                
INSERT INTO @TBLSUMMARY (Boxid,RunningTime,IdlingTime,StopTime)                
 SELECT BoxId,SUM(RunningTime),SUM(IdlingDuration),SUM(StopTime) FROM #tblTripDetailsForTD GROUP BY BoxId                 
 -- SELECT BoxId,SUM(RunningTime) over (partition by BoxId),SUM(IdlingDuration) over (partition by BoxId),SUM(StopTime) over (partition by BoxId) FROM #tblTripDetailsForTD                 
 Select              
  --@dtStartDate as PasStartdate,@dtEndDate as PasEnddate,              
  TripId,A.BoxId,cast(Speed as int) as Speed,AvgSpeed,              
  Convert(varchar,StartDate,@DefaultDateFormat)  as StartDate,Convert(varchar,EndDate,@DefaultDateFormat)   as EndDate,                  
  StartDateSort as StartDateSort,--EndDate as EndDate,            
  TripStatus,Duration,TripDuration,                  
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,(case when Cast(OdometerEnd as Int) < Cast(OdometerStart as int) Then 0              
   else (Cast(OdometerEnd as Int)-Cast(OdometerStart as int)) END))) AS Distance,   --Cast(  as decimal(10,3))             
  StartAddress,EndAddress,VIN,LicensePlate,VehicleDescription,MakeName,ModelName,ModelYear,                
  (CASE WHEN IdlingDuration = 0 OR IdlingDuration IS NULL THEN '-' ELSE a.IdlingTime END) IdlingTime,                
  IdlingDuration,StopDuration,a.StopTime,DistanceCaption,SpeedCaption,             
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStart)) AS OdometerStart,            
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerEnd)) AS OdometerEnd,                
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStartReading)) AS OdometerStartReading,OdometerStartReading as OdometerStartReading1,            
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerEndReading)) AS OdometerEndReading, OdometerEndReading as OdometerEndReading1  ,             
  CASE WHEN @bigOrganizationID=23 THEN MFC.Distance_MFC ELSE (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,(case when Cast(OdometerEndReading as Int) 
  < Cast(OdometerStartReading as int) Then 0                 
  ELSE ROUND(OdometerEndReading-OdometerStartReading,0,0) END))) END AS DistanceSummary,                
  dbo.rvlf_fn_getTimeFromSeconds(TS.IdlingTime) AS IdlingSummary,                
  dbo.rvlf_fn_getTimeFromSeconds(TS.RunningTime) as RunningSummary,                
  dbo.rvlf_fn_getTimeFromSeconds(TS.StopTime) as StopSummary,    
  (ISNULL(TS.IdlingTime,0)/60) AS IdlingTimeForChart,    
  (ISNULL(TS.RunningTime,0)/60) AS RunningTimeForChart,    
  (ISNULL(TS.StopTime,0)/60) AS StopTimeForChart,    
  StartLat,StartLong,StopLat,StopLong,Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,            
  Convert(varchar,@dtEDate,@DefaultDateFormat)+' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,            
   PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtEDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())              
  --Convert(varchar,@dtEDate,@DefaultDateFormat)+' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate                 
   from (                
  select t.TripId,                
   CASE WHEN CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))) > 0 AND Speed =0 THEN '-' ELSE CONVERT(VARCHAR,Speed) END Speed,                
   CASE WHEN CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))) > 0 AND t.AvgSpeed =0 THEN '-' ELSE CONVERT(VARCHAR,AvgSpeed) END AvgSpeed,                
   t.BoxId,            
   StartDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,StartDate),              
  EndDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,EndDate),              
  -- CONVERT(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)),@DefaultDateFormat)+ ' ' + CONVERT(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)) as time),22)  as StartDate,               
  -- Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)),@DefaultDateFormat)+ ' ' + Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as time),22) as EndDate,                
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate))  as StartDateSort,               
 --  DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as EndDate,                   
   CASE WHEN IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,                
   dbo.rvlf_fn_getTimeFromSeconds(RunningTime) as Duration,                
   RunningTime as TripDuration,                 
   CEILING((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) )as Distance, -- CAST( as Decimal(10,3))                
   StartAddress,CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END AS EndAddress  , --Vin, LicensePlate, VehDispName as VehicleDescription, MakeName, ModelName,ModelYear,                 
   dbo.rvlf_fn_GetTimeFromSeconds(IdlingDuration) AS IdlingTime, IdlingDuration,                
   CASE WHEN StopTime IS NULL THEN dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SS,EndDate , @dtEndDate))                 
    WHEN StopTime =0 THEN '-'                
    ELSE dbo.rvlf_fn_GetTimeFromSeconds(StopTime) END AS StopDuration,                
   CASE WHEN StopTime IS NULL THEN ABS(DATEDIFF(SS,EndDate ,@dtEndDate)) ELSE StopTime END AS StopTime,                
   @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,                
   CEILING(CAST((ABS(ISNULL(t.OdometerStart, 0)) * @ConversionFactor) as varchar(20)))as OdometerStart,                
   CEILING(CAST((ABS(ISNULL(t.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)))as OdometerEnd,                
   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerStart, 0)) * @ConversionFactor) as varchar(20)),0,0) FROM #tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerStart ASC) As OdometerStartReading,                 
   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)),0,0)FROM #tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerEnd DESC) AS OdometerEndReading,                
   StartLat,StartLong,StopLat,StopLong                    
  FROM #tblTripDetailsForTD t) A                
  INNER JOIN @TBLSUMMARY TS ON TS.Boxid =A.BoxId                 
  INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON A.BoxId = va.BoxId                
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
  LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId                
  LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId    
  INNER JOIN (SELECT AB.BoxId,SUM(ROUND(AB.Distance_MFC,0,0)) AS Distance_MFC FROM     
  (SELECT ts.BoxId,ts.TripId,CAST((MAX(isnull(OdometerEnd,0))-MIN(ISNULL(OdometerStart,0)))* @ConversionFactor as varchar(20))Distance_MFC    
  from #tblTripDetailsForTD ts GROUP BY ts.BoxId,ts.TripId) AB GROUP BY AB.BoxId) MFC ON MFC.BoxId=A.BoxId    
                     
     SELECT VehicleName, CAST(ROUND((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Round(Distance,0))),0) as bigint) AS Distance --Round(Distance,0)Distance            


  
    
     FROM                
     (                
     select v.VehicleDescription VehicleName,                
     CAST((MAX(isnull(OdometerEnd,0))-MIN(ISNULL(OdometerStart,0)))* @ConversionFactor as varchar(20))Distance--,                
    -- CAST((ABS(ISNULL(SUM(OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as numeric(8,2)) as Distance                
     from #tblTripDetailsForTD t                
     INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON t.BoxId = va.BoxId                
     INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
     Group By VehicleDescription  
     )B                
  Where CAST(Distance AS numeric(22,2)) > 0              
      
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTripSummary_Opt_MasterDB]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE  PROCEDURE [dbo].[rvlf_sp_GetTripSummary_Opt_MasterDB]                
 @bigFleetID bigint = null,                
 @intBoxID varchar(max) = null,                
 @dtStartDate datetime = null,                
 @dtEndDate datetime = null,                
 @bitTripStatus bit = 1,              
 @bigOrganizationID bigint = null,                
 @bigQueryingUser bigint = 0                
AS                
/******************************************************************************/                
-- Name  : rvlf_sp_GetTripSummary_Opt_MasterDB 66,NULL, '2/1/2013 8:00:00 AM', '2/28/2013 8:00:00 PM',1, 45,19    
-- Description : To get the trip summary details                
--    :   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin                
-- Author  : V.Narayanasamy                
-- Company  : Angler Technologies                
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                
--    : 01-Apr-2011 VN Created Intial Version               
--    : 09-Aug-2011 Ranjith Date format Included                
--    : 30-Nov-2011 Sakthi Distance calculation based on Organization      
--   : 07-Jan-2013 Sakthi Sensor num changed for trip details - MFC organization           
--   : 18-Sep-2013 Sakthi idling, running and stop time in mins for chart    
/******************************************************************************/                
                
BEGIN                
                  
-- SET NOCOUNT ON                  
-- Declare @dtFDate datetime =@dtStartDate              
-- Declare @dtEDate datetime =@dtEndDate              
-- IF @bigFleetID IS NULL                
--  BEGIN                
--   SELECT @bigFleetID=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)              
-- DECLARE @DefaultDateFormat INT = 0;     
--  DECLARE @Lang varchar(50),  @LangSetting varchar(20)      
                   
--    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,@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                
                 
-- SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                
-- SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                
                 
-- Create TABLE #tblTripDetailsForTD (                
--  [TripId] [bigint]IDENTITY(1,1) NOT NULL,                
--  [BoxId] [int] NOT NULL,                
--  [StartDate] [datetime] NOT NULL,                
--  [EndDate] [datetime] NULL,                
--  [OdometerStart] [bigint] NOT NULL,                
--  [OdometerEnd] [bigint] NULL,                
--  [IsTripClosed] [bit] NULL,                
--  [IdlingDuration] [int] NULL,                
--  [StopTime] [int] NULL,                
--  [StartAddress] nvarchar(300) NULL,                
--  [EndAddress] nvarchar(300) NULL,   
--  [Speed] int NULL,        
--  [AvgSpeed] int NULL,             
--  [RunningTime] int null,                
--  StartLat numeric(10,6),                
--  StartLong numeric(10,6),                
--  StopLat numeric(10,6),                
--  StopLong numeric(10,6)                
                  
-- )                
                 
-- Create Table #TBLSTART                 
-- (                
--  Processid bigint identity(1,1),                
--  Boxid int,                
--  StartTime datetime,                
--  OdoStart bigint,                
--  StartAddress nvarchar(300),                
--  Running int,                
--  idling int,                
--  Speed int,        
--  AvgSpeed int,            
--  StopInterval int,                
--  tripId int,                
--  Lat numeric(10,6),                
--  Long numeric(10,6)                
-- )                
                 
-- Create Table #TBLSTOP            
-- (                
--  Boxid int,                
--  StopTime datetime,                
--  OdoEnd bigint,                
--  EndAddress nvarchar(300),                
--  tripId int,                
--  Lat numeric(10,6),                
--  Long numeric(10,6),                
-- IsTripCompleted bit                
-- )                 
                
-- DECLARE @intDuration int                
-- DECLARE @dtOriginDateTime datetime                
-- DECLARE @bigOdoMeterReading int                
-- DECLARE @bitIgnitionStatus bit              
-- DECLARE @vcStreetAddress nvarchar(250)                
-- DECLARE @tiBoxMsgInTypeId tinyint                
-- DECLARE @bigTripID bigint                
-- DECLARE @intIterator int                
--DECLARE @canShowFuelMessage bit = 0                
                 
-- IF EXISTS (SELECT * FROM rvlfPackageOperations r                
--  INNER JOIN rvlfOrganizationPackage p ON r.PackageId = p.PackageId                
--  INNER JOIN rvlfOrganization g ON p.OrganizationID = g.OrganizationId                
--  WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)                
--   BEGIN                
--    SET @canShowFuelMessage = 1                
--   END                
                
-- Create Table #tblMessageForProcessingTrip (                
--  [OriginDateTime] [datetime] NOT NULL,                
--  [BoxMsgInTypeId] [tinyint] NULL,                
--  [CustomProp] [varchar](600) NULL,                  
--  [Speed] int NULL,                
--  [Ignition] bit null,                  
--  [Address] nvarchar(300) null,                
--  [OdoMeter] bigint null,                
--  Lat numeric(10,6),                
--  Long numeric(10,6)                
-- )                
                
-- DECLARE @tblBoxes TABLE (BoxID int unique)                
                  
-- INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM rvlfVehicleAssignment va                 
--   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
--   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                
--   WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='0' OR @intBoxID='' or BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID                
--   ORDER BY BoxId                 
                
-- DECLARE @intBoxLooping int                
                 
-- SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes                
-- WHILE @intBoxLooping IS NOT NULL                
--   BEGIN                 
--    -- GET THE MSGS FOR THE BOXID                
--    DELETE FROM #tblMessageForProcessingTrip                     
--    INSERT INTO #tblMessageForProcessingTrip(OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,OdoMeter,Lat,Long)                
--      SELECT  h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,    
--      CASE WHEN @bigOrganizationID=23 AND BoxMsgInTypeId=2 AND CustomProp like 'SENSOR_NUM=2;%' THEN 1 ELSE CAST(SUBSTRING(sensormask,6,1) as bit) END,    
--      --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 (H.LandMarkID IS NULL OR H.LandMarkID = 0) THEN           
--  Replace(ISNULL( H.StreetAddress,'Address is not resolved'),'''','\''')    
--  ELSE L.LandmarkName END,                
--   --   Replace(ISNULL( (    
--   --   Case WHEN @Lang='LanguageArNew' THEN ISNULL(H.StreetAddress_AR,H.StreetAddress)     
--   --When @Lang='LanguageHindi' THEN ISNULL(H.StreetAddress_Hin,H.StreetAddress)     
--   --ELSE H.StreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress,     
--      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 FMS_ARCHIVE.dbo.rvlfMsgInHst  H 
--        LEFT OUTER JOIN rvlfLandmark L ON L.LandmarkID=H.LandMarkID                                          
--       WHERE h.BoxID = @intBoxLooping AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate        
--        ORDER BY h.origindatetime ASC                 
                        
--    -- GET THE IGNITION ON DETAILS                
--    DELETE FROM #TBLSTART                     
--    INSERT INTO #TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                
--    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                 
--     FROM #tblMessageForProcessingTrip                       
--     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                 
--      AND BoxMsgInTypeId IN(2)                
--      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip                 
--       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
--      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip                 
--       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                  
--      AND Ignition=1 AND CustomProp LIKE '%SENSOR_NUM=3%'                
                       
                     
--    --GET THE IGNITION OFF DETAILS                   
--    DELETE FROM #TBLSTOP                 
--    INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)                
--    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                    
--     FROM #tblMessageForProcessingTrip                  
--     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                 
--      AND BoxMsgInTypeId IN(3)                
--      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip                 
--       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
--      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip                 
--       WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                  
--       AND CustomProp LIKE '%SENSOR_NUM=3%'    
                    
--    --CHECK THE ONGOING TRIPS                 
--    --IF ((SELECT TOP 1 BoxMsgInTypeId FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) ORDER BY OriginDateTime DESC)=2)                
--    -- BEGIN                
--    --  INSERT INTO #TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                
--    --   SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                 
--    --    FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC                     
--    -- IF EXISTS(SELECT TOP 1 OriginDateTime FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                
--    --    AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                
--    --    FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC)                        
--    --  BEGIN                        
--    --   INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long,IsTripCompleted)                
--    --    --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,OdoMeter,Address,Lat,Long,0                 
--    --    SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long,0                 
--    --    FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                
--    --     AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                
--    --     FROM #tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC                
--    --  END                 
--    -- ELSE                
--    --  BEGIN                
--    --   INSERT INTO #TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)                
--    --    --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                         
--    --    SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                         
--    --  END                  
--    -- END                
                         
--    --PREPARE THE TRIPS AND DETAILS                    
--    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM #TBLSTART )                 
--    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 #TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                    
                      
--      IF @DTSTOPSTART IS NOT NULL                         
--       UPDATE top(1) #TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART                 
                      
--      SET @DTSTOPSTART=@DTSTART                 
--      SET @DTEND=NULL                
--      SELECT TOP 1 @DTEND=StopTime   FROM #TBLSTOP WHERE StopTime >@DTSTART                 
                      
--      UPDATE top(1) #TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART                 
--      UPDATE top(1) #TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND                  
--      UPDATE top(1) #TBLSTART SET Speed =(SELECT MAX(SPEED) FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),                
--      --AvgSpeed =     
--      --(SELECT CASE WHEN ((CAST(DATEDIFF(SECOND,MIN(OriginDateTime),MAX(OriginDateTime)) AS DECIMAL(8,2)) * 60.00) /3600.00) = 0 THEN 0 ELSE     
--      --ISNULL(CAST(ROUND((ROUND((CAST((MAX(OdoMeter)-MIN(Odometer)) AS DECIMAL(6,2))*@ConversionFactor),0) / ((DATEDIFF(SECOND,MIN(OriginDateTime),MAX(OriginDateTime))) / 3600.00)),0) AS INT) ,0) END    
--      --FROM #tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId <> 35 AND OdoMeter <> 0 GROUP BY BoxId),    
--      idling=(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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9                 
--        AND CustomProp NOT LIKE '%Idling:0;%'),                
--       --Running=(SELECT ISNULL(SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,                
--       --(CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60,0)                             
--       --FROM #tblMessageForProcessingTrip                 
--       --WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =3)                
--       Running=DATEDIFF(S,@DTSTART,@DTEND)                
--       WHERE tripId=@INC AND StartTime=@DTSTART                 
                       
--      SET @INC =@INC +1                
                      
--      SELECT @LOOP =MIN(Processid) FROM #TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART                
     
--     END                 
                           
--    --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME                
--    UPDATE #TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END                 
--     WHERE Running IS NOT NULL                
                    
--    --INSERT THE DETAILS IN THE MASTER TABLE                
--    INSERT INTO #tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,                
--     OdometerEnd,IdlingDuration,Speed,AvgSpeed,IsTripClosed,StopTime,RunningTime,StartLat,StartLong,StopLat,StopLong)                 
--    SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,S.idling,                
--     S.Speed,S.AvgSpeed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running,S.Lat,S.Long,ST.Lat,ST.Long                
--      FROM #TBLSTART S                
--       INNER JOIN #TBLSTOP ST ON ST.tripId=S.tripId                          
                     
--   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping                
                   
--   UPDATE #tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM #tblTripDetailsForTD)           

                      
--   END                 
                
               
--DECLARE @TBLSUMMARY TABLE                
--(                
-- Boxid int,                
-- RunningTime int,                
-- IdlingTime int,                
-- StopTime int                
--)                
--INSERT INTO @TBLSUMMARY (Boxid,RunningTime,IdlingTime,StopTime)                
-- SELECT BoxId,SUM(RunningTime),SUM(IdlingDuration),SUM(StopTime) FROM #tblTripDetailsForTD GROUP BY BoxId                 
-- -- SELECT BoxId,SUM(RunningTime) over (partition by BoxId),SUM(IdlingDuration) over (partition by BoxId),SUM(StopTime) over (partition by BoxId) FROM #tblTripDetailsForTD                 
-- Select              
--  --@dtStartDate as PasStartdate,@dtEndDate as PasEnddate,              
--  TripId,A.BoxId,Speed,AvgSpeed,              
--  Convert(varchar,StartDate,@DefaultDateFormat)  as StartDate,Convert(varchar,EndDate,@DefaultDateFormat)   as EndDate,TripStatus,Duration,TripDuration,                  
--  StartDateSort as StartDateSort,--EndDate as EndDate,            
--  TripStatus,Duration,TripDuration,                  
--  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,(case when Cast(OdometerEnd as Int) < Cast(OdometerStart as int) Then 0              
--   else (Cast(OdometerEnd as Int)-Cast(OdometerStart as int)) END))) AS Distance,   --Cast(  as decimal(10,3))             
--  StartAddress,EndAddress,VIN,LicensePlate,VehicleDescription,MakeName,ModelName,ModelYear,                
--  (CASE WHEN IdlingDuration = 0 OR IdlingDuration IS NULL THEN '-' ELSE a.IdlingTime END) IdlingTime,                
--  IdlingDuration,StopDuration,a.StopTime,DistanceCaption,SpeedCaption,             
--  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStart)) AS OdometerStart,            
--  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerEnd)) AS OdometerEnd,                
--  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStartReading)) AS OdometerStartReading,            
--  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerEndReading)) AS OdometerEndReading,                
--  CASE WHEN @bigOrganizationID=23 THEN MFC.Distance_MFC ELSE (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,(case when Cast(OdometerEndReading as Int) < Cast(OdometerSt
--artReading as int) Then 0                 
--  ELSE ROUND(OdometerEndReading-OdometerStartReading,0,0) END))) END AS DistanceSummary,                
--  dbo.rvlf_fn_getTimeFromSeconds(TS.IdlingTime) AS IdlingSummary,                
--  dbo.rvlf_fn_getTimeFromSeconds(TS.RunningTime) as RunningSummary,                
--  dbo.rvlf_fn_getTimeFromSeconds(TS.StopTime) as StopSummary,    
--  (ISNULL(TS.IdlingTime,0)/60) AS IdlingTimeForChart,    
--  (ISNULL(TS.RunningTime,0)/60) AS RunningTimeForChart,    
--  (ISNULL(TS.StopTime,0)/60) AS StopTimeForChart,    
--  StartLat,StartLong,StopLat,StopLong,Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,            
--  Convert(varchar,@dtEDate,@DefaultDateFormat)+' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,            
--   PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtEDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())              
--  --Convert(varchar,@dtEDate,@DefaultDateFormat)+' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(datead
--d(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate                 
--   from (                
--  select t.TripId,                
--   CASE WHEN CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))) > 0 AND Speed =0 THEN '-' ELSE CONVERT(VARCHAR,Speed) END Speed,                
--   CASE WHEN CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))) > 0 AND t.AvgSpeed =0 THEN '-' ELSE CONVERT(VARCHAR,AvgSpeed) END AvgSpeed,                
--   t.BoxId,            
--   StartDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,StartDate),              
--  EndDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,EndDate),              
--  -- CONVERT(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)),@DefaultDateFormat)+ ' ' + CONVERT(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)) as time),22)  as StartDate,               
--  -- Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)),@DefaultDateFormat)+ ' ' + Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as time),22) as EndDate,                
--   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate))  as StartDateSort,               
-- --  DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as EndDate,                   
--   CASE WHEN IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,                
--   dbo.rvlf_fn_getTimeFromSeconds(RunningTime) as Duration,                
--   RunningTime as TripDuration,                 
--   CEILING((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) )as Distance, -- CAST( as Decimal(10,3))                
--   StartAddress,CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END AS EndAddress  , --Vin, LicensePlate, VehDispName as VehicleDescription, MakeName, ModelName,ModelYear,                 
--   dbo.rvlf_fn_GetTimeFromSeconds(IdlingDuration) AS IdlingTime, IdlingDuration,                
--   CASE WHEN StopTime IS NULL THEN dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SS,EndDate , @dtEndDate))                 
--    WHEN StopTime =0 THEN '-'                
--    ELSE dbo.rvlf_fn_GetTimeFromSeconds(StopTime) END AS StopDuration,                
--   CASE WHEN StopTime IS NULL THEN ABS(DATEDIFF(SS,EndDate ,@dtEndDate)) ELSE StopTime END AS StopTime,                
--   @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,                
--   CEILING(CAST((ABS(ISNULL(t.OdometerStart, 0)) * @ConversionFactor) as varchar(20)))as OdometerStart,                
--   CEILING(CAST((ABS(ISNULL(t.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)))as OdometerEnd,                
--   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerStart, 0)) * @ConversionFactor) as varchar(20)),0,0) FROM #tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerStart ASC) As OdometerStartReading,                 
--   (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)),0,0)FROM #tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerEnd DESC) AS OdometerEndReading,                
--   StartLat,StartLong,StopLat,StopLong                    
--  FROM #tblTripDetailsForTD t) A                
--  INNER JOIN @TBLSUMMARY TS ON TS.Boxid =A.BoxId                 
--  INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON A.BoxId = va.BoxId                
--  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
--  LEFT OUTER JOIN rvlfMake mk ON v.MakeId = mk.MakeId                
--  LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId    
--  INNER JOIN (SELECT AB.BoxId,SUM(ROUND(AB.Distance_MFC,0,0)) AS Distance_MFC FROM     
--  (SELECT ts.BoxId,ts.TripId,CAST((MAX(isnull(OdometerEnd,0))-MIN(ISNULL(OdometerStart,0)))* @ConversionFactor as varchar(20))Distance_MFC    
--  from #tblTripDetailsForTD ts GROUP BY ts.BoxId,ts.TripId) AB GROUP BY AB.BoxId) MFC ON MFC.BoxId=A.BoxId    
                     
--     SELECT VehicleName, CAST(ROUND((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Round(Distance,0))),0) as bigint) AS Distance --Round(Distance,0)Distance            

  
    
--     FROM                
--     (                
--     select v.VehicleDescription VehicleName,                
--     CAST((MAX(isnull(OdometerEnd,0))-MIN(ISNULL(OdometerStart,0)))* @ConversionFactor as varchar(20))Distance--,                
--    -- CAST((ABS(ISNULL(SUM(OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as numeric(8,2)) as Distance                
--     from #tblTripDetailsForTD t                
--     INNER JOIN rvlfVehicleAssignment va WITH (NOLOCK) ON t.BoxId = va.BoxId                
--     INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
--     Group By VehicleDescription                
--     )B                
--  Where CAST(Distance AS numeric(22,2)) > 0              
      select 1
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTripSummary_Opt_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetTripSummary_Opt_PhoneGap]  
 @bigFleetID   bigint = null,                
 @intBoxID   varchar(max) = null,                
 @dtStartDate  datetime = null,                
 @dtEndDate   datetime = null,                
 @bitTripStatus  bit = 1,              
 @bigOrganizationID bigint = null,                
 @bigQueryingUser bigint = 0      
AS  
-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: 15-Jun-2015  
-- Description : To get the trip summary details                
--    : Pass the value 0 (Zero) to @bigQueryingUser if the user is AnglerAdmin  
--    rvlf_sp_GetTripSummary_Opt_PhoneGap 8,0,'12/12/2013 9:30:00 AM','12/12/2013 9:30:00 PM',1,6,229   
--    rvlf_sp_GetTripSummary_Opt_PhoneGap 607,7041,'12-Dec-2016 9:30:00 AM','13-Dec-2016 9:30:00 PM',1,310,1601   
-- =============================================  
BEGIN          
  
  DECLARE @Lang varchar(50),  @LangSetting varchar(20)             
  SELECT @Lang = isnull(Lang,'LanguageEn'), @LangSetting = o.OrgLangSettings   
  FROM dbo.rvlfUserPreferences up   
  INNER JOIN rvlfUser u ON u.UserId = up.UserId  
  INNER  JOIN rvlfOrganization o ON o.OrganizationId = u.OrganizationId   
  WHERE up.UserId = @bigQueryingUser          
                 
 SET NOCOUNT ON  
   
  DECLARE @dtFDate    Datetime = @dtStartDate              
  DECLARE @dtEDate    Datetime = @dtEndDate       
  DECLARE @HoursToBeAdded  Int = 0                
  DECLARE @MinsToBeAdded   Int = 0                
  DECLARE @ConversionFactor  Numeric (10,2) = 1.0                
  DECLARE @DistanceCaptionPrefix Varchar(15)                
  DECLARE @SpeedCaptionPrefix Varchar(15)              
  DECLARE @DefaultDateFormat  Int = 0;              
  DECLARE @Hours     Varchar(MAX) = 0        
  DECLARE @Minutes    Int = 0        
  DECLARE @Sign     Char =0        
  DECLARE @ToDate    Datetime = NULL         
  DECLARE @FromDate    Datetime = NULL          
    
  IF @bigFleetID IS NULL                
  BEGIN                
  SELECT @bigFleetID = FleetID FROM dbo.rvlfFleet  
  WHERE OrganizationId = @bigOrganizationID AND IsDefault = 1  
  END        
          
  SELECT @HoursToBeAdded = tz.HoursToBeAdded, @MinsToBeAdded = tz.MinToBeAdded,        
   -- @Hours= HOURS,@ToDate = ToDate, @FromDate = FromDate,        
   -- @Sign = SUBSTRING(Hours,1,1), @Minutes = SUBSTRING(Hours,5,2),        
   @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,@DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)                
  FROM dbo.rvlfUserPreferences up   
  INNER JOIN dbo.rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser               
                       
  SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                
  SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))     
  
  DECLARE @tblTripDetailsForTD TABLE  
  (                
    [TripId] [bigint]IDENTITY(1,1) NOT NULL,                
    [BoxId] [int] NOT NULL,                
    [StartDate] [datetime] NOT NULL,                
    [EndDate] [datetime] NULL,                
    [OdometerStart] [bigint] NOT NULL,                
    [OdometerEnd] [bigint] NULL,                
    [IsTripClosed] [bit] NULL,                
    [IdlingDuration] [int] NULL,              
    [StopTime] [int] NULL,                
    [StartAddress] nvarchar(300) NULL,                
    [EndAddress] nvarchar(300) NULL,                
    [Speed] int NULL,                
    [RunningTime] int null,  
    StartLat numeric(10,6),                
    StartLong numeric(10,6),                
    StopLat numeric(10,6),          
    StopLong numeric(10,6)  
  )  
   DECLARE @TBLSTART TABLE                
  (                
   Processid bigint identity(1,1),                
   Boxid int,                
   StartTime datetime,                
   OdoStart bigint,             
   StartAddress nvarchar(300),                
   Running int,                
   idling int,                
   Speed int,                
   StopInterval int,                
   tripId int,                
   Lat numeric(10,6),                
   Long numeric(10,6)                
  )                
                  
  DECLARE @TBLSTOP TABLE                
  (                
   Boxid int,                
   StopTime datetime,                
   OdoEnd bigint,                
   EndAddress nvarchar(300),                
   tripId int,                
   Lat numeric(10,6),                
   Long numeric(10,6),                
   IsTripCompleted bit                
  )  
    
  DECLARE @intDuration int                
  DECLARE @dtOriginDateTime datetime                
  DECLARE @bigOdoMeterReading int                
  DECLARE @bitIgnitionStatus bit                
  DECLARE @vcStreetAddress nvarchar(250)                
  DECLARE @tiBoxMsgInTypeId tinyint                
  DECLARE @bigTripID bigint                
  DECLARE @intIterator int                
  DECLARE @canShowFuelMessage bit = 0                
                  
  IF EXISTS (SELECT PackageOrgId  FROM dbo.rvlfPackageOperations r                
   INNER JOIN dbo.rvlfOrganizationPackage p ON r.PackageId = p.PackageId                
   INNER JOIN dbo.rvlfOrganization g ON p.OrganizationID = g.OrganizationId                
   WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)                
    BEGIN                
  SET @canShowFuelMessage = 1                
    END   
     
   DECLARE @tblMessageForProcessingTrip TABLE (                
  [OriginDateTime] [datetime] NOT NULL,                
  [BoxMsgInTypeId] [tinyint] NULL,                
  [CustomProp] [varchar](600) NULL,                  
  [Speed] int NULL,                
  [Ignition] bit null,                  
  [Address] nvarchar(300) null,                
  [OdoMeter] bigint null,                
  Lat numeric(10,6),                
  Long numeric(10,6)                
 )    
    
 DECLARE @tblBoxes TABLE (BoxID int)                
                  
 INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM dbo.rvlfVehicleAssignment va                 
    INNER JOIN dbo.rvlfVehicle v ON va.VehicleId = v.VehicleId                
    INNER JOIN dbo.rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                
    WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID=0 or @intBoxID='' or BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID                
    ORDER BY BoxId     
    
 DECLARE @intBoxLooping int                
                 
 SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes   
      
  WHILE @intBoxLooping IS NOT NULL                
   BEGIN                 
    -- GET THE MSGS FOR THE BOXID                
    DELETE FROM @tblMessageForProcessingTrip                     
    INSERT INTO @tblMessageForProcessingTrip(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 (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 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 dbo.rvlfMsgInHst H                
        LEFT OUTER JOIN dbo.rvlfLandmark L ON L.LandmarkID=H.LandMarkID                                          
       WHERE h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                          
          AND h.BoxID = @intBoxLooping                          
        ORDER BY h.origindatetime ASC                 
                        
    -- GET THE IGNITION ON DETAILS                
    DELETE FROM @TBLSTART                     
    INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                 
     FROM @tblMessageForProcessingTrip                       
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                 
      AND BoxMsgInTypeId IN(2)                
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                  
      AND Ignition=1                
      AND CustomProp LIKE '%SENSOR_NUM=3%'                
                       
                     
    --GET THE IGNITION OFF DETAILS                   
    DELETE FROM @TBLSTOP                 
    INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)                
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                    
     FROM @tblMessageForProcessingTrip                  
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                 
      AND BoxMsgInTypeId IN(3)                
      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                 
       WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                  
      AND CustomProp LIKE '%SENSOR_NUM=3%'                
                    
    --CHECK THE ONGOING TRIPS                 
    IF ((SELECT TOP 1 BoxMsgInTypeId FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) ORDER BY OriginDateTime DESC)=2)                
     BEGIN                
      INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                
       SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                 
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC                     
     IF EXISTS(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                
        AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC)                        
      BEGIN                        
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long,IsTripCompleted)              
        --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,OdoMeter,Address,Lat,Long,0                 
        SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long,0                 
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                
         AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                
         FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE '%SENSOR_NUM=3%' ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC                
      END                 
     ELSE                
      BEGIN                
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)                
        --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                         
        SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                         
      END                  
     END                
                         
    --PREPARE THE TRIPS AND DETAILS                    
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )                 
    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 @TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                    
                      
      IF @DTSTOPSTART IS NOT NULL                         
       UPDATE top(1) @TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART                 
                      
      SET @DTSTOPSTART=@DTSTART                 
      SET @DTEND=NULL                
      SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART                 
                      
      UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART                 
      UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND                  
      UPDATE top(1) @TBLSTART SET Speed =(SELECT MAX(SPEED) FROM @tblMessageForProcessingTrip WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),                
      idling=(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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9                 
        AND CustomProp NOT LIKE '%Idling:0;%'),                
       --Running=(SELECT ISNULL(SUM(CAST(SUBSTRING(CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16,                
       --(CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,0))-(CHARINDEX('SENSOR_DURATION=',CustomProp,0)+16))) AS INT))*60,0)                             
       --FROM @tblMessageForProcessingTrip                 
       --WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =3)                
       Running=DATEDIFF(S,@DTSTART,@DTEND)                
       WHERE tripId=@INC AND StartTime=@DTSTART                 
                       
      SET @INC =@INC +1                
          
      SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART                
                      
     END                 
                           
     --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME                
     UPDATE @TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END                 
     WHERE Running IS NOT NULL      
       
     --INSERT THE DETAILS IN THE MASTER TABLE                
     INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,                
          OdometerEnd,IdlingDuration,Speed, IsTripClosed,StopTime,RunningTime,StartLat,StartLong,StopLat,StopLong)                 
     SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,S.idling,                
     S.Speed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,S.StopInterval,S.Running,S.Lat,S.Long,ST.Lat,ST.Long                
      FROM @TBLSTART S                
       INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId                          
                     
   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping                
                   
   UPDATE @tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM @tblTripDetailsForTD)           




 
 
       
     END  
       
  DECLARE @TBLSUMMARY TABLE                
  (                
    Boxid int,                
    RunningTime int,                
    IdlingTime int,                
    StopTime int                
  )  
    
   INSERT INTO @TBLSUMMARY (Boxid,RunningTime,IdlingTime,StopTime)  
   SELECT BoxId,SUM(RunningTime),SUM(IdlingDuration),SUM(StopTime)  
   FROM @tblTripDetailsForTD  
   GROUP BY BoxId  
     
   -- SELECT BoxId,SUM(RunningTime) over (partition by BoxId),SUM(IdlingDuration) over (partition by BoxId),SUM(StopTime) over (partition by BoxId) FROM @tblTripDetailsForTD                 
   SELECT --@dtStartDate as PasStartdate,@dtEndDate as PasEnddate,              
    ---TripId,A.BoxId,Speed,              
    ---Convert(varchar,StartDate,@DefaultDateFormat)  as StartDate,Convert(varchar,EndDate,@DefaultDateFormat) as EndDate,TripStatus,Duration,TripDuration,                  
    ---StartDateSort as StartDateSort,--EndDate as EndDate,  
    --TripStatus,Duration,TripDuration,  
    ---(SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,          
    ---  (case when Cast(OdometerEnd as Int) < Cast(OdometerStart as int) Then 0                 
    ---  else Cast((Cast(OdometerEnd as Int)-Cast(OdometerStart as int)) as nvarchar(20)) END))) AS 'Distance',                 
      ---StartAddress,EndAddress,VIN,LicensePlate, (case when @Lang='LanguageArNew' then isnull(VehicleDescription_Ar,VehicleDescription) else VehicleDescription end) as VehicleDescription,--,MakeName,ModelName,ModelYear,                
      ---(CASE WHEN IdlingDuration = 0 OR IdlingDuration IS NULL THEN '-' ELSE a.IdlingTime END) IdlingTime,                
      ---IdlingDuration,StopDuration,a.StopTime,  
                
      ---(SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStart)) AS OdometerStart,          
      ---(SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerEnd)) AS OdometerEnd,                
        
    distinct v.VehicleDescription,Cast((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID, 
    (case when Cast(OdometerEndReading as Int) < Cast(OdometerStartReading as int) Then 0                 
    ELSE ROUND(OdometerEndReading-OdometerStartReading,0,0) END))) as INT) AS DistanceSummary,DistanceCaption,SpeedCaption,             
    dbo.rvlf_fn_getTimeFromSeconds(ISNULL(TS.IdlingTime,0)) as IdlingSummary,                
    dbo.rvlf_fn_getTimeFromSeconds(ISNULL(TS.RunningTime,0)) as RunningSummary,                
    dbo.rvlf_fn_getTimeFromSeconds(ISNULL(TS.StopTime,0)) as StopSummary,  
    (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerStartReading)) AS OdometerStartReading,          
    (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,OdometerEndReading)) AS OdometerEndReading,                    
    (ISNULL(TS.IdlingTime,0)/60) AS IdlingTimeForChart,        
    (ISNULL(TS.RunningTime,0)/60) AS RunningTimeForChart,        
    (ISNULL(TS.StopTime,0)/60) AS StopTimeForChart         
    --,StartLat,StartLong,StopLat,StopLong           
    ,Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+          
    ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,          
    PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()) ,         
    --Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate     




 
	(select  max(TripId) from @tblTripDetailsForTD ) as NoofTrips

     
    FROM (                
    SELECT ---t.TripId, CASE WHEN CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))) > 0 AND Speed =0 THEN '-' ELSE CONVERT(VARCHAR,Speed) END Speed,                
      t.BoxId, ---StartDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,StartDate),          
    ---  EndDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,EndDate),          
    ---  --CONVERT(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)),@DefaultDateFormat)+ ' ' + CONVERT(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate)) as time),22)  as StartDate,               
    ---  --Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)),@DefaultDateFormat)+ ' ' + Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as time),22) as EndDate,                
    ---  DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,StartDate))  as StartDateSort,               
    ---  --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,EndDate)) as EndDate,                   
    ---  CASE WHEN IsTripClosed = 1 THEN 'Completed' ELSE 'Ongoing' END as TripStatus,                
    ---  dbo.rvlf_fn_getTimeFromSeconds(RunningTime) as Duration,                
    ---  RunningTime as TripDuration,                 
    ---  CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20)))as Distance,                 
    ---  StartAddress,CASE WHEN IsTripClosed = 1 THEN EndAddress ELSE 'Ongoing Trip' END AS EndAddress  , --Vin, LicensePlate, VehDispName as VehicleDescription, MakeName, ModelName,ModelYear,                 
      dbo.rvlf_fn_GetTimeFromSeconds(IdlingDuration) AS IdlingTime, IdlingDuration,                
      CASE WHEN StopTime IS NULL THEN dbo.rvlf_fn_GetTimeFromSeconds(DATEDIFF(SS,EndDate , @dtEndDate))                 
      WHEN StopTime =0 THEN '-'    
    ELSE dbo.rvlf_fn_GetTimeFromSeconds(StopTime) END AS StopDuration,                
      CASE WHEN StopTime IS NULL THEN ABS(DATEDIFF(SS,EndDate ,@dtEndDate)) ELSE StopTime END AS StopTime,                
      @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,                
      CEILING(CAST((ABS(ISNULL(t.OdometerStart, 0)) * @ConversionFactor) as varchar(20)))as OdometerStart,                
      CEILING(CAST((ABS(ISNULL(t.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)))as OdometerEnd,                
      (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerStart, 0)) * @ConversionFactor) as varchar(20)),0,0)   
       FROM @tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerStart ASC) As OdometerStartReading,                 
      (SELECT TOP 1 ROUND(CAST((ABS(ISNULL(tt.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)),0,0)  
       FROM @tblTripDetailsForTD tt WHERE tt.BoxId = t.BoxId ORDER BY OdometerEnd DESC) AS OdometerEndReading,                
      StartLat,StartLong,StopLat,StopLong                    
    FROM @tblTripDetailsForTD t  
   ) A                
  INNER JOIN @TBLSUMMARY TS ON TS.Boxid =A.BoxId                 
  INNER JOIN dbo.rvlfVehicleAssignment va WITH (NOLOCK) ON A.BoxId = va.BoxId                
  INNER JOIN dbo.rvlfVehicle v ON va.VehicleId = v.VehicleId                
  LEFT OUTER JOIN dbo.rvlfMake mk ON v.MakeId = mk.MakeId                
  LEFT OUTER JOIN dbo.rvlfModel md ON v.ModelId = md.ModelId               

DECLARE @TBLTripSummaryChartData TABLE              
(              
 Speed bigint,              
 StartDate datetime,              
 TripDuration bigint,  
 Distance bigint,            
 IdlingDuration bigint              
)              
INSERT INTO @TBLTripSummaryChartData  (Speed, StartDate, TripDuration, Distance,IdlingDuration)
 (Select            
  --@dtStartDate as PasStartdate,@dtEndDate as PasEnddate,            
  Speed,            
  Convert(varchar,StartDate,@DefaultDateFormat)  as StartDate,TripDuration,  
  (SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,        
  (case when Cast(OdometerEnd as Int) < Cast(OdometerStart as int) Then 0               
  else Cast((Cast(OdometerEnd as Int)-Cast(OdometerStart as int)) as nvarchar(20)) END)))        
  AS 'Distance',   
  IdlingDuration
   from (              
  select  Boxid,           
   CASE WHEN CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20))) > 0 AND Speed =0 THEN '-' ELSE CONVERT(VARCHAR,Speed) END Speed,                 
  StartDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,StartDate),          
   
   dbo.rvlf_fn_getTimeFromSeconds(RunningTime) as Duration,              
   RunningTime as TripDuration,               
   CEILING(CAST((ABS(ISNULL((OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as varchar(20)))as Distance,                  
   dbo.rvlf_fn_GetTimeFromSeconds(IdlingDuration) AS IdlingTime, IdlingDuration,   
   CEILING(CAST((ABS(ISNULL(t.OdometerStart, 0)) * @ConversionFactor) as varchar(20)))as OdometerStart,              
   CEILING(CAST((ABS(ISNULL(t.OdometerEnd, 0)) * @ConversionFactor) as varchar(20)))as OdometerEnd              
  FROM @tblTripDetailsForTD t  group by datepart(DD,StartDate),speed,RunningTime,IdlingDuration,OdometerEnd,OdometerStart,StopTime,BoxId,StartDate ) A  
)
   
   Select convert(date,Startdate,106) as DateValueAsc, replace(convert(varchar(20),Startdate,106),' ','-')  as DateValue, max(speed) as Speed,(sum(TripDuration)/60) as RunningTime,sum(Distance) as Distance,ISNULL((sum(IdlingDuration)/60),0)  as IdlingTime
 from @TBLTripSummaryChartData 
   group by replace(convert(varchar(20),Startdate,106),' ','-'),convert(date,Startdate,106)  order by  convert(date,getutcdate(),106) desc
    
--   DECLARE @TBLTripSummaryData TABLE              
--(
--  DateValueAsc date,                                   
-- DateValue varchar(50),              
-- Speed bigint,              
-- RunningTime bigint,  
-- Distance bigint,            
-- IdlingTime bigint              
--)                
            
 --insert into @TBLTripSummaryData (DateValueAsc, DateValue , Speed ,RunningTime ,  Distance, IdlingTime )
 --Select convert(date,Startdate,106) as DateValueAsc, replace(convert(varchar(20),Startdate,106),' ','-')  as DateValue, Avg(speed) as Speed,(sum(TripDuration)/60) as RunningTime,sum(Distance) as Distance,ISNULL((sum(IdlingDuration)/60),0)  as IdlingTime from @TBLTripSummaryChartData 
 --group by replace(convert(varchar(20),Startdate,106),' ','-'),convert(date,Startdate,106)  order by  convert(date,getutcdate(),106) desc
  
 -- Select * from @TBLTripSummaryData order by DateValueAsc asc

                                  
                     
  ---   SELECT VehicleName, CAST(ROUND((SELECT CASE WHEN OrgDistIncPercentValue >= 1 THEN Distance ELSE Distance END   
---        FROM dbo.rvlf_fn_GetDistanceBasedOrg(@bigOrganizationID,Round(Distance,0))),0) as bigint) AS Distance          
  ---   FROM                
  ---   (                
  --- select v.VehicleDescription VehicleName,                
  --- CAST((MAX(isnull(OdometerEnd,0))-MIN(ISNULL(OdometerStart,0)))* @ConversionFactor as varchar(20))Distance--,                
  ---- CAST((ABS(ISNULL(SUM(OdometerEnd-OdometerStart), 0)) * @ConversionFactor) as numeric(8,2)) as Distance                
  --- from @tblTripDetailsForTD t                
  --- INNER JOIN dbo.rvlfVehicleAssignment va WITH (NOLOCK) ON t.BoxId = va.BoxId                
  --- INNER JOIN dbo.rvlfVehicle v ON va.VehicleId = v.VehicleId                
  --- Group By VehicleDescription                
  ---) B                
  ---WHERE CAST(Distance AS numeric(22,2)) > 0          
    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTyreDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

          
CREATE PROCEDURE [dbo].[rvlf_sp_GetTyreDetails]           
@TyreID int = Null,                        
@bigOrganizationId bigint = Null,                        
@bigUserId bigint = Null                     
          
AS          
-- =============================================          
-- Name   : rvlf_sp_GetTyreDetails 9,6,18     
-- Author  : Kapil          
-- Create date : 19-Feb-2014          
-- Description : Get Tyre Details          
-- Company  : TRINETRA 
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
-- =============================================          
BEGIN          
 -- SET NOCOUNT ON added to prevent extra result sets from          
 -- interfering with SELECT statements.          
 SET NOCOUNT ON;          
 
  IF @TyreID = 0 SET @TyreID = null 
  IF @TyreID is not null   
   
  BEGIN    
    -- Insert statements for procedure here          
   
 -- 	select TyreId,VendorId,'TR'+ CAST(TyreId as Varchar) as TyreCode,BrandID,replace(convert(varchar(20),DateOfPurchase,106 ),' ','-') as DateOfPurchase,TyreBillNo,Quantity,CAST(TyreCost as VARCHAR(20)) as  TyreCost,
 -- 	CAST(TotalAmount as varchar(20)) as TotalAmount,TyreSize,TyreWidth,ModelID,TyreLifetime,TyreCategory,Warranty,used from rvlfTyreMaster       	
	--where IsDelete=0 and TyreId=@TyreID AND OrganizationId = @bigOrganizationId
	
	select M.TyreId,M.VendorId,'TR'+ CAST(M.TyreId as Varchar) as TyreCode,M.BrandID,replace(convert(varchar(20),
  	DateOfPurchase,106 ),' ','-') as DateOfPurchase, TyreBillNo,Quantity,CAST(TyreCost as VARCHAR(20)) as  TyreCost,
  	CAST(TotalAmount as varchar(20)) as TotalAmount,TyreSize,TyreWidth,M.ModelID,TyreLifetime,TyreCategory,Warranty,ISNULL(S.UsedQuantity,0) as UsedQuantity	
  	from rvlfTyreMaster M left JOIN rvlfTyreStock S on S.TyreID = M.TyreId        	
	where IsDelete=0 and M.TyreId=@TyreID AND M.OrganizationId = @bigOrganizationId
	
  END
  
  ELSE
  
  BEGIN
	
	--CASE WHEN VendorState='' THEN '-' ELSE VendorState END as VendorState,
	--CASE WHEN ZipCode='' THEN '-' ELSE ZipCode END as ZipCode
	Select TyreId, 'TR'+ CAST(TyreId as Varchar) as TyreCode,T.VendorId,VM.VendorName,TMak.BrandName,replace(convert(varchar(20),DateOfPurchase,106 ),' ','-') as DateOfPurchase ,
	TyreBillNo,Quantity,CAST(TyreCost as VARCHAR(20)) TyreCost,TyreCost as Cost,CAST(TotalAmount as varchar(20)) Total,TotalAmount as TotalAmounts ,TyreSize,TyreWidth,TMod.ModelName as model,TMod.Remarks as TyreLifetime,TyreCategory,
	Warranty 
	from rvlfTyreMaster T  
	LEFT OUTER JOIN rvlfTyreVendorMaster VM on VM.VendorId = T.VendorId 
	LEFT OUTER JOIN rvlfTyreMake TMak on TMak.BrandID = T.BrandID 
	LEFT OUTER JOIN rvlfTyreModel TMod on TMod.ModelID = T.ModelID		
	where t.IsDelete=0 AND T.OrganizationId = @bigOrganizationId order by TyreId 
		
	select ISNULL(MAX(TyreId),0) + 1 as TyreCode from rvlfTyreMaster where OrganizationId = @bigOrganizationId
	
	
	
	
  END
  
 set Nocount off;        
END 





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTyreID]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetTyreID]
@bigOrganizationId bigint = Null
AS
/******************************************************************************/
--	Name		  : rvlf_sp_GetTyreID 6
--	Description	  :	To get all the VehicleNames  
--	Author		  :	Kapil
--	Created Date  : 22-Feb-2014
--  Modified Date : 
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 	
	
	SET ANSI_WARNINGS OFF;
	
   --SELECT  VendorId,VendorName FROM rvlfTyreVendorMaster where IsDelete =0 and IsActive =1 and OrganizationId= @bigOrganizationId       
   
	
	select  'T' + CAST(ISNULL(MAX(TyreMappingId),0)+1 AS VARCHAR) AS TID from rvlfTyreVehicleMapping
	--select TyreId, TotalQuantity,ISNULL(UsedQuantity,0) as UsedQty, (TotalQuantity-ISNULL(UsedQuantity,0)) Available from rvlfTyreStock
    		
	SET NOCOUNT OFF
END

--select * from rvlfTyreVehicleMapping
--select TyreId from  rvlfTyreStock WHERE Available > 0
--select * from rvlfTyreHistory

 --select CONVERT(date,GETUTCDATE()-1)


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTyreMakeandModel]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    
CREATE Procedure [dbo].[rvlf_sp_GetTyreMakeandModel]        
 @CarID bigint=null,    
 @IsDeleteMake bit=null,    
 @bitOpeation bit=null,
 @bigOrganizationId bigint = null  
         
 /******************************************************************************/    
-- Name  : [rvlf_sp_GetTyreMakeandModel]    
-- Description : To get the Car Make and Model details.    
-- Author      : Kapil.k   
-- Company     : Angler Technologies    
-- History     : <<Date(dd-MON-yyyy)>> Initial Reason    
--             : 05-Mar-2014 Kapil Created Intial Version     
/******************************************************************************/    
    
AS    
    
BEGIN    
    
 IF(@bitOpeation =1)     
  BEGIN          
   --SELECT MakeId,MakeName       
   --FROM rvlfMake Make WHERE (@CarID IS NULL OR @CarID ='' OR Make.MakeId = @CarID) ORDER BY MakeName ASC                
   SELECT BrandID,BrandName,Benefits
   FROM rvlfTyreMake Make WHERE (@CarID IS NULL OR @CarID ='' OR Make.BrandId = @CarID) 
   and OrganizationId =@bigOrganizationId
   ORDER BY BrandName ASC           
       
   --SELECT Model.ModelId,Model.ModelName,Make.MakeName,Make.MakeId,MakeType.VehicleTypeId,MakeType.VehicleTypeName  FROM rvlfModel 
   --Model INNER JOIN rvlfMake Make on Make.MakeId = Model.MakeId 
   --inner join rvlfVehicleType MakeType on Model.VehicleTypeId=MakeType.VehicleTypeId 
   --WHERE (@CarID IS NULL OR @CarID ='' OR Model.ModelId=@CarID)     
   
   SELECT Model.ModelID,Model.ModelName,Make.BrandName,Make.BrandId,Make.Benefits,Model.Size,Model.Width,Model.Remarks FROM rvlfTyreModel 
   Model INNER JOIN rvlfTyreMake Make on Make.BrandId = Model.BrandID     
   WHERE (@CarID IS NULL OR @CarID ='' OR Model.ModelId=@CarID)
   and Make.OrganizationID = @bigOrganizationId
                
   --SELECT ModelId,MakeId  FROM rvlfModel WHERE (@CarID IS NULL OR @CarID ='' OR MakeId=@CarID)    
   SELECT ModelID,M.BrandID,Size,Width,Remarks FROM rvlfTyreModel TM
   LEFT JOIN  rvlfTyreMake M on M.BrandID = TM.BrandID
   WHERE (@CarID IS NULL OR @CarID ='' OR TM.BrandID=@CarID)  
   AND M.OrganizationId =@bigOrganizationId
       
  -- SELECT VehicleTypeId,VehicleTypeName FROM rvlfVehicleType  WHERE (@VehicleTypeId = 0 OR VehicleTypeId=@VehicleTypeId)    
      
  END    
 ELSE    
  BEGIN    
      
  IF(@IsDeleteMake=0)    
  BEGIN    
      
   DELETE rvlfTyreMake WHERE BrandID=@CarID and OrganizationId =@bigOrganizationId
       
   DELETE rvlfTyreModel WHERE BrandID=@CarID    
  END    
  ELSE    
  BEGIN    
   DELETE rvlfTyreModel WHERE ModelID=@CarID    
  END     
       
  END    
END    
    
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTyreMappingDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
CREATE PROCEDURE [dbo].[rvlf_sp_GetTyreMappingDetails]        
@FleetID BIGINT = null,   
@TyreMapId int = Null,                        
@bigOrganizationId bigint = Null,                        
@bigUserId bigint = Null

          
AS          
-- =============================================          
-- Name   : rvlf_sp_GetTyreMappingDetails null,null,35,18			
-- Author  : Kapil          
-- Create date : 24-Feb-2014          
-- Description : Get Tyre Mapped Details          
-- Company  : TRINETRA 
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
-- =============================================          
BEGIN          
 -- SET NOCOUNT ON added to prevent extra result sets from          
 -- interfering with SELECT statements.          
 SET NOCOUNT ON;    
  IF @TyreMapId = 0 SET @TyreMapId = null
  IF @TyreMapId IS NOT NULL
   
  BEGIN    
    -- Insert statements for procedure here             
	--select TyreID ,CASE WHEN ISNULL(category,0) =1 THEN ToVehicleID ELSE VehicleID END as VehicleID,
	--CASE WHEN ISNULL(category,0) =1 THEN ToAxleID ELSE AxleID END as AxleID,
	--CASE WHEN ISNULL(category,0) =1 THEN ToLocationID ELSE TyreLocationID END as TyreLocationID,
	--CASE WHEN ISNULL(category,0) =1 THEN ToVehicleOdometer ELSE Odometer END as Odometer,	
	
	select TyreID,Category,CASE WHEN ISNULL(category,0) =1 THEN isnull(ToVehicleID,VehicleID) 
	WHEN ISNULL(category,0) =2 THEN ISNULL(ToVehicleID,VehicleID) 
	ELSE VehicleID END as VehicleID,
	CASE WHEN ISNULL(category,0) =1 THEN isnull(ToAxleID,AxleID) 
	WHEN ISNULL(category,0) =2 THEN isnull(ToAxleID,AxleID)		
	ELSE AxleID END as AxleID,
	CASE WHEN ISNULL(category,0) =1 THEN isnull(ToLocationID,TyreLocationID)
	WHEN ISNULL(category,0) =2 THEN isnull(ToLocationID,TyreLocationID)
	ELSE TyreLocationID END as TyreLocationID,	
	CASE WHEN ISNULL(category,0) =1 THEN ISNULL(ToVehicleOdometer,Odometer)
	WHEN ISNULL(category,0) =2 THEN ISNULL(ToVehicleOdometer,Odometer)
	ELSE Odometer END as Odometer,
	LifeTimeKM,replace(convert(varchar(20),MappedDate,106 ),' ','-')  as MappedDate,
	Notification1,Notification2,Notification3,
	ISNULL(dbo.rvlf_fn_GetNotificationsList(13, TyreMappingId, 1,1,0),'') as EmailList,   
    ISNULL(dbo.rvlf_fn_GetNotificationsList(13, TyreMappingId, 0,1,0),'') as SMSList,  
    REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(13, TyreMappingId, 1,0,1),''),',',', ') as EmailUserNameList,  
    REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(13, TyreMappingId, 0,0,1),''),',',', ') as SMSUserNameList ,
    CASE WHEN category =1 THEN 'Yes' else 'No' end as SwapStatus,  
    CASE WHEN VM.IsRethread =1 THEN 'Yes' else 'No' end as ReThreadStatus,    
    ISNULL(VM.IsRethread,0) as IsRethread,
    TID,TyreName,VM.BrandID,VM.ModelID,Make.BrandName,
    Model.ModelName,
  --  Ven.VendorName,
   -- VM.vendorId    
    CASE WHEN ISNULL(IsRethread,0) <> 0 THEN ISNULL(ReVen.VendorName,ven.VendorName) ELSE Ven.VendorName END as VendorName,
    CASE WHEN ISNULL(IsRethread,0) <> 0 THEN ISNULL(VM.RetreadVendorId,VM.VendorId) ELSE VM.VendorId END as vendorId,
    VM.RetreadCost 
	from rvlfTyreVehicleMapping VM 	
	left JOIN rvlfTyreModel Model on Model.ModelID = VM.ModelID 
	left  JOIN rvlfTyreMake Make on Make.BrandID = Model.BrandID	
	LEFT  JOIN rvlfTyreVendorMaster Ven  on Ven.VendorId = Vm.VendorId 	
	LEFT  JOIN rvlfTyreVendorMaster ReVen  on ReVen.VendorId = Vm.RetreadVendorId
	where TyreMappingId = @TyreMapId and VM.isdelete =0
	
  END
  
  ELSE
  
  BEGIN
	--CASE WHEN VendorState='' THEN '-' ELSE VendorState END as VendorState,
	--CASE WHEN ZipCode='' THEN '-' ELSE ZipCode END as ZipCode
			
	select FV.FleetId,VM.TyreMappingId,VM.Category,
	CASE WHEN isNULL(VM.category,0) =1 THEN ISNULL(VT.VehicleDescription, V.VehicleDescription) ELSE V.VehicleDescription END as VehicleDescription,
	--CASE WHEN VM.category =1 THEN VT.VehicleId ELSE V.VehicleId END as VehicleId,
	CASE WHEN isNULL(VM.category,0) =1 THEN ISNULL(AT.AxleName,A.AxleName) ELSE A.AxleName END as AxleName,
	--CASE WHEN VM.category =1 THEN AT.AxleId ELSE A.AxleName END as AxleId,
	CASE WHEN isNULL(VM.category,0) =1 THEN ISNULL(lT.TyreLocation,L.TyreLocation) ELSE L.TyreLocation END as TyreLocation,
	CASE WHEN isNULL(VM.category,0) =1 THEN ISNULL(Vm.ToVehicleOdometer,Vm.Odometer) ELSE VM.Odometer END as Odometer,	
	--CASE WHEN isNULL(VM.category,0) =0 THEN V.VehicleDescription when (VM.Category) = 1 THEN V.VehicleDescription ELSE V.VehicleDescription END as VehicleDescription,	
	--CASE WHEN isNULL(VM.category,0) = 0 THEN A.AxleName WHEN (VM.Category) = 1 THEN A.AxleName ELSE AT.AxleName END as AxleName,
	--CASE WHEN isNULL(VM.category,0) = 0 THEN l.TyreLocation WHEN VM.Category = 1 THEN L.TyreLocation ELSE Lt.TyreLocation END as TyreLocation,
	--CASE WHEN isNULL(VM.category,0) = 0 THEN  VM.Odometer WHEN VM.Category = 1 THEN VM.Odometer else Vm.ToVehicleOdometer  END as Odometer,
	VM.TID as TyreCode,Make.BrandName,
	CASE WHEN ISNULL(IsRethread,0) <> 0 THEN isnull(ReVen.VendorName,Ven.VendorName) ELSE Ven.VendorName END as VendorName,
	--Ven.VendorName,
	Vm.TyreName,
	VM.LifeTimeKM, replace(convert(varchar(20),MappedDate,106 ),' ','-')  as MappedDate,
	ISNULL(dbo.rvlf_fn_GetNotificationsList(13, vm.TyreMappingId, 1,1,0),'') as EmailList,   
    ISNULL(dbo.rvlf_fn_GetNotificationsList(13, vm.TyreMappingId, 0,1,0),'') as SMSList,  
    REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(13, vm.TyreMappingId, 1,0,1),''),',',', ') as EmailUserNameList,  
    REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(13, vm.TyreMappingId, 0,0,1),''),',',', ') as SMSUserNameList ,
    CASE WHEN VM.category =1 THEN 'Yes' else 'No' end as SwapStatus,
    CASE WHEN VM.IsRethread =1 THEN 'Yes' else 'No' end as ReThreadStatus,
    ISNULL(VM.IsRethread,0) as IsRethread
	from
	rvlfTyreVehicleMapping VM LEFT OUTER JOIN rvlfVehicle V on V.VehicleId = VM.VehicleID
	left join rvlfFleetVehicles FV on FV.VehicleId = VM.VehicleID 
	LEFT  JOIN rvlfVehicle VT ON VT.VehicleId = VM.ToVehicleId 
	LEFT  JOIN rvlfTyreAxleMaster A on A.AxleId = VM.AxleID
	LEFT  JOIN rvlfTyreAxleMaster AT on At.AxleId = VM.ToAxleId
	LEFT  JOIN rvlfTyreLocationMaster L on L.TyreLocationID = VM.TyreLocationID
	LEFT  JOIN rvlfTyreLocationMaster Lt on Lt.TyreLocationID = VM.ToLocationID
	--LEFT  JOIN rvlfTyreMaster T on T.BrandID = VM.BrandID
	left JOIN rvlfTyreModel Model on Model.ModelID = VM.ModelID 
	left  JOIN rvlfTyreMake Make on Make.BrandID = Model.BrandID	
	LEFT  JOIN rvlfTyreVendorMaster Ven  on Ven.VendorId = Vm.VendorId 
	LEFT  JOIN rvlfTyreVendorMaster ReVen  on ReVen.VendorId = Vm.RetreadVendorId 
	--LEFT OUTER JOIN 
	where vm.Isdelete =0 and VM.OrganizationId = @bigOrganizationId 
		
	and VM.TyreMappingId in(select MAX(TyreMappingId) from rvlfTyreVehicleMapping where IsDelete = 0 and IsActive = 1
	 and OrganizationId = @bigOrganizationId and 
	--(@FleetID IS NULL OR @FleetID = '' OR (FV.FleetId IN( SELECT * FROM [rvlf_fn_GetParentChild](@FleetID))))
	(@FleetID IS NULL OR @FleetID = '' OR FV.FleetId = @FleetID)
	and ISNULL(VM.Category,0) <>2
	Group by TyreName)
	
	order by CASE WHEN VM.category =1 THEN VT.VehicleDescription ELSE V.VehicleDescription END
	
			
	select VM.TyreMappingId,VM.Category,
	CASE WHEN isNULL(VM.category,0) =1 THEN ISNULL(VT.VehicleDescription, V.VehicleDescription)  END as VehicleDescription,
	--CASE WHEN VM.category =1 THEN VT.VehicleId ELSE V.VehicleId END as VehicleId,
	CASE WHEN isNULL(VM.category,0) =1 THEN ISNULL(AT.AxleName,A.AxleName) ELSE A.AxleName END as AxleName,
	--CASE WHEN VM.category =1 THEN AT.AxleId ELSE A.AxleName END as AxleId,
	CASE WHEN isNULL(VM.category,0) =1 THEN ISNULL(lT.TyreLocation,L.TyreLocation) ELSE L.TyreLocation END as TyreLocation,
	CASE WHEN isNULL(VM.category,0) =1 THEN ISNULL(Vm.ToVehicleOdometer,Vm.Odometer) ELSE VM.Odometer END as Odometer,	
	--CASE WHEN isNULL(VM.category,0) =0 THEN V.VehicleDescription when (VM.Category) = 1 THEN V.VehicleDescription ELSE V.VehicleDescription END as VehicleDescription,	
	--CASE WHEN isNULL(VM.category,0) = 0 THEN A.AxleName WHEN (VM.Category) = 1 THEN A.AxleName ELSE AT.AxleName END as AxleName,
	--CASE WHEN isNULL(VM.category,0) = 0 THEN l.TyreLocation WHEN VM.Category = 1 THEN L.TyreLocation ELSE Lt.TyreLocation END as TyreLocation,
	--CASE WHEN isNULL(VM.category,0) = 0 THEN  VM.Odometer WHEN VM.Category = 1 THEN VM.Odometer else Vm.ToVehicleOdometer  END as Odometer,
	VM.TID as TyreCode,Make.BrandName,
	CASE WHEN ISNULL(IsRethread,0) <> 0 THEN ISNULL(ReVen.VendorName,Ven.VendorName) ELSE Ven.VendorName END as VendorName,
	--Ven.VendorName,
	Vm.TyreName,
	VM.LifeTimeKM, replace(convert(varchar(20),MappedDate,106 ),' ','-')  as MappedDate,
	ISNULL(dbo.rvlf_fn_GetNotificationsList(13, vm.TyreMappingId, 1,1,0),'') as EmailList,   
    ISNULL(dbo.rvlf_fn_GetNotificationsList(13, vm.TyreMappingId, 0,1,0),'') as SMSList,  
    REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(13, vm.TyreMappingId, 1,0,1),''),',',', ') as EmailUserNameList,  
    REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(13, vm.TyreMappingId, 0,0,1),''),',',', ') as SMSUserNameList ,
    CASE WHEN VM.category =1 THEN 'Yes' else 'No' end as SwapStatus,
    CASE WHEN VM.IsRethread =1 THEN 'Yes' else 'No' end as ReThreadStatus,
     ISNULL(VM.IsRethread,0) as IsRethread,
    VM.Notification1,VM.Notification2,VM.Notification3    
	from
	rvlfTyreVehicleMapping VM LEFT OUTER JOIN rvlfVehicle V on V.VehicleId = VM.VehicleID
	LEFT  JOIN rvlfVehicle VT ON VT.VehicleId = VM.ToVehicleId 
	LEFT  JOIN rvlfTyreAxleMaster A on A.AxleId = VM.AxleID
	LEFT  JOIN rvlfTyreAxleMaster AT on At.AxleId = VM.ToAxleId
	LEFT  JOIN rvlfTyreLocationMaster L on L.TyreLocationID = VM.TyreLocationID
	LEFT  JOIN rvlfTyreLocationMaster Lt on Lt.TyreLocationID = VM.ToLocationID
	--LEFT  JOIN rvlfTyreMaster T on T.BrandID = VM.BrandID
	left JOIN rvlfTyreModel Model on Model.ModelID = VM.ModelID 
	left  JOIN rvlfTyreMake Make on Make.BrandID = Model.BrandID	
	LEFT  JOIN rvlfTyreVendorMaster Ven  on Ven.VendorId = Vm.VendorId 
	LEFT  JOIN rvlfTyreVendorMaster ReVen  on ReVen.VendorId = Vm.RetreadVendorId
	--LEFT OUTER JOIN 
	where vm.Isdelete =0 and VM.OrganizationId = @bigOrganizationId
	and VM.IsActive = 0	
	
	
	select VM.TyreMappingId,VM.Category,
	CASE WHEN isNULL(VM.category,0) =1 THEN ISNULL(VT.VehicleDescription, V.VehicleDescription)  END as VehicleDescription,
	--CASE WHEN VM.category =1 THEN VT.VehicleId ELSE V.VehicleId END as VehicleId,
	CASE WHEN isNULL(VM.category,0) =1 THEN ISNULL(AT.AxleName,A.AxleName) ELSE A.AxleName END as AxleName,
	--CASE WHEN VM.category =1 THEN AT.AxleId ELSE A.AxleName END as AxleId,
	CASE WHEN isNULL(VM.category,0) =1 THEN ISNULL(lT.TyreLocation,L.TyreLocation) ELSE L.TyreLocation END as TyreLocation,
	CASE WHEN isNULL(VM.category,0) =1 THEN ISNULL(Vm.ToVehicleOdometer,Vm.Odometer) ELSE VM.Odometer END as Odometer,	
	--CASE WHEN isNULL(VM.category,0) =0 THEN V.VehicleDescription when (VM.Category) = 1 THEN V.VehicleDescription ELSE V.VehicleDescription END as VehicleDescription,	
	--CASE WHEN isNULL(VM.category,0) = 0 THEN A.AxleName WHEN (VM.Category) = 1 THEN A.AxleName ELSE AT.AxleName END as AxleName,
	--CASE WHEN isNULL(VM.category,0) = 0 THEN l.TyreLocation WHEN VM.Category = 1 THEN L.TyreLocation ELSE Lt.TyreLocation END as TyreLocation,
	--CASE WHEN isNULL(VM.category,0) = 0 THEN  VM.Odometer WHEN VM.Category = 1 THEN VM.Odometer else Vm.ToVehicleOdometer  END as Odometer,
	VM.TID as TyreCode,Make.BrandName,
	CASE WHEN ISNULL(IsRethread,0) <> 0 THEN ISNULL(ReVen.VendorName,Ven.VendorName) ELSE Ven.VendorName END as VendorName,
	Ven.VendorName,
	Vm.TyreName,
	VM.LifeTimeKM, replace(convert(varchar(20),MappedDate,106 ),' ','-')  as MappedDate,
	ISNULL(dbo.rvlf_fn_GetNotificationsList(13, vm.TyreMappingId, 1,1,0),'') as EmailList,   
    ISNULL(dbo.rvlf_fn_GetNotificationsList(13, vm.TyreMappingId, 0,1,0),'') as SMSList,  
    REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(13, vm.TyreMappingId, 1,0,1),''),',',', ') as EmailUserNameList,  
    REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(13, vm.TyreMappingId, 0,0,1),''),',',', ') as SMSUserNameList ,
    CASE WHEN VM.category =1 THEN 'Yes' else 'No' end as SwapStatus,
    CASE WHEN VM.IsRethread =1 THEN 'Yes' else 'No' end as ReThreadStatus,
     ISNULL(VM.IsRethread,0) as IsRethread,
    VM.Notification1,VM.Notification2,VM.Notification3    
	from
	rvlfTyreVehicleMapping VM LEFT OUTER JOIN rvlfVehicle V on V.VehicleId = VM.VehicleID
	LEFT  JOIN rvlfVehicle VT ON VT.VehicleId = VM.ToVehicleId 
	LEFT  JOIN rvlfTyreAxleMaster A on A.AxleId = VM.AxleID
	LEFT  JOIN rvlfTyreAxleMaster AT on At.AxleId = VM.ToAxleId
	LEFT  JOIN rvlfTyreLocationMaster L on L.TyreLocationID = VM.TyreLocationID
	LEFT  JOIN rvlfTyreLocationMaster Lt on Lt.TyreLocationID = VM.ToLocationID
	--LEFT  JOIN rvlfTyreMaster T on T.BrandID = VM.BrandID
	left JOIN rvlfTyreModel Model on Model.ModelID = VM.ModelID 
	left  JOIN rvlfTyreMake Make on Make.BrandID = Model.BrandID	
	LEFT  JOIN rvlfTyreVendorMaster Ven  on Ven.VendorId = Vm.VendorId 
	LEFT  JOIN rvlfTyreVendorMaster ReVen  on ReVen.VendorId = Vm.RetreadVendorId
	--LEFT OUTER JOIN 
	where vm.Isdelete =0 and VM.OrganizationId = @bigOrganizationId
	and isRemap =1
	
		
	END
  
 set Nocount off;        
END 




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTyreNames]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetTyreNames]
@bigOrganizationId bigint = Null,
@VehicleID varchar(50) = null
AS
/******************************************************************************/
--	Name		  : rvlf_sp_GetTyreNames 1 ,246
--	Description	  :	To get all the TyreNames 
--	Author		  :	Kapil
--	Created Date  : 17-Mar-2014
--  Modified Date : 
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 

if @VehicleID = 0 or @VehicleID = ''

SET @VehicleID = null

--select TyreName,TID,TyreMappingId from rvlfTyreVehicleMapping where OrganizationId = @bigOrganizationId
--and TyreName is not null and TyreName <> '' 
--  AND IsDelete= 0 AND
----and VehicleID is not null and VehicleID in (@VehicleID)
--(@VehicleID IS NULL OR @VehicleID='' OR VehicleID = @VehicleID) AND    
--(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId= @bigOrganizationID)      
----and ToVehicleID is not null and ToVehicleID in(@VehicleID)      


select distinct TyreName,TID from rvlfTyreVehicleMapping where OrganizationId = @bigOrganizationId
and TyreName is not null and TyreName <> ''
  AND IsDelete= 0 
 -- AND (Category <> 2 AND ISNULL(IsRethread,0) =0)
  AND
--and VehicleID is not null and VehicleID in (@VehicleID)
(@VehicleID IS NULL OR @VehicleID='' OR VehicleID = @VehicleID) AND    
(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId= @bigOrganizationID)  
      		
SET NOCOUNT OFF
END





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTyreReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
      
CREATE PROCEDURE [dbo].[rvlf_sp_GetTyreReport] 
 @bigFleetID bigint = null,                
 @TyreId varchar(MAX)=null,
 @dtStartDate datetime = null,   
 @dtEndDate datetime = null, 
 @bigOrganizationID bigint = null,      
 @bigQueryingUser bigint = null,
 @Vehicleid BIGINT = NULL,
 @intBoxID varchar(max) = null         
AS              
/******************************************************************************************************************/              
-- Name			: rvlf_sp_GetTyreReport '','T241',1,18,null
-- Author		: Kapil              
-- Company     : Trinetra Technologies              
-- History     : <<Date(dd-MON-yyyy)>> Initial Reason              
--             : 15-Mar-2014 Created Intial Version            
/******************************************************************************************************************/ 
BEGIN

if @VehicleID = 0 or @VehicleID = ''
SET @VehicleID = null

IF @TyreId = '' or @TyreId is null
	BEGIN
		SET @TyreId = ''
	END 
--select @TyreId
 Declare @dtFDate datetime =  null         
 Declare @dtEDate datetime =  null   

 DECLARE @HoursToBeAdded INT = 0              
 DECLARE @MinsToBeAdded INT = 0              
 DECLARE @ConversionFactor numeric (10,2) = 1.0              
 DECLARE @DistanceCaptionPrefix varchar(15)              
 DECLARE @SpeedCaptionPrefix varchar(15)            
 DECLARE @DefaultDateFormat INT = 0;            
 DECLARE @Hours varchar(max) = 0      
 DECLARE @Minutes INT = 0
 DECLARE @Sign char =0 
 DECLARE @ToDate Datetime = NULL       
 DECLARE @FromDate Datetime = NULL 
        
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
-- @Hours= HOURS,@ToDate = ToDate,@FromDate = FromDate,      
 --@Sign = SUBSTRING(Hours,1,1),@Minutes = SUBSTRING(Hours,5,2),      
 @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,@DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)              
 FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz              
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser             
           
 --SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))              
 --SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))      
  
--Declare @Table1 as Table(
--MapId int,
--VehicleId int,
--TyreID Varchar(15),
--TyreName varchar(50),
--VehicleName varchar(50),
--BrandName varchar(50),
--Model varchar(50),
--Axle varchar(20),
--Location varchar(20),
--DateOfAssign Datetime,
--CurrentStatus varchar(50),
--Distance BIGINT,
--TotalDistance BIGINT,
--LifeTimeKM BIGINT,
--AvailLifetime BIGINT,
--Comments varchar(150)
--)

--insert into @Table1(MapId,TyreName,TyreID,VehicleId,VehicleName,BrandName,Model,Axle,Location,DateOfAssign,CurrentStatus,LifeTimeKM,TotalDistance,AvailLifetime,Comments)
--select VM.TyreMappingId,Vm.TyreName,VM.TID,
--case when ISNULL(VM.Category,0) =1 then TV.VehicleId  else V.VehicleId  end as VehicleId,
--case when ISNULL(VM.Category,0) =1 then TV.VehicleDescription when ISNULL(VM.Category,0) =2 then ISNULL(TV.VehicleDescription, V.VehicleDescription) else V.VehicleDescription end as VehicleName,
--Make.BrandName,Model.ModelName,
--case when ISNULL(VM.Category,0) =1 then TA.AxleName when ISNULL(VM.Category,0) =2 THEN ISNULL(TA.AxleName,A.AxleName) else A.AxleName end as Axle,
--case when ISNULL(VM.Category,0) =1 then TL.TyreLocation WHEN ISNULL(VM.Category,0) =2 then ISNULL(TL.TyreLocation,L.TyreLocation)  else L.TyreLocation end as Location,
--case when ISNULL(VM.Category,0) =1 then VM.SwapDate when ISNULL(VM.Category,0) =2 then VM.RemovedDate else VM.MappedDate end as DateOfAssign,
--case when ISNULL(VM.Category,0) =1 then 'Swapped' when ISNULL(VM.Category,0) =2 THEN 'Removed' else 'Mapped' end as CurrentStatus,
--Model.Remarks,
--VM.distance,
--Model.Remarks - ISNULL(VM.distance,0),
--case when ISNULL(VM.Category,0) =2 then VM.RemoveComments else '-' END as Comments
--from rvlfTyreVehicleMapping VM 
----LEFT JOIN rvlfTyreMaster TM ON TM.TyreId = VM.TyreID 
--LEFT JOIN rvlfVehicle V on V.VehicleId = VM.VehicleID
--LEFT JOIN rvlfVehicle TV on TV.VehicleId = VM.ToVehicleID
--LEFT JOIN rvlfTyreAxleMaster A ON A.AxleId = VM.AxleID
--LEFT JOIN rvlfTyreAxleMaster TA ON TA.AxleId = VM.ToAxleID
--LEFT JOIN rvlfTyreLocationMaster L on L.TyreLocationID = VM.TyreLocationID
--LEFT JOIN rvlfTyreLocationMaster TL on TL.TyreLocationID = VM.ToLocationID
--left join rvlfVehicleAssignment VA on VA.VehicleId = VM.VehicleId	
--left JOIN rvlfTyreModel Model on Model.ModelID = VM.ModelID 
--left JOIN rvlfTyreMake Make on Make.BrandID = Model.BrandID  
--where VM.IsDelete = 0 and VM.OrganizationId =@bigOrganizationID
----and (@TyreId IS NULL OR @TyreId = '' OR VM.TID=@TyreId)
----AND VM.CreatedDateTime BETWEEN @dtStartDate AND @dtEndDate
--and VM.TID IN (select TID from rvlfTyreVehicleMapping where OrganizationId = @bigOrganizationId
--and TyreName is not null and TyreName <> '' and
--(@TyreId IS NULL OR @TyreId='' OR TID = @TyreId) and
--(@VehicleID IS NULL OR @VehicleID='' OR VehicleID = @VehicleID) AND    
--(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId= @bigOrganizationID)
--  AND IsDelete= 0 and IsRethread is null)
--and ISNULL(VM.Category,0) <>0
--and ISNULL(VM.Category,0) <>1 
--order by v.VehicleDescription
----select 1,* from  @Table1

--insert into @Table1 (MapId,TyreName,TyreID,VehicleId,VehicleName,Axle,Location,DateOfAssign,CurrentStatus,BrandName,Model,Distance,LifeTimeKM,TotalDistance,AvailLifetime,Comments)
--select H.TyreMappingID,Vm.TyreName,VM.TID,H.VehicleID,V.VehicleDescription,A.AxleName,L.TyreLocation,H.CreatedDate,
--case when ISNULL(H.Category,0) =1 then 'Swapped' when ISNULL(H.Category,0) =2 THEN 'Removed' else 'Mapped' end as CurrentStatus,
--Make.BrandName,
--Model.ModelName,H.Odometer,Model.Remarks,VM.distance,
--Model.Remarks - ISNULL(VM.distance,0),
--ISNULL(swapComments,'-') as swapComments
--from rvlfTyreHistory H
--LEFT JOIN rvlfVehicle V on V.VehicleId = H.VehicleID
--LEFT JOIN rvlfTyreAxleMaster A ON A.AxleId = H.AxleID
--LEFT JOIN rvlfTyreLocationMaster L on L.TyreLocationID = H.LocationID
--INNER JOIN rvlfTyreVehicleMapping VM on VM.TyreMappingId = H.TyreMappingID 
--left JOIN rvlfTyreModel Model on Model.ModelID = VM.ModelID 
--left  JOIN rvlfTyreMake Make on Make.BrandID = Model.BrandID
--where VM.IsDelete = 0 and VM.OrganizationId =@bigOrganizationID
----and (@TyreId IS NULL OR @TyreId = '' OR VM.TID=@TyreId)
--and VM.TID IN (select TID from rvlfTyreVehicleMapping where OrganizationId = @bigOrganizationId
--and TyreName is not null and TyreName <> '' and
--(@TyreId IS NULL OR @TyreId='' OR TID = @TyreId) and
--(@VehicleID IS NULL OR @VehicleID='' OR VehicleID = @VehicleID) AND    
--(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId= @bigOrganizationID)
--  AND IsDelete= 0)
----AND VM.CreatedDateTime BETWEEN @dtStartDate AND @dtEndDate\
--select MapId,TyreName,TyreID,VehicleId,VehicleName,BrandName,Model,Axle,Location,convert(varchar, DateOfAssign)as DateOfAssign1,DateOfAssign AS DateSort
--,CurrentStatus,LifeTimeKM,ISNULL(Distance,0) as Distance ,ISNULL(TotalDistance,0) as TotalDistance ,AvailLifetime ,Comments,
--CONVERT(varchar, DateOfAssign) as DateAction,
--Convert(Datetime,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,DateOfAssign))) as DateOfAssign2,
--Convert(Datetime,dbo.rvlf_fn_DayLightSavings_Date(DateOfAssign,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,DateOfAssign)) as OriginDateTime,          
--DateOfAssign = dbo.rvlf_fn_DayLightSavings(DateOfAssign,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateOfAssign),    
--Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+        
-- ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,        
-- PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()) 
--from  @Table1 ORDER BY OriginDateTime desc 






Declare @Table1 as Table(
MapId int,
VehicleId int,
TyreID Varchar(15),
TyreName varchar(50),
VehicleName varchar(50),
BrandName varchar(50),
Model varchar(50),
Axle varchar(20),
Location varchar(20),
DateOfAssign Datetime,
CurrentStatus varchar(50),
Distance BIGINT,
TotalDistance BIGINT,
LifeTimeKM BIGINT,
AvailLifetime BIGINT,
Comments varchar(150),
IsRtread bit 
)

Declare @Table2 as Table(
MapId int,
VehicleId int,
TyreID Varchar(15),
TyreName varchar(50),
VehicleName varchar(50),
BrandName varchar(50),
Model varchar(50),
Axle varchar(20),
Location varchar(20),
DateOfAssign Datetime,
CurrentStatus varchar(50),
Distance BIGINT,
TotalDistance BIGINT,
LifeTimeKM BIGINT,
AvailLifetime BIGINT,
Comments varchar(150),
IsRtread bit 
)

insert into @Table1(MapId,TyreName,TyreID,VehicleId,VehicleName,BrandName,Model,Axle,Location,DateOfAssign,CurrentStatus,LifeTimeKM,TotalDistance,AvailLifetime,Comments,IsRtread)
select VM.TyreMappingId,Vm.TyreName,VM.TID,
case when ISNULL(VM.Category,0) =1 then TV.VehicleId  else V.VehicleId  end as VehicleId,
case when ISNULL(VM.Category,0) =1 then TV.VehicleDescription when ISNULL(VM.Category,0) =2 then ISNULL(TV.VehicleDescription, V.VehicleDescription) else V.VehicleDescription end as VehicleName,
Make.BrandName,Model.ModelName,
case when ISNULL(VM.Category,0) =1 then TA.AxleName when ISNULL(VM.Category,0) =2 THEN ISNULL(TA.AxleName,A.AxleName) else A.AxleName end as Axle,
case when ISNULL(VM.Category,0) =1 then TL.TyreLocation WHEN ISNULL(VM.Category,0) =2 then ISNULL(TL.TyreLocation,L.TyreLocation)  else L.TyreLocation end as Location,
case when ISNULL(VM.Category,0) =1 then VM.SwapDate when ISNULL(VM.Category,0) =2 then VM.RemovedDate else VM.MappedDate end as DateOfAssign,
case when ISNULL(VM.Category,0) =1 then 'Swapped' when ISNULL(VM.Category,0) =2 THEN 'Removed' else 'Mapped' end as CurrentStatus,
Model.Remarks,
VM.distance,
Model.Remarks - ISNULL(VM.distance,0),
case when ISNULL(VM.Category,0) =2 then VM.RemoveComments else '-' END as Comments,
Vm.IsRethread
from rvlfTyreVehicleMapping VM 
--LEFT JOIN rvlfTyreMaster TM ON TM.TyreId = VM.TyreID 
LEFT JOIN rvlfVehicle V on V.VehicleId = VM.VehicleID
LEFT JOIN rvlfVehicle TV on TV.VehicleId = VM.ToVehicleID
LEFT JOIN rvlfTyreAxleMaster A ON A.AxleId = VM.AxleID
LEFT JOIN rvlfTyreAxleMaster TA ON TA.AxleId = VM.ToAxleID
LEFT JOIN rvlfTyreLocationMaster L on L.TyreLocationID = VM.TyreLocationID
LEFT JOIN rvlfTyreLocationMaster TL on TL.TyreLocationID = VM.ToLocationID
left join rvlfVehicleAssignment VA on VA.VehicleId = VM.VehicleId	
left JOIN rvlfTyreModel Model on Model.ModelID = VM.ModelID 
left JOIN rvlfTyreMake Make on Make.BrandID = Model.BrandID  
where VM.IsDelete = 0 and VM.OrganizationId =@bigOrganizationID
and(IsRethread is null or IsRethread = 2 or IsRethread = 0)
--and (@TyreId IS NULL OR @TyreId = '' OR VM.TID=@TyreId)
--AND VM.CreatedDateTime BETWEEN @dtStartDate AND @dtEndDate
and VM.TID IN (select TID from rvlfTyreVehicleMapping where OrganizationId = @bigOrganizationId
and TyreName is not null and TyreName <> '' and
(@TyreId IS NULL OR @TyreId='' OR TID = @TyreId) and
(@VehicleID IS NULL OR @VehicleID='' OR VehicleID = @VehicleID) AND    
(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId= @bigOrganizationID)
  AND IsDelete= 0 and (IsRethread is null or IsRethread = 2 or IsRethread = 0))
and ISNULL(VM.Category,0) <>0
and ISNULL(VM.Category,0) <>1 
order by v.VehicleDescription
--select 1,* from  @Table1

insert into @Table1 (MapId,TyreName,TyreID,VehicleId,VehicleName,Axle,Location,DateOfAssign,CurrentStatus,BrandName,Model,Distance,LifeTimeKM,TotalDistance,AvailLifetime,Comments,IsRtread)
select H.TyreMappingID,Vm.TyreName,VM.TID,H.VehicleID,V.VehicleDescription,A.AxleName,L.TyreLocation,H.CreatedDate,
case when ISNULL(H.Category,0) =1 then 'Swapped' when ISNULL(H.Category,0) =2 THEN 'Removed' else 'Mapped' end as CurrentStatus,
Make.BrandName,
Model.ModelName,H.Odometer,Model.Remarks,VM.distance,
Model.Remarks - ISNULL(VM.distance,0),
ISNULL(swapComments,'-') as swapComments,H.IsRetread
from rvlfTyreHistory H
LEFT JOIN rvlfVehicle V on V.VehicleId = H.VehicleID
LEFT JOIN rvlfTyreAxleMaster A ON A.AxleId = H.AxleID
LEFT JOIN rvlfTyreLocationMaster L on L.TyreLocationID = H.LocationID
INNER JOIN rvlfTyreVehicleMapping VM on VM.TyreMappingId = H.TyreMappingID 
left JOIN rvlfTyreModel Model on Model.ModelID = VM.ModelID 
left  JOIN rvlfTyreMake Make on Make.BrandID = Model.BrandID
where VM.IsDelete = 0 and VM.OrganizationId =@bigOrganizationID
--and (@TyreId IS NULL OR @TyreId = '' OR VM.TID=@TyreId)

and VM.TID IN (select TID from rvlfTyreVehicleMapping where OrganizationId = @bigOrganizationId
and TyreName is not null and TyreName <> '' and
(@TyreId IS NULL OR @TyreId='' OR TID = @TyreId) and
(@VehicleID IS NULL OR @VehicleID='' OR VehicleID = @VehicleID) AND    
(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId= @bigOrganizationID)
  --AND IsDelete= 0 and IsRetread is null)  
     AND IsDelete= 0 and (IsRethread is null or IsRethread = 2 or IsRethread = 0))
     and IsRethread <> 1 
--AND VM.CreatedDateTime BETWEEN @dtStartDate AND @dtEndDate\


------------------------------------------------------------------------AFTER-----------------------------------------------------------------

insert into @Table2(MapId,TyreName,TyreID,VehicleId,VehicleName,BrandName,Model,Axle,Location,DateOfAssign,CurrentStatus,LifeTimeKM,TotalDistance,AvailLifetime,Comments,IsRtread)
select VM.TyreMappingId,Vm.TyreName,VM.TID,
case when ISNULL(VM.Category,0) =1 then TV.VehicleId  else V.VehicleId  end as VehicleId,
case when ISNULL(VM.Category,0) =1 then TV.VehicleDescription when ISNULL(VM.Category,0) =2 then ISNULL(TV.VehicleDescription, V.VehicleDescription) else V.VehicleDescription end as VehicleName,
Make.BrandName,Model.ModelName,
case when ISNULL(VM.Category,0) =1 then TA.AxleName when ISNULL(VM.Category,0) =2 THEN ISNULL(TA.AxleName,A.AxleName) else A.AxleName end as Axle,
case when ISNULL(VM.Category,0) =1 then TL.TyreLocation WHEN ISNULL(VM.Category,0) =2 then ISNULL(TL.TyreLocation,L.TyreLocation)  else L.TyreLocation end as Location,
case when ISNULL(VM.Category,0) =1 then VM.SwapDate when ISNULL(VM.Category,0) =2 then VM.RemovedDate else VM.MappedDate end as DateOfAssign,
case when ISNULL(VM.Category,0) =1 then 'Swapped' when ISNULL(VM.Category,0) =2 THEN 'Removed' else 'Mapped' end as CurrentStatus,
VM.LifeTimeKM,
VM.distance,
VM.LifeTimeKM - ISNULL(VM.distance,0),
case when ISNULL(VM.Category,0) =2 then VM.RemoveComments else '-' END as Comments,Vm.IsRethread
from rvlfTyreVehicleMapping VM 
--LEFT JOIN rvlfTyreMaster TM ON TM.TyreId = VM.TyreID 
LEFT JOIN rvlfVehicle V on V.VehicleId = VM.VehicleID
LEFT JOIN rvlfVehicle TV on TV.VehicleId = VM.ToVehicleID
LEFT JOIN rvlfTyreAxleMaster A ON A.AxleId = VM.AxleID
LEFT JOIN rvlfTyreAxleMaster TA ON TA.AxleId = VM.ToAxleID
LEFT JOIN rvlfTyreLocationMaster L on L.TyreLocationID = VM.TyreLocationID
LEFT JOIN rvlfTyreLocationMaster TL on TL.TyreLocationID = VM.ToLocationID
left join rvlfVehicleAssignment VA on VA.VehicleId = VM.VehicleId	
left JOIN rvlfTyreModel Model on Model.ModelID = VM.ModelID 
left JOIN rvlfTyreMake Make on Make.BrandID = Model.BrandID  
where VM.IsDelete = 0 and VM.OrganizationId =@bigOrganizationID
and isnull(IsRethread,0) = 1
--and (@TyreId IS NULL OR @TyreId = '' OR VM.TID=@TyreId)
--AND VM.CreatedDateTime BETWEEN @dtStartDate AND @dtEndDate
and VM.TID IN (select TID from rvlfTyreVehicleMapping where OrganizationId = @bigOrganizationId
and TyreName is not null and TyreName <> '' and
(@TyreId IS NULL OR @TyreId='' OR TID = @TyreId) and
(@VehicleID IS NULL OR @VehicleID='' OR VehicleID = @VehicleID) AND    
(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId= @bigOrganizationID)
  AND IsDelete= 0 and ISNULL(IsRethread,0) =1)
and ISNULL(VM.Category,0) <>0
and ISNULL(VM.Category,0) <>1 
--and isnull(IsRethread,0) = 1
order by v.VehicleDescription
--select 1,* from  @Table1

insert into @Table2 (MapId,TyreName,TyreID,VehicleId,VehicleName,Axle,Location,DateOfAssign,CurrentStatus,BrandName,Model,Distance,LifeTimeKM,TotalDistance,AvailLifetime,Comments,IsRtread)

select H.TyreMappingID,Vm.TyreName,VM.TID,H.VehicleID,V.VehicleDescription,A.AxleName,L.TyreLocation,H.CreatedDate,
case when ISNULL(H.Category,0) =1 then 'Swapped' when ISNULL(H.Category,0) =2 THEN 'Removed' else 'Mapped' end as CurrentStatus,
Make.BrandName,
Model.ModelName,H.Odometer,VM.LifeTimeKM,VM.distance,
VM.LifeTimeKM - ISNULL(VM.distance,0),
ISNULL(swapComments,'-') as swapComments,H.IsRetread
from rvlfTyreHistory H
LEFT JOIN rvlfVehicle V on V.VehicleId = H.VehicleID
LEFT JOIN rvlfTyreAxleMaster A ON A.AxleId = H.AxleID
LEFT JOIN rvlfTyreLocationMaster L on L.TyreLocationID = H.LocationID
INNER JOIN rvlfTyreVehicleMapping VM on VM.TyreMappingId = H.TyreMappingID 
left JOIN rvlfTyreModel Model on Model.ModelID = VM.ModelID 
left  JOIN rvlfTyreMake Make on Make.BrandID = Model.BrandID
where VM.IsDelete = 0 and VM.OrganizationId =@bigOrganizationID
and isnull(IsRetread,0) = 1
--and (@TyreId IS NULL OR @TyreId = '' OR VM.TID=@TyreId)
and VM.TID IN (select TID from rvlfTyreVehicleMapping where OrganizationId = @bigOrganizationId
and TyreName is not null and TyreName <> '' and
(@TyreId IS NULL OR @TyreId='' OR TID = @TyreId) and
(@VehicleID IS NULL OR @VehicleID='' OR VehicleID = @VehicleID) AND    
(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR OrganizationId= @bigOrganizationID)
 AND IsDelete= 0 and ISNULL(IsRethread,0) = 1 )

--AND VM.CreatedDateTime BETWEEN @dtStartDate AND @dtEndDate\
select MapId,TyreName,TyreID,VehicleId,VehicleName,BrandName,Model,Axle,Location,convert(varchar, DateOfAssign)as DateOfAssign1,DateOfAssign AS DateSort
,CurrentStatus,LifeTimeKM,ISNULL(Distance,0) as Distance ,ISNULL(TotalDistance,0) as TotalDistance ,AvailLifetime ,Comments,
CONVERT(varchar, DateOfAssign) as DateAction,
Convert(Datetime,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,DateOfAssign))) as DateOfAssign2,
Convert(Datetime,dbo.rvlf_fn_DayLightSavings_Date(DateOfAssign,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,DateOfAssign)) as OriginDateTime,          
DateOfAssign = dbo.rvlf_fn_DayLightSavings(DateOfAssign,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateOfAssign),    
Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+        
 ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,        
 PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()),
 IsRtread, 0 as IsRetreadingBit,'New' as TyreType
from  @Table1 --ORDER BY OriginDateTime desc 

UNION

select MapId,TyreName,TyreID,VehicleId,VehicleName,BrandName,Model,Axle,Location,convert(varchar, DateOfAssign)as DateOfAssign1,DateOfAssign AS DateSort
,CurrentStatus,LifeTimeKM,ISNULL(Distance,0) as Distance ,ISNULL(TotalDistance,0) as TotalDistance ,AvailLifetime ,Comments,
CONVERT(varchar, DateOfAssign) as DateAction,
Convert(Datetime,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,DateOfAssign))) as DateOfAssign2,
Convert(Datetime,dbo.rvlf_fn_DayLightSavings_Date(DateOfAssign,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,DateOfAssign)) as OriginDateTime,          
DateOfAssign = dbo.rvlf_fn_DayLightSavings(DateOfAssign,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,DateOfAssign),    
Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+        
 ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,        
 PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()) ,
 IsRtread,1 as IsRetreadingBit,'Retreaded' as TyreType
from  @Table2 ORDER BY OriginDateTime desc 
                
END 



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTyreStockDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
CREATE PROCEDURE [dbo].[rvlf_sp_GetTyreStockDetails]
@bigOrganizationId bigint = Null,                        
@bigUserId bigint = Null                     
          
AS          
-- =============================================          
-- Name   : rvlf_sp_GetTyreStockDetails 6,18         
-- Author  : Kapil          
-- Create date : 16-April-2014          
-- Description : Get Tyre Vendor Details          
-- Company  : TRINETRA 
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
-- =============================================          
BEGIN          
 -- SET NOCOUNT ON added to prevent extra result sets from          
 -- interfering with SELECT statements.          
 SET NOCOUNT ON;          
  
  
  BEGIN
	
		select VendorName,V.VendorId,BrandName,M.BrandID,ModelName,MD.ModelID,TotalQuantity,UsedQuantity,Available,
		cast(TotalQuantity AS VARCHAR)as SumTotal,CAST(UsedQuantity as VARCHAR) as SumUsed,CAST(Available as VARCHAR) as SumAvail
		from rvlfTyreStock S 
		inner join rvlfTyreVendorMaster V on V.VendorId = S.VendorId 
		INNER JOIN rvlfTyreMake M on M.BrandID = S.BrandID 
		INNER JOIN rvlfTyreModel  MD on MD.ModelID = S.ModelID 
		where 
		(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR S.OrganizationId= @bigOrganizationID)
		--AND(@Brand IS NULL OR @Brand ='' OR M.BrandID = @Brand)
		--AND(@Model IS NULL OR @Model ='' OR MD.ModelID = @Model)
		--AND(@Vendor Is NULL or @Vendor ='' OR V.VendorId = @Vendor)
		ORDER BY VendorName
  END
 set Nocount off;        
END 



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTyreStockReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
      
CREATE PROCEDURE [dbo].[rvlf_sp_GetTyreStockReport] 
@bigFleetID bigint = null, 
@Vendor int =NULL,
@Brand int = null,
@Model int =NULL,
@bigOrganizationID int =null,
@bigQueryingUser bigint = null,
@dtStartDate datetime = null,   
@dtEndDate datetime = null,
 @intBoxID varchar(max) = null      
AS              
/******************************************************************************************************************/              
-- Name		   :rvlf_sp_GetTyreStockReport '','','','',24,18
-- Author	   : Kapil              
-- Company     : Trinetra Technologies              
-- History     : <<Date(dd-MON-yyyy)>> Initial Reason              
--             : 15-April-2014 Created Intial Version             
/******************************************************************************************************************/ 
BEGIN

if @Vendor = 0 or @Vendor = ''
SET @Vendor = null

IF @Brand = '' or @Brand is null
	BEGIN
		SET @Brand = ''
	END 
	
	IF @Model = '' or @Model is null
	BEGIN
		SET @Model = ''
	END 
	
--select @TyreId
 Declare @dtFDate datetime =  null         
 Declare @dtEDate datetime =  null

 DECLARE @HoursToBeAdded INT = 0              
 DECLARE @MinsToBeAdded INT = 0              
 DECLARE @ConversionFactor numeric (10,2) = 1.0              
 DECLARE @DistanceCaptionPrefix varchar(15)              
 DECLARE @SpeedCaptionPrefix varchar(15)            
 DECLARE @DefaultDateFormat INT = 0;            
 DECLARE @Hours varchar(max) = 0      
 DECLARE @Minutes INT = 0  
 DECLARE @Sign char =0
 DECLARE @ToDate Datetime = NULL  
 DECLARE @FromDate Datetime = NULL
        
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
-- @Hours= HOURS,@ToDate = ToDate,@FromDate = FromDate,      
 --@Sign = SUBSTRING(Hours,1,1),@Minutes = SUBSTRING(Hours,5,2),      
 @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,@DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)              
 FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz              
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser              
           
--SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))              
--SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))      
 
  
DECLARE @tbl as Table 
(
BrandId int,
ModelId int,
Total bigint,
Used bigint,
Avail bigint,
OrganizationId bigint
)
 
 insert into @tbl 
 
select  BrandID,ModelID,sum(TotalQuantity),sum(UsedQuantity),sum(Available),OrganizationId FROM rvlfTyreStock GROUP BY BrandID,ModelID,OrganizationId
--SELECT * FROM @tbl 

select  distinct BrandName,M.BrandID,ModelName,MD.ModelID,s.Total as TotalQuantity,s.Used as UsedQuantity,
s.Avail as Available, 
a.SumTotal,a.SumUsed,A.SumAvailable, 
(select SUM(TotalQuantity) as Total from rvlfTyreStock S 
--inner join rvlfTyreVendorMaster V on V.VendorId = S.VendorId 
INNER JOIN rvlfTyreMake M on M.BrandID = S.BrandID 
INNER JOIN rvlfTyreModel  MD on MD.ModelID = S.ModelID  where 
(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR S.OrganizationId= @bigOrganizationID)) as Total,
(select SUM(UsedQuantity) as Used from rvlfTyreStock S 
--inner join rvlfTyreVendorMaster V on V.VendorId = S.VendorId 
INNER JOIN rvlfTyreMake M on M.BrandID = S.BrandID 
INNER JOIN rvlfTyreModel  MD on MD.ModelID = S.ModelID  where 
(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR S.OrganizationId= @bigOrganizationID)) as Used,
(select SUM(Available) as Avail from rvlfTyreStock S 
--inner join rvlfTyreVendorMaster V on V.VendorId = S.VendorId 
INNER JOIN rvlfTyreMake M on M.BrandID = S.BrandID 
INNER JOIN rvlfTyreModel  MD on MD.ModelID = S.ModelID 
 where 
(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR S.OrganizationId= @bigOrganizationID)) as Avail,
Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+        
 ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,
 PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())
 from @tbl S 
--inner join rvlfTyreVendorMaster V on V.VendorId = S.VendorId 
INNER JOIN rvlfTyreMake M on M.BrandID = S.BrandID 
INNER JOIN rvlfTyreModel  MD on MD.ModelID = S.ModelID 
INNER JOIN 
(
select Md.BrandID,SUM(TotalQuantity) as SumTotal,SUM(UsedQuantity) as  SumUsed,SUM(Available) as SumAvailable from rvlfTyreStock S 
--inner join rvlfTyreVendorMaster V on V.VendorId = S.VendorId 
INNER JOIN rvlfTyreMake M on M.BrandID = S.BrandID 
INNER JOIN rvlfTyreModel  MD on MD.ModelID = S.ModelID 
where
(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR S.OrganizationId= @bigOrganizationID)
AND(@Brand IS NULL OR @Brand ='' OR M.BrandID = @Brand)
AND(@Model IS NULL OR @Model ='' OR MD.ModelID = @Model)
--AND(@Vendor Is NULL or @Vendor ='' OR V.VendorId = @Vendor)
group by Md.BrandID) a on  a.BrandID = S.BrandID
where
(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR S.OrganizationId= @bigOrganizationID)
AND(@Brand IS NULL OR @Brand ='' OR M.BrandID = @Brand)
AND(@Model IS NULL OR @Model ='' OR MD.ModelID = @Model)
--AND(@Vendor Is NULL or @Vendor ='' OR V.VendorId = @Vendor)
ORDER BY BrandName

--select SUM(TotalQuantity) as Total,SUM(UsedQuantity) as Used,SUM(Available) as Available from rvlfTyreStock

                
END 



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetTyreVendorDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
                
CREATE PROCEDURE [dbo].[rvlf_sp_GetTyreVendorDetails]                 
@VendorID int = Null,                              
@bigOrganizationId bigint = Null,                              
@bigUserId bigint = Null,    
@VendorType char(3)=null    
                
AS                
-- =============================================                
-- Name   : rvlf_sp_GetTyreVendorDetails 2,1,18               
-- Author  : Kapil                
-- Create date : 17-Feb-2014                
-- Description : Get Tyre Vendor Details                
-- Company  : TRINETRA       
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                
-- =============================================                
BEGIN                
 -- SET NOCOUNT ON added to prevent extra result sets from                
 -- interfering with SELECT statements.                
  SET NOCOUNT ON;                
       
  IF @VendorID = 0 SET @VendorID = null              
        
  IF @VendorID is not null         
  BEGIN        
    -- Insert statements for procedure here                     
	IF @VendorType = 'LM'
	Begin
		select VendorId,VendorName,VendorAddress,VendorCity,VendorState,ZipCode,Email,Email1,Email2,ContactNo,MobileNo,VendorDesc from rvlfTyreVendorMaster         
		where IsDelete=0 and VendorId=@VendorID  and (VendorType = 'LMV' OR VendorType = 'LMC') ORDER BY VendorName 
	End
	Else
	Begin
		select VendorId,VendorName,VendorAddress,VendorCity,VendorState,ZipCode,Email,Email1,Email2,ContactNo,MobileNo,VendorDesc from rvlfTyreVendorMaster         
		where IsDelete=0 and VendorId=@VendorID  and VendorType=@VendorType order by VendorName 
	End
  END      

  ELSE      
  BEGIN    
	IF @VendorType = 'LM'
	Begin
		SELECT VendorId,VendorName,VendorAddress,CASE WHEN VendorCity='' THEN '-' ELSE VendorCity END as VendorCity ,    
		CASE WHEN VendorState='' THEN '-' ELSE VendorState END as VendorState,    
		CASE WHEN ZipCode='' THEN '-' ELSE ZipCode END as ZipCode,Email,Email1,Email2,ContactNo,MobileNo,VendorDesc from rvlfTyreVendorMaster         
		WHERE IsDelete=0 and OrganizationId =@bigOrganizationId   and (VendorType = 'LMV' OR VendorType = 'LMC') ORDER BY VendorName
	End
	Else
	Begin
		SELECT VendorId,VendorName,VendorAddress,CASE WHEN VendorCity='' THEN '-' ELSE VendorCity END as VendorCity ,    
		CASE WHEN VendorState='' THEN '-' ELSE VendorState END as VendorState,    
		CASE WHEN ZipCode='' THEN '-' ELSE ZipCode END as ZipCode,Email,Email1,Email2,ContactNo,MobileNo,VendorDesc from rvlfTyreVendorMaster         
		WHERE IsDelete=0 and OrganizationId =@bigOrganizationId   and VendorType=@VendorType  ORDER BY VendorName
	End
  END    

 SET NOCOUNT OFF;               
END       
      
      
--select * from rvlfTyreVendorMaster

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUnassignedBoxIDs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetUnassignedBoxIDs]

AS

/******************************************************************************/
--	Name		:	rvlf_sp_GetUnassignedBoxIDs
--	Description	:	To get the Box Ids which is not assigned to the vehicles
--	Author		:	L. Kumuthini
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	18-Nov-2009		Created Intial Version 
--				:	23-May-2011	TSK	Showd the missed BoxID 
/******************************************************************************/

BEGIN

	SET NOCOUNT ON
	
		SELECT BoxId FROM rvlfBoxSettings WHERE BoxId NOT IN (SELECT BoxId FROM rvlfVehicleAssignment)
		--	select l.BoxId + 1 as BoxId from Rvlfboxid as l  left outer join Rvlfboxid as r on l.BoxId + 1 = r.BoxId
		--	where r.BoxID is null;
		
	SET NOCOUNT OFF
END





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUnassignedEquipIds]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 2017-01-17
-- Description:	To load the devices that are newly created and yet to be assigned with equiprment - Customized for Ador
--				rvlf_sp_GetUnassignedEquipIds 86,294
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetUnassignedEquipIds]
	-- Add the parameters for the stored procedure here
	@bigOrganizationId	bigint = NULL, 
	@bigUserId			bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT	B.BoxId 
	From	rvlfBoxId B
	Inner	Join rvlfVehicleAssignment VA ON VA.BoxId = B.BoxId
	Inner	Join rvlfVehicle V ON V.VehicleId = VA.VehicleId
	Where	B.BoxId NOT IN (Select BoxId From rvlfMAKDevices Where OrganizationID = @bigOrganizationId)
	AND		B.OrganizationID = @bigOrganizationId and V.OrganizationID = @bigOrganizationId
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUnassignedFleetUsers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetUnassignedFleetUsers]        
/******************************************************        
Stored Procedure Name : rvlf_sp_GetUnassignedFleetUsers       
Purpose     : Retrieve unassigned fleet's Users       
Created by    : Uma        
Created date   : 11-Jul-09        
Updated by    :         
Updated date   : 19-May-2011 TSK Blocked hidden users        
*******************************************************/        
        
@FleetId int  = Null        
        
AS        
        
BEGIN         
         
        
SELECT usr.UserId, usr.UserName  FROM rvlfUser usr         
WHERE  (usr.UserName <> 'Administrator') AND UserId not in         
(SELECT ref.UserId   FROM rvlfFleetUsers ref         
WHERE  
 (usr.IsActive = 1) AND
 ((@FleetId is Null) or (@FleetId =0)  or (FleetId=@FleetId))) and usr.IsHidden <> 1  AND usr.IsDelete = 0  AND usr.IsRegisteredUser IS NULL  
 ORDER BY usr.UserName ASC      
        
END        
-- rvlf_sp_GetUnassignedFleetUsers 33


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUnassignedFleetVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetUnassignedFleetVehicles]  
/******************************************************  
Stored Procedure Name : rvlf_sp_GetUnassignedFleetVehicles  
Purpose     : Retrieve unassigned fleet's vehicles  
Created by    : Uma  
Created date   : 09-Jul-09  
Updated by    :   
Updated date   :   
*******************************************************/  
  
@FleetId int  = Null  
  
AS  
  
BEGIN   
   
  
SELECT veh.vehicleid, veh.VehicleDescription  FROM rvlfvehicle veh   
WHERE VehicleId not in   
(SELECT ref.vehicleid  FROM rvlfFleetVehicles ref   
WHERE ((@FleetId is Null) or (FleetId=@FleetId)))
ORDER BY veh.VehicleDescription ASC  
  
END  
-- rvlf_sp_GetUnassignedFleetVehicles 1


GO
/****** Object:  StoredProcedure [dbo].[RVLF_SP_GetUpdatePosition]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[RVLF_SP_GetUpdatePosition]
 (@boxID /*VehicleID*/ bigint = null
, @intBoxID /*BoxID*/ bigint = null,
  @bigQueryingUser bigint = null
)  
AS
/******************************************************************************/
--	Name		:	[RVLF_SP_GetUpdatePosition] null, 999222, 1
--	Description	:	To get the response for the command sent
--	Author		:	T. Sathish Kumar
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	08-Jan-2010 MJJC Included the message history mapping to change the icon for fuel.
--              :   09-Jan-2010 LK   Included the Land mark 
--				:	11-Jan-2010 MJJC To get the message details from the function
--				:	25-Jan-2010 MJJC To update the alarm details function parameters
--				:	26-Jan-2010 MJJC Mapped to user preferences which is deleted accidently
--				:	30-Jan-2010 MJJC To check the sensor off with duration for ignition status
--				:   20-Apr-2011 LK   Included the Driver Name
/******************************************************************************/
BEGIN 

	DECLARE @HoursToBeAdded INT = 0
	DECLARE @MinsToBeAdded INT = 0
	DECLARE @SpeedUnit varchar(50);
	
	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 ,
		   @SpeedUnit = 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 = @bigQueryingUser
    
	IF @intBoxID IS NOT NULL
	BEGIN
		SELECT @boxID = VehicleId from rvlfVehicleAssignment WHERE BoxId = @intBoxID
	END
	
	select MessageInID,IH.BoxId,
	DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,IH.OriginDateTime)) AS OriginDateTime,
	DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,IH.DateTimeReceived)) As DateTimeReceived,
	@SpeedUnit as Units,
	IH.ValidGps,IH.Latitude,IH.Longitude, 
	CASE WHEN IH.BoxMsgInTypeId =114 and  CHARINDEX('38;FuelTankLength=',IH.CustomProp,0) <> 0 then 186 
		 ELSE IH.BoxMsgInTypeId END as MessageID, 
	CASE WHEN IH.ValidGps = 0 THEN CAST(CAST((IH.Speed* @ConversionFactor) as int) as varchar(30)) 
		ELSE '0' END AS Speed,
	CASE WHEN SensorMask IS NOT NULL AND LEN(SensorMask)=8 THEN
		dbo.rvlf_fn_GetSensorMaskInformation(sensorMask,IH.BoxId) ELSE 'N/A' END as SensorInfo,
	CASE WHEN IH.Speed=0 OR IH.ValidGps >0 THEN -1 ELSE IH.Heading END As Heading, 
		ISNULL(IH.StreetAddress, 'Address is not resolved') as StreetAddress ,V.VehicleId,V.VehicleDescription,
	--CASE --WHEN IH.BoxMsgInTypeID in (11 , 2 , 3 , 13 , 9 , 14 , 15 , 16 , 17 , 24 , 18)
				--THEN dbo.rvlf_fn_GetAlarmDetails(IH.customprop,IH.BoxMsgInTypeID, IH.BoxId )
				--WHEN IH.BoxMsgInTypeId IN (5,6) THEN
		--			dbo.rvlf_fn_GetAlarmDetails(CAST( SUBSTRING(IH.CustomProp,
		--CHARINDEX('=',IH.CustomProp,1)+1,(CHARINDEX(';',IH.CustomProp,1)
		--			- CHARINDEX('=',IH.CustomProp,1))-1) as bigint), IH.BoxMsgInTypeId,IH.BoxId )
			--ELSE 
			dbo.rvlf_fn_GetAlarmDetails_Optimzd(IH.customprop,IH.BoxMsgInTypeID, IH.BoxId, IH.MessageInID,
				IH.OriginDateTime,'LanguageEn' )--CT.BoxMsgInTypeDesc 
			--END 
			as MessageDetails, IH.NearestLandmark,
			--CASE 
			--	WHEN IH.BoxMsgInTypeId = 37	/* Analog (Fuel) Sensor Status - LOW*/ THEN 3
			--	WHEN IH.BoxMsgInTypeId = 38	/* Analog (Fuel) Sensor Status - MEDIUM*/ THEN 4
			--	WHEN IH.BoxMsgInTypeId = 39	/* Analog (Fuel) Sensor Status - HIGH */ THEN 5
			--	WHEN IH.BoxMsgInTypeId = 11 AND CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,
			--		CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) = 27 THEN 6
			--	ELSE 0 END 
			CASE 
				WHEN IH.BoxMsgInTypeId = 37	/* Analog (Fuel) Sensor Status - LOW*/ THEN 3
				WHEN IH.BoxMsgInTypeId = 38	/* Analog (Fuel) Sensor Status - MEDIUM*/ THEN 4
				WHEN IH.BoxMsgInTypeId = 39	/* Analog (Fuel) Sensor Status - HIGH */ THEN 5
				WHEN IH.BoxMsgInTypeId = 11 AND CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,
					CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) = 27 THEN 6
				WHEN IH.BoxMsgInTypeId = 3 THEN 0			
				WHEN IH.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 FuelStatus,
		'' AS Landmark,
		  '-'   as DriverName	
	from rvlfMsgInHst IH Inner join rvlfVehicleAssignment VA on VA.BoxId = IH.BoxId
		INNER JOIN rvlfVehicle V on VA.VehicleId = V.VehicleId 
		INNER JOIN rvlfBoxMsgInType CT ON IH.BoxMsgInTypeId = CT.BoxMsgInTypeId
		--LEFT OUTER JOIN rvlfLandmark L ON IH.LandMarkID = L.LandmarkID
		--LEFT OUTER JOIN rvlfIButtonMapping BM on IH.BoxId = BM.BoxID
		--LEFT OUTER JOIN rvlfDriverMaster DM on DM.DriverId = BM.DriverId
	where MessageInID = (select MessageInID from rvlfMsgOutHst where BoxID = 
			(select BoxId from rvlfVehicleAssignment where VehicleId = @boxID)
		 and SentDateTime = (select Max(SentDateTime) 
				from rvlfMsgOutHst where BoxID = 
					(select BoxId from rvlfVehicleAssignment where VehicleId = @boxID)) and Acknowledged = 1) 
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUploadedVehiclesDocs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
--				rvlf_sp_GetUploadedVehiclesDocs 731
-- Author:		Anbarasu.E
-- Create date: 04-Aug-2016
-- Description:	<Fetches the documents uploaded for a particular vehicle for download.>
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetUploadedVehiclesDocs]
	-- Add the parameters for the stored procedure here
	@bigVehicleId			bigint			= null
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT	vd.VehicleId, v.VehicleDescription, vd.DocumentName, vd.DocumentPath 
	FROM	rvlfVehicleDocuments vd
	INNER	JOIN	rvlfVehicle	v ON v.VehicleId = vd.VehicleId
	WHERE	vd.VehicleId = @bigVehicleId and vd.IsDeleted = 0
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUserActivities]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetUserActivities]          
@bigOrganizationID bigint = null,     
@bigFleetID bigint = null,       
@dtStartDate datetime = null,  
@dtEndDate datetime = null,  
@frequency int = 7,        
@bigQueryingUser int = null        
AS          
/******************************************************************************/                          
-- Name  : rvlf_sp_GetUserActivities null,null,null,null,7,94        
-- Description : To get the details of user activities                          
-- Created date : 13-Sep-2011                        
-- Created by : Sakthi Gopinath S          
/******************************************************************************/                          
BEGIN          
 SET NOCOUNT ON          
           
  DECLARE @HoursToBeAdded INT = 0                            
  DECLARE @MinsToBeAdded INT = 0                            
  DECLARE @DefaultDateFormat INT = 0                          
  DECLARE @pasGeneratedDate varchar(50)        
        
  SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,      
  @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 = @bigQueryingUser        
           
  SELECT @pasGeneratedDate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())
  --@pasGeneratedDate=Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22)     
  
          
  Declare @noOfOrg int          
  --To get the total no of activated organization          
  SELECT @noOfOrg=COUNT(*) FROM rvlfOrganization o INNER JOIN rvlfOrganizationPackage OP          
  ON o.OrganizationId=OP.OrganizationID WHERE OP.IsActive=1 and OP.ExpiresOn > GETUTCDATE()          
            
  --To get the organization details of unused landmark,geozone,schedule report and commands          
  SELECT @noOfOrg as NoOfOrganization,o.OrganizationId,o.OrganizationName,      
  CASE WHEN L.LandmarkCount IS NULL THEN '-' ELSE CAST(L.LandmarkCount AS VARCHAR) END AS Landmark_Count,          
  CASE WHEN G.GeozoneCount IS NULL THEN '-' ELSE CAST(G.GeozoneCount AS VARCHAR) END AS Geozone_Count,          
  CASE WHEN SR.SRCount IS NULL THEN '-' ELSE CAST(SR.SRCount AS VARCHAR) END AS Schedule_Report_Count,          
  CASE WHEN SC.SCCount IS NULL THEN '-' ELSE CAST(SC.SCCount AS VARCHAR) END AS Schedule_Command_Count,        
  @pasGeneratedDate as PasGenerateddate             
  FROM rvlfOrganization o INNER JOIN rvlfOrganizationPackage op          
  ON op.OrganizationID = o.OrganizationId AND op.ExpiresOn > GETDATE() AND op.IsActive=1 LEFT OUTER JOIN          
  (SELECT OrganizationId,Count(*) AS LandmarkCount FROM rvlfLandmark Group By OrganizationId) L           
  ON L.OrganizationId = o.OrganizationId LEFT OUTER JOIN           
  (SELECT OrganizationId,Count(*) AS GeozoneCount FROM rvlfOrganizationGeozone Group By OrganizationId) G          
  ON G.OrganizationId = o.OrganizationId LEFT OUTER JOIN           
  (SELECT OrganizationId,Count(*) AS SRCount FROM rvlfSchedulingReport Group By OrganizationId) SR          
  ON SR.OrganizationId = o.OrganizationId LEFT OUTER JOIN           
  (SELECT cm.OrganizationId,Count(*) AS SCCount FROM rvlfScheduleOfCommandsMaster cm INNER JOIN rvlfUser u ON       
  cm.OrganizationId=u.OrganizationId and cm.UserId=u.UserId Group By cm.OrganizationId) SC          
  ON SC.OrganizationId = o.OrganizationId WHERE o.OrganizationId IS NOT NULL AND o.OrganizationId NOT IN (1,55,6,30)         
  AND (L.LandmarkCount IS NULL OR G.GeozoneCount IS NULL OR SR.SRCount IS NULL)          
           
  --To get the Inactivated User          
  SELECT A.OrganizationId,A.OrganizationName,A.NoOfVehicles,A.UserId,A.UserName,      
   Convert(varchar,A.LastLogin,@DefaultDateFormat) + ' ' + Convert(varchar,cast(A.LastLogin as time),22) AS LastLogin,        
   A.NoOfDays,Convert(varchar,A.ExpiresOn,@DefaultDateFormat) + ' ' + Convert(varchar,cast(A.ExpiresOn as time),22) AS ExpiresOn,@pasGeneratedDate AS PasGenerateddate FROM        
  (SELECT AB.OrganizationId,AB.OrganizationName,COUNT(v.VehicleId) AS NoOfVehicles,u.UserId,usr.UserName,AB.LoginDateTime AS LastLogin,AB.NoOfDays,AB.ExpiresOn      
  FROM rvlfUserLogin u INNER JOIN           
  (SELECT b.OrganizationId,d.OrganizationName,MAX(LoginDateTime) AS LoginDateTime,          
  DATEDIFF(DD,MAX(LoginDateTime),GETUTCDATE()) AS NoOfDays,OP.ExpiresOn        
  FROM rvlfUserLogin a           
  INNER JOIN rvlfUser b ON a.UserId=b.UserId and b.IsHidden <> 1 INNER JOIN rvlfOrganization d ON d.OrganizationId=b.OrganizationId           
  INNER JOIN rvlfOrganizationPackage OP ON d.OrganizationID=OP.OrganizationId AND OP.IsActive=1 AND OP.ExpiresOn > GETDATE()          
  GROUP BY b.OrganizationId,d.OrganizationName,OP.ExpiresOn           
  HAVING CONVERT(DATE,MAX(LoginDateTime),103) < CONVERT(DATE,DATEADD(DD,-@frequency,GETUTCDATE()),103))          
  AS AB ON u.LoginDateTime=AB.LoginDateTime INNER JOIN rvlfUser usr ON usr.UserId=u.UserId          
  INNER JOIN rvlfVehicle v on v.OrganizationId=AB.OrganizationId          
  INNER JOIN rvlfVehicleAssignment va ON va.VehicleId = v.VehicleId          
  --WHERE (@bigOrganizationID IS NULL OR (AB.OrganizationId = @bigOrganizationID))          
  GROUP BY AB.OrganizationId,AB.OrganizationName,u.UserId,usr.UserName,AB.LoginDateTime,AB.NoOfDays,AB.ExpiresOn        
  ) A  WHERE A.OrganizationId NOT IN (1,15,55,6,30) order by A.NoOfDays desc    
           
 SET NOCOUNT OFF          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUserDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetUserDetails]         
/******************************************************        
Stored Procedure Name : rvlf_sp_GetUserDetails @UserID=N'0',@bigOrganizationId=N'86',@bitIsActive=N'True',@intUserid=N'457'
Purpose     : Retrieve  Users' details        
Created by    : Uma        
Created date   : 17-Jul-09        
Update History:        
    17-Sep-2009 Jaya Chitra Added the required parameters        
    09-Oct-2009 Jaya Chitra Added the preferences retrieval        
    13-Feb-2010 Jaya Chitra Added the parameter to check status        
    08-Apr-2010 Jaya Chitra Added the user's time zone details and added the users list        
    29-Dec-2010 VN Restrict the deleted users.        
    24-Feb-2011 VN Included Hidden user visibility check    
    05-Aug-2011 Ranjith Hidden User code Included       
    10-Sep-2011 Ranjith Password Field accessable for particular user     
    07-Dec-2013 Kapil Added Mulitlingual Support  
*******************************************************/        
 @bigOrganizationId bigint = Null,        
 @bitIsActive bit = null,        
 @vcUserName varchar(50) = null,        
 @bitIsLocked bit = null,        
 @UserID int  = Null,        
 @intUserGroupID int = null,        
 @vcUserIDsList varchar(max) = null,    
 @intUserid int =null    
AS        
BEGIN               
 --IF @UserID = 0 SET @UserID = null        
 declare @Lang varchar(50)      
 --declare @CheckUser int =null,@lastname nvarchar(100),@CheckUGid int
 select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = (case when @intUserid is null then @vcUserIDsList else  @intUserid end)  
    
    DECLARE @tblUserList Table         
 (        
  UserID bigint        
 )        
--select @CheckUGid=UserGroupId from rvlfUserGroupAssignment where UserId=@intUserid
--select @lastname=LastName from rvlfUser where UserId=@intUserid
--if((@lastname like '%VXL%' or @lastname like '%trinetra%') or @CheckUGid=1)
--begin
--	set @CheckUser=null
--end
--else
--begin
--	set @CheckUser=1
--end
 IF @vcUserIDsList is not null        
  BEGIN        
   SELECT *,   
 CASE WHEN u.IsActive = 1 THEN (case when @Lang='LanguageEn' then 'Active' when @Lang='LanguageHindi' then N'सक्रिय'  else N'نشط' end) 
 ELSE (case when @Lang='LanguageEn' then 'Inactive' when @Lang='LanguageHindi' then N'निष्क्रिय' else N'غير نشط' end) END




 as ActiveStatusDisp,            
 CASE WHEN u.IsLocked= 1 THEN (case when @Lang='LanguageEn' then 'Locked' when @Lang='LanguageHindi' then N'बंद' else N'مقفل' end) 
 ELSE (case when @Lang='LanguageEn' then 'Unlocked' when @Lang='LanguageHindi' then N'खुला' else N'غير مقفل' end) END as LockedStatusDisp,         
    CASE WHEN u.IsActive = 1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus,        
    CASE WHEN u.IsLocked= 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,        
     CASE WHEN u.IsSMSQry= 1 THEN (case when @Lang='LanguageEn' then 'Enabled' when @Lang='LanguageHindi' then N'समर्थ बनाना' else N'تمكين' end)  
	 ELSE (case when @Lang='LanguageEn' then 'Disabled' when @Lang='LanguageHindi' then N'असमर्थ' else N'معاق' end

)  END as SMS,   
    dbo.rvlf_fn_GetUserGroupsByUserID(u.UserId) AS GroupBelongsTo,        
    p.DefaultFleetId, p.Distance, p.RefreshFrequencyId, p.TimezoneId,        
    t.HoursToBeAdded, t.MinToBeAdded,null as ExpiryDate    
    FROM rvlfUser u LEFT OUTER JOIN rvlfUserPreferences p ON u.UserId=p.UserId        
    INNER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId        
    INNER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId        
    INNER JOIN rvlfTimeZones t ON t.TimeZoneID = p.TimezoneId        
    WHERE         
    u.userID in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcUserIDsList,','))         
    AND U.ISDELETE=0 AND U.IsHidden <> 1        
    ORDER BY UserName ASC      
      
--    select ISNULL(SMSQryCount,0)  as SMSMaxCount, COUNT(IsSMSQry) as IsSMSCount,  
--CASE WHEN COUNT(IsSMSQry)>=(ISNULL(SMSQryCount,0)) THEN '0' ELSE '1' END as AllowSMS  
--from rvlfOrganization O inner JOIN rvlfUser U on O.OrganizationId = U.OrganizationId   
--where U.IsDelete =0 aND U.OrganizationId =@bigOrganizationId and U.IsSMSQry =1  
--group by SMSQryCount     

select 0  as SMSMaxCount, 0 as IsSMSCount,  0 as AllowSMS  

  --SELECT ga.UserGroupId, g.IsDefaultUserGroup, g.UserGroupName FROM rvlfUserGroupAssignment ga         
    --INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId        
    --WHERE ga.UserId = @UserID        
  END        
          
 ELSE IF @intUserGroupID IS NOT NULL        
 BEGIN        
  IF @vcUserName IS NOT NULL         
  BEGIN        
   INSERT INTO @tblUserList select UserId from rvlfUser where (@vcUserName IS NULL OR @vcUserName='' OR UserName like '%'+ @vcUserName +'%' )        
    and OrganizationId = @bigOrganizationID        
    AND ISDELETE=0        
  END        
          
  IF @intUserGroupID IS NOT NULL         
  BEGIN         
   INSERT INTO @tblUserList select UserId from rvlfUser where         
    UserId IN (SELECT ga.UserId FROM rvlfUserGroupAssignment ga WHERE         
    (@intUserGroupID IS NULL OR @intUserGroupID='' OR ga.UserGroupId = @intUserGroupID)) AND        
    OrganizationId = @bigOrganizationID        
    AND ISDELETE=0        
  END        
   SELECT *,     
 CASE WHEN u.IsActive = 1 THEN (case when @Lang='LanguageEn' then 'Active' when @Lang='LanguageHindi' then N'सक्रिय'  else N'نشط' end) 
 ELSE (case when @Lang='LanguageEn' then 'Inactive' when @Lang='LanguageHindi' then N'निष्क्रिय' else N'غير نشط' end) END

 as ActiveStatusDisp,            
 CASE WHEN u.IsLocked= 1 THEN (case when @Lang='LanguageEn' then 'Locked' when @Lang='LanguageHindi' then N'बंद' else N'مقفل' end) 
 ELSE (case when @Lang='LanguageEn' then 'Unlocked' when @Lang='LanguageHindi' then N'खुला' else N'غير مقفل' end) END as LockedStatusDisp,         
    CASE WHEN u.IsActive = 1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus,        
    CASE WHEN u.IsLocked= 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,    
     CASE WHEN u.IsSMSQry= 1 THEN (case when @Lang='LanguageEn' then 'Enabled' when @Lang='LanguageHindi' then N'समर्थ बनाना' else N'تمكين' end)  
	 ELSE (case when @Lang='LanguageEn' then 'Disabled' when @Lang='LanguageHindi' then N'असमर्थ' else N'معاق' end

)  END as SMS,       
    dbo.rvlf_fn_GetUserGroupsByUserID(u.UserId) AS GroupBelongsTo,        
    p.DefaultFleetId, p.Distance, p.RefreshFrequencyId, p.TimezoneId,        
    t.HoursToBeAdded, t.MinToBeAdded,null as ExpiryDate    
    FROM rvlfUser u LEFT OUTER JOIN rvlfUserPreferences p ON u.UserId=p.UserId        
    INNER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId        
    INNER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId        
    INNER JOIN rvlfTimeZones t ON t.TimeZoneID = p.TimezoneId        
    WHERE               
    --(username<> 'Administrator') AND        
    ((@UserID is Null) or (@UserID='') or (@UserID = 0)or ( u.UserId = @UserID) ) AND        
    ((@bigOrganizationId is Null) or (@bigOrganizationId='') or ( u.OrganizationId = @bigOrganizationId)) and        
    u.UserId IN (SELECT UserId FROM @tblUserList)        
	--and ((@CheckUser is Null) or (u.LastName = @lastname)) 
    AND (@bitIsActive is null or IsActive = @bitIsActive)        
    AND (@bitIsLocked is null or IsLocked = @bitIsLocked)        
    AND U.ISDELETE=0 AND U.IsHidden <> 1        
    ORDER BY UserName ASC         
            
    SELECT ga.UserGroupId, g.IsDefaultUserGroup, g.UserGroupName FROM rvlfUserGroupAssignment ga         
    INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId        
    WHERE ga.UserId = @UserID      
      
--    select ISNULL(SMSQryCount,0)  as SMSMaxCount, COUNT(IsSMSQry) as IsSMSCount,  
--CASE WHEN COUNT(IsSMSQry)>=(ISNULL(SMSQryCount,0)) THEN '0' ELSE '1' END as AllowSMS  
--from rvlfOrganization O inner JOIN rvlfUser U on O.OrganizationId = U.OrganizationId   
--where U.IsDelete =0 aND U.OrganizationId =@bigOrganizationId and U.IsSMSQry =1  
--group by SMSQryCount  
  
 select 0  as SMSMaxCount, 0 as IsSMSCount,  0 as AllowSMS   
    
 END        
 ELSE        
 BEGIN       
    declare @usergrp int    
    set @usergrp=(SELECT g.UserGroupId FROM rvlfUserGroupAssignment ga         
    INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId        
    WHERE ga.UserId = @intUserid)    
        
     --SELECT *,        
    SELECT u.UserId,u.UserName,u.Titleid,case when @intUserid in (12,14,303,19,18) then Password else null end as Password,u.Firstname,u.Lastname,
	u.Email,u.PhoneNo,u.MobileNo,u.OrganizationId,u.DisplayName,u.IsLocked,u.LockedDateTime,u.IsActive,u.IsPwdChanged,
	u.CreatedBy,u.CreatedDateTime,u.ModifiedBy,u.ModifiedDateTime,u.IsDelete,u.IsRegisteredUser,u.IsHidden,u.IsSMSQry,  
    p.UserPreferenceID,p.Userid,p.TimeZoneId,p.Distance,p.RefreshFrequencyId,p.OrganizationID,p.LandingPageId,p.Fuel,p.Lang,p.DefaultDateFormat,    
    ga.UserId,ga.UserGroupId,AssignedBy,g.UserGroupId,g.UserGroupName,g.UserGroupDesc,g.IsDefaultUserGroup,g.OrganizationId,g.CreatedBy,g.CreatedDate,g.ModifiedBy,g.ModifiedDate,t.TimeZoneName,t.TimeZoneDesc,t.HoursToBeAdded,t.MinToBeAdded,      
    CASE WHEN u.IsActive = 1 THEN (case when @Lang='LanguageEn' then 'Active' when @Lang='LanguageHindi' then N'सक्रिय'  else N'نشط' end) 
	ELSE (case when @Lang='LanguageEn' then 'Inactive' when @Lang='LanguageHindi' then N'निष्क्रिय' else N'غير نشط' end) 




END as ActiveStatusDisp,            
 CASE WHEN u.IsLocked= 1 THEN (case when @Lang='LanguageEn' then 'Locked' when @Lang='LanguageHindi' then N'बंद' else N'مقفل' end) 
 ELSE (case when @Lang='LanguageEn' then 'Unlocked' when @Lang='LanguageHindi' then N'खुला' else N'غير مقفل' end) END as LockedStatusDisp,         
    CASE WHEN u.IsActive = 1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus,        
    CASE WHEN u.IsLocked= 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,   
    CASE WHEN u.IsSMSQry= 1 THEN (case when @Lang='LanguageEn' then 'Enabled' when @Lang='LanguageHindi' then N'समर्थ बनाना' else N'تمكين' end)  
	ELSE (case when @Lang='LanguageEn' then 'Disabled' when @Lang='LanguageHindi' then N'असमर्थ' else N'معاق' end)




  END as SMS,        
    dbo.rvlf_fn_GetUserGroupsByUserID(u.UserId) AS GroupBelongsTo,        
    p.DefaultFleetId, p.Distance, p.RefreshFrequencyId, p.TimezoneId,        
    t.HoursToBeAdded, t.MinToBeAdded,null as ExpiryDate     
    FROM rvlfUser u LEFT OUTER JOIN rvlfUserPreferences p ON u.UserId=p.UserId        
    LEFT OUTER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId        
    LEFT OUTER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId        
    INNER JOIN rvlfTimeZones t ON t.TimeZoneID = p.TimezoneId        
    WHERE               
    --(username<> 'Administrator') AND        
    ((@UserID is Null) or (@UserID='') or  (@UserID = 0) or( u.UserId = @UserID)) AND        
    ((@bigOrganizationId is Null) or (@bigOrganizationId='') or ( u.OrganizationId = @bigOrganizationId))         
    AND (@bitIsActive is null or IsActive = @bitIsActive)        
    AND (@bitIsLocked is null or IsLocked = @bitIsLocked)        
    and(@vcUserName IS NULL or @vcUserName='' OR UserName like @vcUserName +'%' )        
    AND U.ISDELETE=0     
	--and ((@CheckUser is Null) or (u.LastName = @lastname)) 
    AND  IsHidden <> (case when @usergrp = 1 then 2 else 1 end)    
    ORDER BY UserName ASC         
    SELECT ga.UserGroupId, g.IsDefaultUserGroup, g.UserGroupName FROM rvlfUserGroupAssignment ga         
    INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId        
    WHERE ga.UserId = @UserID        
      
      
--    select ISNULL(SMSQryCount,0)  as SMSMaxCount, COUNT(IsSMSQry) as IsSMSCount,  
--CASE WHEN COUNT(IsSMSQry)>=(ISNULL(SMSQryCount,0)) THEN '0' ELSE '1' END as AllowSMS  
--from rvlfOrganization O inner JOIN rvlfUser U on O.OrganizationId = U.OrganizationId   
--where U.IsDelete =0 aND U.OrganizationId =@bigOrganizationId and U.IsSMSQry =1  
--group by SMSQryCount  

select 0  as SMSMaxCount, 0 as IsSMSCount,  0 as AllowSMS  
    
 END        
              
END              
-- rvlf_sp_GetUserDetailsNew 50,null,0,null        
-- [rvlf_sp_GetUserDetails] 1, null, null, 1        
--exec rvlf_sp_GetUserDetails @vcUserIDsList='1,44' 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUserDetailsNew]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetUserDetailsNew]     
/******************************************************    
Stored Procedure Name : rvlf_sp_GetUserDetails 2,1,'a'    
Purpose     : Retrieve  Users' details    
Created by    : Uma    
Created date   : 17-Jul-09    
Update History:    
    17-Sep-2009 Jaya Chitra Added the required parameters    
    09-Oct-2009 Jaya Chitra Added the preferences retrieval    
    13-Feb-2010 Jaya Chitra Added the parameter to check status    
    08-Apr-2010 Jaya Chitra Added the user's time zone details and added the users list    
    29-Dec-2010 VN Restrict the deleted users.    
    24-Feb-2011 VN Included Hidden user visibility check
    05-Aug-2011 Ranjith Hidden User code Included    
*******************************************************/    
 @bigOrganizationId bigint = Null,    
 @bitIsActive bit = null,    
 @vcUserName varchar(50) = null,    
 @bitIsLocked bit = null,    
 @UserID int  = Null,    
 @intUserGroupID int = null,    
 @vcUserIDsList varchar(max) = null,
 @intUserid int =null
AS    
BEGIN           
 --IF @UserID = 0 SET @UserID = null    
    DECLARE @tblUserList Table     
 (    
  UserID bigint    
 )    
     
 IF @vcUserIDsList is not null    
  BEGIN    
   SELECT *,     
    CASE WHEN u.IsActive = 1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus,    
    CASE WHEN u.IsLocked= 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,    
    dbo.rvlf_fn_GetUserGroupsByUserID(u.UserId) AS GroupBelongsTo,    
    p.DefaultFleetId, p.Distance, p.RefreshFrequencyId, p.TimezoneId,    
    t.HoursToBeAdded, t.MinToBeAdded
    FROM rvlfUser u LEFT OUTER JOIN rvlfUserPreferences p ON u.UserId=p.UserId    
    INNER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId    
    INNER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId    
    INNER JOIN rvlfTimeZones t ON t.TimeZoneID = p.TimezoneId    
    WHERE           
    u.userID in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcUserIDsList,','))     
    AND U.ISDELETE=0 AND U.IsHidden <> 1    
    ORDER BY UserName ASC     
        
    --SELECT ga.UserGroupId, g.IsDefaultUserGroup, g.UserGroupName FROM rvlfUserGroupAssignment ga     
    --INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId    
    --WHERE ga.UserId = @UserID    
  END    
      
 ELSE IF @intUserGroupID IS NOT NULL    
 BEGIN    
  IF @vcUserName IS NOT NULL     
  BEGIN    
   INSERT INTO @tblUserList select UserId from rvlfUser where (@vcUserName IS NULL OR @vcUserName='' OR UserName like '%'+ @vcUserName +'%' )    
    and OrganizationId = @bigOrganizationID    
    AND ISDELETE=0    
  END    
      
  IF @intUserGroupID IS NOT NULL     
  BEGIN     
   INSERT INTO @tblUserList select UserId from rvlfUser where     
    UserId IN (SELECT ga.UserId FROM rvlfUserGroupAssignment ga WHERE     
    (@intUserGroupID IS NULL OR @intUserGroupID='' OR ga.UserGroupId = @intUserGroupID)) AND    
    OrganizationId = @bigOrganizationID    
    AND ISDELETE=0    
  END    
   SELECT *,     
    CASE WHEN u.IsActive = 1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus,    
    CASE WHEN u.IsLocked= 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,    
    dbo.rvlf_fn_GetUserGroupsByUserID(u.UserId) AS GroupBelongsTo,    
    p.DefaultFleetId, p.Distance, p.RefreshFrequencyId, p.TimezoneId,    
    t.HoursToBeAdded, t.MinToBeAdded
    FROM rvlfUser u LEFT OUTER JOIN rvlfUserPreferences p ON u.UserId=p.UserId    
    INNER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId    
    INNER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId    
    INNER JOIN rvlfTimeZones t ON t.TimeZoneID = p.TimezoneId    
    WHERE           
    --(username<> 'Administrator') AND    
    ((@UserID is Null) or (@UserID='') or (@UserID = 0)or ( u.UserId = @UserID) ) AND    
    ((@bigOrganizationId is Null) or (@bigOrganizationId='') or ( u.OrganizationId = @bigOrganizationId)) and    
    u.UserId IN (SELECT UserId FROM @tblUserList)    
    AND (@bitIsActive is null or IsActive = @bitIsActive)    
    AND (@bitIsLocked is null or IsLocked = @bitIsLocked)    
    AND U.ISDELETE=0 AND U.IsHidden <> 1    
    ORDER BY UserName ASC     
        
    SELECT ga.UserGroupId, g.IsDefaultUserGroup, g.UserGroupName FROM rvlfUserGroupAssignment ga     
    INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId    
    WHERE ga.UserId = @UserID    
 END    
 ELSE    
 BEGIN   
       
    declare @usergrp int
    set @usergrp=(SELECT g.UserGroupId FROM rvlfUserGroupAssignment ga     
    INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId    
    WHERE ga.UserId = @intUserid)
    
    SELECT *,    
    CASE WHEN u.IsActive = 1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus,    
    CASE WHEN u.IsLocked= 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,    
    dbo.rvlf_fn_GetUserGroupsByUserID(u.UserId) AS GroupBelongsTo,    
    p.DefaultFleetId, p.Distance, p.RefreshFrequencyId, p.TimezoneId,    
    t.HoursToBeAdded, t.MinToBeAdded
    FROM rvlfUser u LEFT OUTER JOIN rvlfUserPreferences p ON u.UserId=p.UserId    
    INNER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId    
    INNER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId    
    INNER JOIN rvlfTimeZones t ON t.TimeZoneID = p.TimezoneId    
    WHERE           
    --(username<> 'Administrator') AND    
    ((@UserID is Null) or (@UserID='') or  (@UserID = 0) or( u.UserId = @UserID)) AND    
    ((@bigOrganizationId is Null) or (@bigOrganizationId='') or ( u.OrganizationId = @bigOrganizationId))     
    AND (@bitIsActive is null or IsActive = @bitIsActive)    
    AND (@bitIsLocked is null or IsLocked = @bitIsLocked)    
    and(@vcUserName IS NULL or @vcUserName='' OR UserName like @vcUserName +'%' )    
    AND U.ISDELETE=0 AND  IsHidden <> (case when @usergrp = 1 then 2 else 1 end)
    ORDER BY UserName ASC     
    SELECT ga.UserGroupId, g.IsDefaultUserGroup, g.UserGroupName FROM rvlfUserGroupAssignment ga     
    INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId    
    WHERE ga.UserId = @UserID    

 END    
          
END          
-- rvlf_sp_GetUserDetailsNew 50,null,0,null    
-- [rvlf_sp_GetUserDetails] 1, null, null, 1    
--exec rvlf_sp_GetUserDetails @vcUserIDsList='1,44'

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUserFeedbacks]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.e
-- Create date: 15-05-2015
-- Description:	Loads User Feedbacks for AnglerAdmin view.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetUserFeedbacks]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT	ufb.UserFeedbackId, ufb.UserId, org.OrganizationName, usr.UserName, 
			convert(varchar,ufb.FeedbackDate,106) as FeedbackDate, ufb.FeedbackText, 
			Case ufb.Status 
			When 0 then 'Not viewed'
			When 1 then 'Replied'
			End as Status
	FROM	rvlfUserFeedback ufb
	Inner Join rvlfOrganization org On ufb.OrganizationId = org.OrganizationId
	Inner Join rvlfUser usr On ufb.UserId = usr.UserId
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUserGroup]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetUserGroup]
	@userGroupId int=null
	
		
AS
/******************************************************************************/
--	Name		:	[[rvlf_sp_GetUserGroup]]
--	Description	:	To GET user group details.
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	23-Nov-2009	VN	Created Intial Version 
/******************************************************************************/

BEGIN
	SELECT UserGroupName,UserGroupDesc,LockUserTries  FROM rvlfUserGroup WHERE UserGroupId=@userGroupId
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUserGroupAssignments]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetUserGroupAssignments]  
 @intUserGroupId int ,  
 @bigOrganizationID bigint = null,  
 @bitIsAssigned bit = 0,  
 @vcUserName varchar(50) = null,
 @intUserid int = null          
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetUserGroupAssignments  
-- Description : To get assinged and unassinged users in User Groups  
-- Author  : Kumuthini. L  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 27-Jul-2009  Created Intial Version   
--    : 29-Dec-2010 Restricted the deleteted users  
--    : 19-May-2011 Restricted the hidden users  
--	  :	07-Dec-2013 Kapil Added Mulitlingual Support
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
 
 Declare @Lang varchar(50)                     
 select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @intUserid      
   
  declare @usergrp int    
    set @usergrp=(SELECT g.UserGroupId FROM rvlfUserGroupAssignment ga         
    INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId        
    WHERE ga.UserId = @intUserid) 
	--declare @CheckUser int =null,@lastname nvarchar(100),@CheckUGid int
	--select @CheckUGid=UserGroupId from rvlfUserGroupAssignment where UserId=@intUserid
	--select @lastname=LastName from rvlfUser where UserId=@intUserid
	--if((@lastname like '%VXL%' or @lastname like '%trinetra%') or @CheckUGid=1)
	--begin
	--	set @CheckUser=null
	--end
	--else
	--begin
	--	set @CheckUser=1
	--end
 IF @bitIsAssigned = 0   
 BEGIN  
  -- Select all the users from the User Information which is not present in User Group Assignment  
  select distinct(v.UserId), v.UserName, v.DisplayName, v.Firstname,  
    v.LastName, v.IsActive, v.IsLocked, dbo.rvlf_fn_GetUserGroupsByUserID(v.UserId) AS GroupBelongsTo,  
    CASE WHEN v.IsActive = 1 THEN (case when @Lang='LanguageEn' then 'Active' when @Lang='LanguageHindi' then N'8		M	0	?	/	'  else N'F47' end) ELSE (case when @Lang='LanguageEn' then 'Inactive' when @Lang='LanguageHindi' then N'(	?	7	M		M	0	?	/	' else N':J1 F47' end) END as ActiveStatusDisp,          
	CASE WHEN v.IsLocked= 1 THEN (case when @Lang='LanguageEn' then 'Locked' when @Lang='LanguageHindi' then N',		&	' else N'EBAD' end) ELSE (case when @Lang='LanguageEn' then 'Unlocked' when @Lang='LanguageHindi' then N'	A	2	>	' else N':J1 EBAD' end) END as LockedStatusDisp,       
     
    CASE WHEN v.IsActive =1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus,  
    CASE WHEN v.IsLocked= 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,v.IsHidden     
  FROM rvlfUser v   
  WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)  
      AND (@vcUserName IS NULL OR @vcUserName='' OR v.UserName LIKE @vcUserName + '%')  
   AND v.UserId NOT IN  
    ( SELECT ug.UserId FROM rvlfUserGroupAssignment ug WHERE UserGroupId = @intUserGroupId)   
   AND V.ISDELETE=0 AND V.IsHidden <> (case when @usergrp = 1 then 2 else 1 end) AND v.IsRegisteredUser is null 
   --and ((@CheckUser is Null) or (v.LastName = @lastname)) 
  ORDER BY UserName asc  
 END   
 ELSE IF @bitIsAssigned = 1  
 BEGIN  
  -- SELECT the users assinged to the User Group  
  select distinct(v.UserId), v.UserName, v.DisplayName, v.Firstname,  
    v.LastName, v.IsActive, v.IsLocked, dbo.rvlf_fn_GetUserGroupsByUserID(v.UserId) AS GroupBelongsTo,  
    CASE WHEN v.IsActive = 1 THEN (case when @Lang='LanguageEn' then 'Active' when @Lang='LanguageHindi' then N'8		M	0	?	/	'  else N'F47' end) ELSE (case when @Lang='LanguageEn' then 'Inactive' when @Lang='LanguageHindi' then N'(	?	7	M		M	0	?	/	' else N':J1 F47' end) END as ActiveStatusDisp,          
	CASE WHEN v.IsLocked= 1 THEN (case when @Lang='LanguageEn' then 'Locked' when @Lang='LanguageHindi' then N',		&	' else N'EBAD' end) ELSE (case when @Lang='LanguageEn' then 'Unlocked' when @Lang='LanguageHindi' then N'	A	2	>	' else N':J1 EBAD' end) END as LockedStatusDisp,       
      
    CASE WHEN v.IsActive =1 THEN 'Active' ELSE 'Inactive' END as ActiveStatus,  
    CASE WHEN v.IsLocked= 1 THEN 'Locked' ELSE 'Unlocked' END as LockedStatus,v.IsHidden    
  FROM rvlfUser v   
  INNER JOIN rvlfUserGroupAssignment ug ON v.UserId = ug.UserId   
  WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)  
  AND (@vcUserName IS NULL OR @vcUserName='' OR v.UserName LIKE @vcUserName + '%')  
   AND ug.UserGroupId = @intUserGroupId  
   AND V.ISDELETE=0 AND V.IsHidden <> (case when @usergrp = 1 then 2 else 1 end)  AND v.IsRegisteredUser is null 
   --and ((@CheckUser is Null) or (v.LastName = @lastname)) 
  ORDER BY UserName asc  
 END  
   
 SET NOCOUNT OFF  
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUserGroupPriviledges]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetUserGroupPriviledges]
@intUserGroupId AS INT = NULL,
@bitIsNonAnglerAdmin AS BIT = 0,
@bigOrganizationID AS BIGINT

AS
/****************************************************************************************/
--	Name		  : rvlf_sp_GetUserGroupPriviledges @bigOrganizationID=86,@intUserGroupId=0
--	Description	  :	To get the User Group Priviledges
--	Author		  :	Kumuthini. L
--	Created Date  : 01-Dec-09
--  History		  :
--				  : 05-Dec-2009 MJJC	Included the parent module restriction
--				  : 25-Mar-2010 MJJC	Included the solution based retrieval
--				  : 26-May-2011 VN		Retrive the modules and operatration based on the security admin.
--				  : 27-Apr-2013 SAKTHI	Check condition for mobile application
/***************************************************************************************/
BEGIN
	SET NOCOUNT ON 
	
	DECLARE @bigPackageId AS BIGINT = 0
	SET @bigPackageId = (SELECT PackageId FROM rvlfOrganizationPackage WHERE OrganizationID = @bigOrganizationID AND IsActive = 1) 
	DECLARE @bigSolutionId bigint
	SET @bigSolutionId = (SELECT SolutionID FROM rvlfOrganizationSolution WHERE  OrganizationID = @bigOrganizationID) 
	DECLARE @bigMobileOrgId AS INT = 0
	SELECT @bigMobileOrgId = ISNULL(OrgId,0) FROM rvlfOrganizationServiceURL_App WHERE OrgId = @bigOrganizationID
	IF(@bigPackageId > 0)
	BEGIN
		IF(@intUserGroupId IS NOT NULL AND @intUserGroupId > 0)
		BEGIN
		 print 'IN'
			SELECT m.ModuleID, @intUserGroupId AS UserGroupId, 
			CASE WHEN @bigMobileOrgId <> 0 THEN REPLACE(REPLACE(s.ModuleName,'Fleet','Group'),'Vehicle','Asset') ELSE s.ModuleName END AS ModuleName,
			CASE WHEN @bigMobileOrgId <> 0 THEN REPLACE(REPLACE(s.ModuleDesc,'Fleet','Group'),'Vehicle','Asset') ELSE s.ModuleDesc END AS ModuleDesc,   
			--s.ModuleName, s.ModuleDesc, 
			dbo.rvlf_fn_GetModulesOperations(NULL,@intUserGroupId,1) AS ModuleList FROM rvlfModule m
			INNER JOIN rvlfSolutionModules s ON m.ModuleID = s.ModuleId
			WHERE 
			--m.ModuleID IN (SELECT ModuleID FROM rvlfPackageOperations WHERE PackageId = @bigPackageId)
			m.ModuleID IN(SELECT DISTINCT UG.ModuleId from  rvlfUserGroupSecurity UG 
			INNER JOIN rvlfPackageOperations PO on PO.ModuleID = UG.ModuleId
			where PO.PackageId = @bigPackageId)
			AND m.ModuleID NOT IN (SELECT ParentModuleId FROM rvlfModule WHERE ParentModuleId IS NOT NULL)
			AND s.SolutionId = @bigSolutionId
			
		   	SELECT t.OperationTypeId, t.OperationTypeName , t.OperationDesc, s.ModuleID, s.ModuleName, s.ModuleDesc, 
			dbo.rvlf_fn_GetModulesOperations(NULL,@intUserGroupId,0) AS OperationsList FROM rvlfOperationType t
			INNER JOIN rvlfModule m ON t.ModuleID = m.ModuleID
			INNER JOIN rvlfSolutionModules s ON m.ModuleID = s.ModuleId
			INNER JOIN rvlfSolutionOperation fs ON fs.OperationId = t.OperationTypeId
			WHERE 
			----t.OperationTypeId IN (SELECT OperationID FROM rvlfPackageOperations WHERE PackageId = @bigPackageId)
			--t.OperationTypeId IN(SELECT DISTINCT UG.OperationTypeId from  rvlfUserGroupSecurity UG 
		 --  INNER JOIN rvlfPackageOperations PO on PO.OperationID = UG.OperationTypeId
		 --  where PO.PackageId = @bigPackageId)
		t.OperationTypeId IN (SELECT OperationID FROM rvlfPackageOperations WHERE PackageId = @bigPackageId)  and   
		t.OperationTypeId IN(SELECT DISTINCT OperationId FROM rvlfUserGroup UG  
		INNER JOIN rvlfUserGroupSecurity UGS ON UGS.UserGroupId =UG.UserGroupId  
		INNER JOIN rvlfPackageOperations PO on PO.OperationID = UGS.OperationTypeId 
		WHERE OrganizationId=@bigOrganizationID AND IsDefaultUserGroup =1 and PO.PackageId = @bigPackageId)
			AND s.SolutionId = @bigSolutionId AND fs.SolutionId= @bigSolutionId AND t.OperationTypeId <> 144 
			ORDER BY t.OperationTypeName ASC
		  
        END
        ELSE
        BEGIN
			SELECT m.ModuleID, NULL AS UserGroupId, NULL AS UserGroupName, NULL AS UserGroupDesc, 
			CASE WHEN @bigMobileOrgId <> 0 THEN REPLACE(REPLACE(s.ModuleName,'Fleet','Group'),'Vehicle','Asset') ELSE s.ModuleName END AS ModuleName,
			CASE WHEN @bigMobileOrgId <> 0 THEN REPLACE(REPLACE(s.ModuleDesc,'Fleet','Group'),'Vehicle','Asset') ELSE s.ModuleDesc END AS ModuleDesc,   
			--s.ModuleName, s.ModuleDesc, 
			NULL AS ModuleList FROM rvlfModule m
			INNER JOIN rvlfSolutionModules s ON m.ModuleID = s.ModuleId
			WHERE m.ModuleID IN (SELECT ModuleID FROM rvlfPackageOperations WHERE PackageId = @bigPackageId)
			AND M.ModuleID IN(SELECT DISTINCT ModuleId FROM rvlfUserGroup UG
					INNER JOIN rvlfUserGroupSecurity UGS ON UGS.UserGroupId =UG.UserGroupId 
				WHERE OrganizationId=@bigOrganizationID AND IsDefaultUserGroup =1)
			AND m.ModuleID NOT IN (SELECT ParentModuleId FROM rvlfModule WHERE ParentModuleId IS NOT NULL)
			AND s.SolutionId = @bigSolutionId
			
			SELECT t.OperationTypeId,
			CASE WHEN @bigMobileOrgId <> 0 THEN REPLACE(REPLACE(fs.OperationTypeName,'Fleet','Group'),'Vehicle','Asset') ELSE t.OperationTypeName END AS OperationTypeName,
			CASE WHEN @bigMobileOrgId <> 0 THEN REPLACE(REPLACE(fs.OperationDesc,'Fleet','Group'),'Vehicle','Asset') ELSE t.OperationDesc END AS OperationDesc,   
			s.ModuleID, 
			CASE WHEN @bigMobileOrgId <> 0 THEN REPLACE(REPLACE(s.ModuleName,'Fleet','Group'),'Vehicle','Asset') ELSE s.ModuleName END AS ModuleName,
			CASE WHEN @bigMobileOrgId <> 0 THEN REPLACE(REPLACE(s.ModuleDesc,'Fleet','Group'),'Vehicle','Asset') ELSE s.ModuleDesc END AS ModuleDesc,
			-- fs.OperationTypeName , fs.OperationDesc, s.ModuleID, s.ModuleName, s.ModuleDesc, 
			NULL AS OperationsList FROM rvlfOperationType t
			INNER JOIN rvlfModule m ON t.ModuleID = m.ModuleID
			INNER JOIN rvlfSolutionModules s ON m.ModuleID = s.ModuleId
			INNER JOIN rvlfSolutionOperation fs ON fs.OperationId = t.OperationTypeId
			WHERE t.OperationTypeId IN (SELECT OperationID FROM rvlfPackageOperations WHERE PackageId = @bigPackageId)
			AND t.OperationTypeId IN(SELECT DISTINCT OperationId FROM rvlfUserGroup UG
					INNER JOIN rvlfUserGroupSecurity UGS ON UGS.UserGroupId =UG.UserGroupId 
				WHERE OrganizationId=@bigOrganizationID AND IsDefaultUserGroup =1)
			AND s.SolutionId = @bigSolutionId AND fs.SolutionId= @bigSolutionId AND t.OperationTypeId <> 144 
			ORDER BY t.OperationTypeName ASC
        
        END		
	END
	
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUserlist]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetUserlist]         
/******************************************************        
Stored Procedure Name : rvlf_sp_GetAllUsers    389    
Purpose     : Retrieve all Users        
Created by    : Uma        
Created date   : 11-Jul-09        
Updated by    :         
Updated date   :         
*******************************************************/        
        
@CustomerID nchar(20)  = Null,
@OrgId nchar(20)  = Null         
        
AS        
        
BEGIN         
         
 SELECT UserName,UserId,Firstname,LastName from rvlfUser         
        
 WHERE CustomerID=  @CustomerID AND OrganizationId= @OrgId-- AND LastName LIKE '%vxl%'    
  
 ORDER BY UserName ASC   
        
END        
-- rvlf_sp_GetAllUsers Null  



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUserPriviledges]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetUserPriviledges]

@intUserGroupId AS int,
@bitIsNonAnglerAdmin AS bit = 0,
@bigOrganizationID AS bigint = NULL

AS
/****************************************************************************************/
--	Name		  : rvlf_sp_GetUserPriviledges
--	Description	  :	To get the User Priviledges
--	Author		  :	Kumuthini. L
--	Created Date  : 21-Sep-09
--  Modified Date :
/***************************************************************************************/
BEGIN
	SET NOCOUNT ON 
	
	IF(@intUserGroupId > 0)
	BEGIN
	
	   IF(@bitIsNonAnglerAdmin = 0)
	   BEGIN
			SELECT M.ModuleID, M.ModuleName, OT.OperationTypeId, OT.OperationTypeName,
			  CASE WHEN UP.UserGroupId IS NULL THEN 'false' ELSE 'true' END AS 'AssignPrevilege'
			FROM rvlfModule M 
			INNER JOIN rvlfOperationType OT ON OT.ModuleID = M.ModuleID
			LEFT OUTER JOIN rvlfUserPriviledges UP ON UP.OperationTypeId = OT.OperationTypeId AND UP.UserGroupId = @intUserGroupId
			ORDER BY OT.OperationTypeName ASC
	   END
	   ELSE
	   BEGIN
			SELECT M.ModuleID, M.ModuleName, OT.OperationTypeId, OT.OperationTypeName,
			  CASE WHEN UP.UserGroupId IS NULL THEN 'false' ELSE 'true' END AS 'AssignPrevilege'
			FROM rvlfModule M 
			INNER JOIN rvlfOperationType OT ON OT.ModuleID = M.ModuleID
			LEFT OUTER JOIN rvlfUserPriviledges UP ON UP.OperationTypeId = OT.OperationTypeId AND UP.UserGroupId = @intUserGroupId
			WHERE M.IsVisibleToNonAnglerAdmin = 1 AND OT.IsVisibleToNonAnglerAdmin = 1
			ORDER BY OT.OperationTypeName ASC	
	   END	
	END
	
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUserPriviledgesByOperation]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetUserPriviledgesByOperation]

@vcType AS Varchar(3),
@vcOprIds AS Varchar(Max) = NULL,
@intUserGroupId AS int,
@bitIsNonAnglerAdmin AS bit = 1,
@bigOrganizationID AS bigint = NULL

AS
/****************************************************************************************/
--	Name		  : rvlf_sp_GetUserPriviledges
--	Description	  :	To get the User Priviledges
--	Author		  :	Kumuthini. L
--	Created Date  : 21-Sep-09
--  Modified Date :
/***************************************************************************************/
BEGIN
	SET NOCOUNT ON 
	
	IF(@intUserGroupId > 0)
	BEGIN
	
	   IF(@bitIsNonAnglerAdmin = 0)
	   BEGIN
	        IF(@vcType = 'All')
	        BEGIN
				SELECT M.ModuleID, M.ModuleName, OT.OperationTypeId, OT.OperationTypeName,
				  CASE WHEN UP.UserGroupId IS NULL THEN 'false' ELSE 'true' END AS 'AssignPrevilege'
				FROM rvlfModule M 
				INNER JOIN rvlfOperationType OT ON OT.ModuleID = M.ModuleID
				LEFT OUTER JOIN rvlfUserPriviledges UP ON UP.OperationTypeId = OT.OperationTypeId AND UP.UserGroupId = @intUserGroupId
			END
			ELSE
			BEGIN
			    
				SELECT M.ModuleID, M.ModuleName, OT.OperationTypeId, OT.OperationTypeName,
				CASE WHEN UP.UserGroupId IS NULL THEN 'false' ELSE 'true' END AS 'AssignPrevilege'
				FROM rvlfModule M 
				INNER JOIN rvlfOperationType OT ON OT.ModuleID = M.ModuleID
				LEFT OUTER JOIN rvlfUserPriviledges UP ON UP.OperationTypeId = OT.OperationTypeId AND UP.UserGroupId = @intUserGroupId
				WHERE OT.OperationTypeId IN (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcOprIds,','))
			END
	   END
	   ELSE
	   BEGIN
		    IF(@vcType = 'All')
	        BEGIN
				SELECT M.ModuleID, M.ModuleName, OT.OperationTypeId, OT.OperationTypeName,
				  CASE WHEN UP.UserGroupId IS NULL THEN 'false' ELSE 'true' END AS 'AssignPrevilege'
				FROM rvlfModule M 
				INNER JOIN rvlfOperationType OT ON OT.ModuleID = M.ModuleID
				LEFT OUTER JOIN rvlfUserPriviledges UP ON UP.OperationTypeId = OT.OperationTypeId AND UP.UserGroupId = @intUserGroupId
				WHERE M.IsVisibleToNonAnglerAdmin = 1 AND OT.IsVisibleToNonAnglerAdmin = 1
			END
			ELSE
			BEGIN
				SELECT M.ModuleID, M.ModuleName, OT.OperationTypeId, OT.OperationTypeName,
				  CASE WHEN UP.UserGroupId IS NULL THEN 'false' ELSE 'true' END AS 'AssignPrevilege'
				FROM rvlfModule M 
				INNER JOIN rvlfOperationType OT ON OT.ModuleID = M.ModuleID
				LEFT OUTER JOIN rvlfUserPriviledges UP ON UP.OperationTypeId = OT.OperationTypeId AND UP.UserGroupId = @intUserGroupId
				WHERE M.IsVisibleToNonAnglerAdmin = 1 AND OT.IsVisibleToNonAnglerAdmin = 1
				AND OT.OperationTypeId IN (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcOprIds,','))
			END
	   END		
	END
	
	SET NOCOUNT OFF
END

--exec [rvlf_sp_GetUserPriviledges] 1,1,1

--delete from rvlfUserPriviledges

--exec  rvlf_sp_GetUserPriviledgesByOperation 'All','17,18,19,20,21',3,0,1


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUsers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetUsers]      
 @bigOrganizationID bigint = null,      
 @bigFleetID bigint = null,      
 @bigUserID bigint = null,      
 @bigQueryingUser bigint = 0,      
 @vcUserName varchar(50) = null,      
 @cOrganizationCode varchar(50)= null      
AS      
/******************************************************************************/      
-- Name  : rvlf_sp_GetUsers       
-- Description : To get the users      
--    :   Pass the valu 0 (Zero) to @bigQueryingUser if the user is angler admin      
-- Author  : M. Jebamalai Jaya Chitra.      
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--    : 04-Jun-2009 MJJC Created Intial Version       
--    :   13-Jul-09 Arun Vijai included UserName and OrganizationCode in where clause       
--    : 29-Dec-2010 Restricted the deleteted users      
--    : 28-Mar-2011 TSK Blocked the hidden user from viewing      
/******************************************************************************/      
BEGIN      
 SET NOCOUNT ON       
       
       
 --If @vcUserName is null      
 --Begin      
 -- set @vcUserName =  '%'      
 --End      
       
 --If @vcOrganizationCode is null      
 --Begin      
 -- set @vcOrganizationCode =  '%'      
 --End      
      
 --SELECT       
 -- r.*,g.OrganizationCode      
 --FROM rvlfUser r       
 --LEFT OUTER JOIN rvlfOrganization g ON r.OrganizationId = g.OrganizationId      
 --where (@vcUsername IS NULL OR @vcUsername='' OR UserName = @vcUsername) and      
 --(@cOrganizationCode IS NULL OR @cOrganizationCode='' OR  g.OrganizationCode =@cOrganizationCode)      
 -- AND R.ISDELETE=0 and (R.IsHidden is null or R.IsHidden = 0)      
 
 IF EXISTS (Select * from rvlfUser where UserName = @vcUserName)  
  begin  
   SELECT r.*,g.OrganizationCode  FROM rvlfUser r       
   LEFT OUTER JOIN rvlfOrganization g ON r.OrganizationId = g.OrganizationId      
   where (@vcUsername IS NULL OR @vcUsername='' OR UserName = @vcUsername) and      
   (@cOrganizationCode IS NULL OR @cOrganizationCode='' OR  g.OrganizationCode =@cOrganizationCode)      
   AND R.ISDELETE=0 and (R.IsHidden is null or R.IsHidden = 0)      
  END    
  Else  
  Begin  
   SELECT r.*,g.OrganizationCode  FROM rvlfParentMaster r       
    LEFT OUTER JOIN rvlfOrganization g ON r.OrganizationId = g.OrganizationId      
    where (@vcUsername IS NULL OR @vcUsername='' OR UserName = @vcUsername) and      
    (@cOrganizationCode IS NULL OR @cOrganizationCode='' OR  g.OrganizationCode =@cOrganizationCode)      
    AND R.ISDELETE=0 and (R.IsHidden is null or R.IsHidden = 0)      
  End          
        
 SET NOCOUNT OFF      
END      

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUsers_KPI]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetUsers_KPI]
(
  @BigOrganizationId  BIGINT = NULL,
  @UserId INT = NULL,
  @FleetId INT = NULL
)
AS 
/*******************************************************************************/  
-- Name			: rvlf_sp_GetUsers_KPI  132,NULL,275
-- Description	: To get all the User details in fleet based   
-- Author		: Asanraj N  
-- Created Date	: 15-Mar-2019  
--  History		: 

-- exec rvlf_sp_GetUsers_KPI @BigOrganizationId=N'132',@FleetId=N'275'
/*******************************************************************************/ 
BEGIN
  SELECT u.UserId, U.UserName,u.DisplayName FROM rvlfUser U 
    INNER JOIN rvlfFleetUsers FU ON U.UserId = FU.UserId
    INNER JOIN rvlfFleet F ON F.FleetId = FU.FleetId 
  WHERE U.OrganizationId=@BigOrganizationId AND IsDelete =0 AND IsLocked=0 and IsActive=1 AND F.FleetId = @FleetId
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetUsersDevRegIDs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetUsersDevRegIDs] 
@UserId INT = NULL         
AS          
/****************************************************************************************/          
-- Name    : rvlf_sp_GetUsersDevRegIDs          
-- Description   : To get the news details          
-- Author    : ranjith N       
-- Created Date  : 16-Apr-2014       
-- History			: 12-Oct-2016 SS UserId parameter included   
/***************************************************************************************/          
BEGIN          
 SET NOCOUNT ON           
           
     IF @UserId IS NOT NULL
	 BEGIN   
		SELECT UserId,UserName,DevOS,DevRegId FROM dbo.rvlfUser WHERE UserId=@UserId AND DevRegID IS NOT NULL AND DevOS IS NOT NULL and IsPushNotfication=1 
	 END
	 ELSE
	 BEGIN
		SELECT distinct DevRegId,DevOS FROM rvlfUser WHERE DevRegID is not null and IsPushNotfication =  1 
		and DevRegID <> '0' and DevRegID <> '' and DevOS in ('A','I') and Len(DevRegid) >=20 --and userid = 845   --and DevOS = 'A'                 
	 END
					
					 
 --SELECT distinct DevRegId,Devos      
 -- FROM rvlfUser                  
 --WHERE       
 --  DevRegID is not null and IsPushNotfication =  1 and DevRegID <> '0' and DevRegID <> '' and DevOS in ('A') and Len(DevRegid) >=20 --,'I' --and userid = 845   --and DevOS = 'A'                 
         
 SET NOCOUNT OFF          
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehiclebyLandmark]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    
CREATE proc [dbo].[rvlf_sp_GetVehiclebyLandmark]        
 @FleetID BIGINT = null,                          
 @bigQueryingUser bigint = 0,                             
 @Radius bigint = null,                           
 @bigOrganizationID bigint = null,          
 @LandMarkID bigint = null,
 @LatLong varchar(100) = null        
as        
/******************************************************************************/                                      
-- Name  : rvlf_sp_GetVehiclebyLandmark 178,303,32,118,1338  
-- Description : To get the Vehicle based on the landmark                                                             
-- Author  :Gopal.R        20-Jan-2014                              
-- Company  : Angler Technologies                                      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                  
/******************************************************************************/                                      
BEGIN
	IF @LandMarkID IS NOT NULL
	BEGIN        
		SELECT A.LandmarkID,A.LandmarkName,A.BoxId,A.LastValidDateTime,A.Distance,hlat,HLng,Radius ,   
		(select mapitvalues from dbo.rvlf_Fn_GetMapItValues(A.BoxID,@bigQueryingUser,'M')) AS Mapitvalues,        
		(select landmarkvalues from dbo.rvlf_Fn_GetMapItValues(A.BoxID,@bigQueryingUser,'L')) AS LandMarkvalues,        
		(select LandMarkIds from dbo.rvlf_Fn_GetMapItValues(A.BoxID,@bigQueryingUser,'L')) AS LandMarkIds ,    
		(select Notcurposveh from dbo.rvlf_Fn_GetMapItValues(A.BoxID,@bigQueryingUser,'P')) AS Notcurposveh,  
		CASE WHEN A.Distance <= A.Radius THEN 1 ELSE 0 END AS IsMapIt     
		FROM             
		(select distinct(G.LastValidDateTime),L.LandMarkId,L.LandMarkName,G.LastLatitude as HLat,G.LastLongitude as HLng,L.Latitude,L.Longitude,G.BoxId,            
		 ROUND((MIN(DEGREES(ACOS(CAST(
		(SIN(RADIANS(L.Latitude)) * SIN(RADIANS(G.LastLatitude)) + COS(RADIANS(L.Latitude)) *                                        
			  COS(RADIANS(G.LastLatitude)) * COS(RADIANS(L.Longitude - G.LastLongitude))
			 ) AS Decimal(14,10))
			  ))) * 69.09 * 1.609344),3) as Distance1,
              
			  ROUND((MIN(DEGREES(ACOS(                
						  --CAST(                
						  (                
			  SIN(RADIANS(L.Latitude)) *                                            
			  SIN(RADIANS(G.LastLatitude)) +                                            
			  COS(RADIANS(L.Latitude)) *                                            
			  COS(RADIANS(G.LastLatitude)) *                                            
			  COS(RADIANS(L.Longitude - G.LastLongitude))                
						  ) 
						  --AS Decimal(14,10))                
					  ))) * 69.09 * 1.609344),3) as Distance,
		cast(CAST((case when (@Radius is null or @Radius=0) then L.Radius else @Radius end) AS decimal(8,4))/1000 as decimal(10,6)) as Radius                                          
		From rvlfLandMarK L,rvlfBoxId G         
		inner join rvlfVehicleAssignment VA on VA.BoxId=G.BoxId inner join rvlfFleetVehicles FV on VA.VehicleId=FV.VehicleId inner join rvlfFleet F on FV.FleetId=F.FleetId        
		WHERE L.OrganizationId = @bigOrganizationID and L.LandmarkID=@LandMarkID and G.OrganizationId=@bigOrganizationID and F.FleetId=@FleetID        
		group by G.LastValidDateTime,L.LandMarkId,L.LandMarkName,G.LastLatitude,G.LastLongitude,L.Latitude,L.Longitude,G.BoxId  ,case when (@Radius is null or @Radius=0) then L.Radius else @Radius end          
		) A WHERE A.Distance <= Radius            
		order by LastValidDateTime,BoxId, Distance asc   
  
		Declare @landmark varchar(max)                  
		SET @landmark=''                  
		SELECT @landmark += CAST(Latitude AS VARCHAR)+'~#~'+CAST(Longitude AS VARCHAR)+'~#~'+CAST((case when (@Radius is null or @Radius=0) then L.Radius else @Radius end) AS VARCHAR)+'~#~'+CAST(LandmarkName AS VARCHAR)+                  
		'~#~'+CAST(StreetAddress AS VARCHAR(max))+'~&~' FROM rvlfLandmark l where l.LandMarkId=@LandMarkID  
		SELECT @landmark AS LandmarkEntries                                                    
   END
   ELSE
	BEGIN
		DECLARE @Latitude varchar(50), @Longitude varchar(50)
		SELECT	@Latitude = SUBSTRING(@LatLong,0,CHARINDEX(',',@LatLong)),
				@Longitude = SUBSTRING(@LatLong,CHARINDEX(',',@LatLong)+1,LEN(@LatLong))

		--SELECT SUBSTRING('100.00,50.00',0,CHARINDEX(',','100.00,50.00')),
		--SUBSTRING('100.00,50.00',CHARINDEX(',','100.00,50.00')+1,LEN('100.00,50.00'))

		DECLARE @coord TABLE(Latitude varchar(50), Longitude varchar(50))
		INSERT	INTO @coord 
		SELECT	@Latitude, @Longitude

		IF (@Radius is null or @Radius=0) 
		SET @Radius = 50

		SELECT A.BoxId,A.LastValidDateTime,A.Distance,hlat,HLng,Radius ,   
		(select mapitvalues from dbo.rvlf_Fn_GetMapItValues(A.BoxID,@bigQueryingUser,'M')) AS Mapitvalues,        
		(select landmarkvalues from dbo.rvlf_Fn_GetMapItValues(A.BoxID,@bigQueryingUser,'L')) AS LandMarkvalues,        
		(select LandMarkIds from dbo.rvlf_Fn_GetMapItValues(A.BoxID,@bigQueryingUser,'L')) AS LandMarkIds ,    
		(select Notcurposveh from dbo.rvlf_Fn_GetMapItValues(A.BoxID,@bigQueryingUser,'P')) AS Notcurposveh,  
		CASE WHEN A.Distance <= A.Radius THEN 1 ELSE 0 END AS IsMapIt--,
		--A.DriverName,A.DriverMobile
		FROM
			(SELECT	DISTINCT(G.LastValidDateTime),G.LastLatitude as HLat,G.LastLongitude as HLng,C.Latitude,C.Longitude,G.BoxId,            
					ROUND((MIN(DEGREES(ACOS(CAST((SIN(RADIANS(@Latitude)) * SIN(RADIANS(G.LastLatitude)) + COS(RADIANS(@Latitude)) 
					* COS(RADIANS(G.LastLatitude)) * COS(RADIANS(@Longitude - G.LastLongitude))) AS Decimal(14,10))))) * 69.09 * 1.609344),3) as Distance1,
					ROUND((MIN(DEGREES(ACOS((SIN(RADIANS(@Latitude)) * SIN(RADIANS(G.LastLatitude)) + COS(RADIANS(@Latitude)) * COS(RADIANS(G.LastLatitude)) 
					* COS(RADIANS(@Longitude - G.LastLongitude)))))) * 69.09 * 1.609344),3) as Distance,
					CAST(CAST(@Radius AS decimal(8,4))/1000 as decimal(10,6)) as Radius
			From	@coord C, rvlfBoxId G         
			inner	join rvlfVehicleAssignment VA on VA.BoxId=G.BoxId 
			inner	join rvlfFleetVehicles FV on VA.VehicleId=FV.VehicleId 
			inner	join rvlfFleet F on FV.FleetId=F.FleetId        
			WHERE	G.OrganizationId = @bigOrganizationID 
			and		F.FleetId = @FleetID        
			group	by	G.LastValidDateTime,G.LastLatitude,G.LastLongitude,C.Latitude,C.Longitude,G.BoxId
						--@Radius --,DM.DriverName,DM.DisplayName,DM.MobileNo
			) A WHERE A.Distance <= Radius            
		order by LastValidDateTime,BoxId,Distance asc

		SET @landmark=''		
		SELECT @landmark += CAST(@Latitude AS VARCHAR)+'~#~'+CAST(@Longitude AS VARCHAR)+'~#~'+CAST(@Radius AS VARCHAR)
		SELECT @landmark AS LandmarkEntries
	END     
END        
  
   

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleCostAssignment]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
               
create proc [dbo].[rvlf_sp_GetVehicleCostAssignment] --8,6        
(        
@bigFleetId int = null,        
@bigOrganizationID bigint = null,            
@bigUserId bigint = null,         
@CostId tinyint = null,  
@vehicleId bigint =null,  
@costtype tinyint=null  
)        
as      
/*************************************************************************************************************/                
-- Name     : rvlf_sp_GetVehicleCostAssignment                
-- Description : To Get vehicle cost information     
-- Author      : R.Gopal.                
-- Company     : Angler Technologies                
-- History     : <<Date(dd-MON-yyyy)>> Initial Reason                
--      : 11-Sep-2013  Created Intial Version             
/*************************************************************************************************************/   
begin       
    Set nocount on   
  select b.Id,FleetName,VehicleDescription,b.CostName,b.CostDesc,b.CostTypedesc,b.Cost,b.CreatedDate,b.OrganizationId,b.CostType,b.VehicleId,b.FleetId from   
(select  id,CostName,CostDesc,r.CostType,VehicleId,MAX(vc.CreatedDate) as dat from  rvlfROICost R   
inner join rvlfVehicleCost VC on r.Id=VC.CostType group by  id,CostName,CostDesc,r.CostType,VehicleId ) as a   
inner join   
(select r.Id ,f.FleetName,v.VehicleDescription,r.CostName,r.CostDesc,    
CASE WHEN R.CostType=1 THEN 'Operational Cost' WHEN R.CostType=2 THEN 'Ownership Cost' ELSE 'Other Cost' END AS CostTypedesc,R.CostType    
, VC.Cost,VC.CreatedDate,v.OrganizationId,v.VehicleId,f.FleetId   
from rvlfROICost R inner join rvlfVehicleCost VC on r.Id=VC.CostType     
--join rvlfVehicleAssignment VA on VC.VehicleId=VA.VehicleId    
join rvlfFleetVehicles FV on FV.VehicleId=VC.VehicleId    
join rvlfFleet F on FV.FleetId=f.FleetId    
join rvlfVehicle v on VC.VehicleId=v.VehicleId    
where v.OrganizationId=@bigOrganizationID and f.FleetId=@bigFleetId and (IsDelete=0 or IsDelete is null))  as b   
on a.CostDesc=b.CostDesc and a.CostName=b.CostName  and a.dat=b.CreatedDate and a.Id=b.Id   
   where (FleetId=@bigFleetId or @bigFleetId is null or @bigFleetId='') and (b.VehicleId=@vehicleId or @vehicleId is null or @vehicleId='')   
   and (b.Id=@CostId or @CostId is null or @CostId='') and (b.CostType=@costtype or @costtype is null or @costtype='')  
Set nocount off
end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleDetails_API]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicleDetails_API]
@OrgCode VARCHAR(3) = NULL
AS
/************************************************************************************/      
-- Name				: rvlf_sp_GetVehicleDetails_API 'BDN'
-- Description		: To get the vehicles details with speed & temperature values
-- Author			: S Sakthi Gopinath
-- Created Date		: 09-Mar-2016
-- Company			: Trinetra wireless pvt ltd.
-- History			: <<Date(dd-MON-yyyy)>> Initial Reason      
/***********************************************************************************/    
BEGIN
SET NOCOUNT ON

	IF NOT EXISTS (SELECT 1 FROM rvlfOrganization WHERE OrganizationCode=@OrgCode)
	BEGIN
		SELECT 'Invalid Code' AS Response
	END
	ELSE IF NOT EXISTS (SELECT 1 FROM rvlfOrganization WHERE OrganizationCode=@OrgCode AND ExpiresOn > GETUTCDATE())
	BEGIN
		SELECT 'Requested Organization is expired' AS Response
	END
	ELSE 
	BEGIN

			DECLARE @bigOrganizationId INT,@bigFleetId INT
			SELECT @bigOrganizationId = OrganizationId FROM rvlfOrganization WHERE OrganizationCode=@OrgCode
			SELECT TOP 1 @bigFleetId = FleetId FROM rvlfFleet WHERE OrganizationId=@bigOrganizationId
		
			SELECT T.*,REPLACE(REPLACE(REPLACE(T.T1,'0 degree Celsius','NA'),' degree Celsius',''),'Disconnected','NA') AS T1_Value,
			REPLACE(REPLACE(REPLACE(T.T2,'0 degree Celsius','NA'),' degree Celsius',''),'Disconnected','NA') AS T2_Value,
			REPLACE(REPLACE(REPLACE(T.T3,'0 degree Celsius','NA'),' degree Celsius',''),'Disconnected','NA') AS T3_Value,
			REPLACE(REPLACE(REPLACE(T.T4,'0 degree Celsius','NA'),' degree Celsius',''),'Disconnected','NA') AS T4_Value,'°C' AS Units
			FROM (SELECT b.BoxId,v.VehicleId,v.VehicleDescription, b.LastStatusDateTime AS LastStatusDateTime,
			b.LastLatitude,b.LastLongitude,ISNULL(b.LastStreetAddress,'N/A') AS StreetAddress,
			dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID, h.BoxId, h.MessageInID, h.OriginDateTime) as MessageDetails,
			CASE WHEN B.LastValidDateTime = B.LastStatusDateTime THEN 1 ELSE 0 END as IsCurrent,b.LastSpeed,h.CustomProp,
			CASE WHEN CHARINDEX('Temperature Sensor-1 Value',h.CustomProp,0) <> 0 THEN
			SUBSTRING(h.CustomProp,CHARINDEX('Temperature Sensor-1 Value',h.CustomProp,0)+27,
			(CHARINDEX(';',h.CustomProp,CHARINDEX('Temperature Sensor-1 Value',h.CustomProp,0))  - 
			(CHARINDEX('Temperature Sensor-1 Value',h.CustomProp,0)+27))) ELSE 'NA' END AS T1,
			CASE WHEN CHARINDEX('Temperature Sensor-2 Value',h.CustomProp,0) <> 0 THEN
			SUBSTRING(h.CustomProp,CHARINDEX('Temperature Sensor-2 Value',h.CustomProp,0)+27,
			(CHARINDEX(';',h.CustomProp,CHARINDEX('Temperature Sensor-2 Value',h.CustomProp,0))  - 
			(CHARINDEX('Temperature Sensor-2 Value',h.CustomProp,0)+27))) 
			ELSE 'NA' END AS T2,
			CASE WHEN CHARINDEX('Temperature Sensor-3 Value',h.CustomProp,0) <> 0 THEN
			SUBSTRING(h.CustomProp,CHARINDEX('Temperature Sensor-3 Value',h.CustomProp,0)+27,
			(CHARINDEX(';',h.CustomProp,CHARINDEX('Temperature Sensor-3 Value',h.CustomProp,0))  - 
			(CHARINDEX('Temperature Sensor-3 Value',h.CustomProp,0)+27))) ELSE 'NA' END AS T3,
			CASE WHEN CHARINDEX('Temperature Sensor-4 Value',h.CustomProp,0) <> 0 THEN
			SUBSTRING(h.CustomProp,CHARINDEX('Temperature Sensor-4 Value',h.CustomProp,0)+27,
			(CHARINDEX(';',h.CustomProp,CHARINDEX('Temperature Sensor-4 Value',h.CustomProp,0))  - 
			(CHARINDEX('Temperature Sensor-4 Value',h.CustomProp,0)+27))) 
			ELSE 'NA' END AS T4
			FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId
			INNER JOIN rvlfBoxId b ON b.BoxId=va.BoxId
			INNER JOIN rvlfMsgInHst h ON h.MessageInID=b.MessageInId
			INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=v.VehicleId
			INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId
			WHERE v.OrganizationId=@bigOrganizationId AND f.FleetId=@bigFleetId) T
	
	END 

SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleDetails_App]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicleDetails_App]
@bigOrganizationID int,
@IsSave bit = 0,
@VehId int = null,
@VehName varchar(25) = null
AS
/*********************************************************************************************
Procedure Name	: rvlf_sp_GetVehicleDetails_App 6
Description		: Get the vehicle details for mapping to model
Created By		: Sakthi Gopinath S
Created Date	: 15-Mar-2013
*********************************************************************************************/
BEGIN
SET NOCOUNT ON
	IF @IsSave = 1
	BEGIN
		Update dbo.rvlfVehicle SET VehicleDescription=@VehName WHERE VehicleId=@VehId
		SELECT 'Success' AS [Status]
	END
	ELSE
	BEGIN
		SELECT v.VehicleId,va.BoxId,v.VehicleDescription FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va On va.VehicleId=v.VehicleId
		LEFT OUTER JOIN rvlfModelBoxSettings_App MA ON MA.BoxID=va.BoxId
		WHERE v.OrganizationId=@bigOrganizationID AND MA.AssignedDate IS NULL
	END
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicledetails_Monitor]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	    Asan Raj N
-- Create date: 14-Dec-2019
-- Description:	Get Vehicle and compactor details for Mobile Monitor Page.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicledetails_Monitor] 
	@bigVehicleId  bigint = null
AS
BEGIN
	SET NOCOUNT ON;
 SELECT md.BoxId,v.VehicleId,V.VehicleDescription,v.VehicleTypeId,vt.VehicleTypeName, C.CompType,    
  C.CompModel,CASE WHEN C.IsVentilator =1 THEN '1' ELSE '0' END AS IsVentilator,C.VentilatorModel ,C.SeqNo, Md.VFantype AS NoofFan
  FROM  rvlfMAKDevices Md 
   inner join rvlfVehicleAssignment VA ON VA.BoxId = Md.BoxId
   Inner join rvlfVehicle V ON V.VehicleId = VA.VehicleId
   inner join rvlfVehicleType vt on vt.VehicleTypeId = V.VehicleTypeId 
   Left outer join rvlf_CompactorDetails c on c.DeviceId = Md.BoxId
   WHERE V.VehicleId = @bigVehicleId  and Md.IsDelete= 0 
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleDetails_Rpt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicleDetails_Rpt]
@bigFleetID bigint = NULL,
@intBoxID varchar(max) = NULL,
@dtStartDate DateTime = null,
@dtEndDate DateTime = null,
@bigOrganizationID bigint = NULL,
@bigQueryingUser bigint = NULL
/******************************************************************************/                
-- Procedure	: rvlf_sp_GetVehicleDetails_Rpt 464,NULL,NULL,NULL,183,303
-- Description	: To get the Vechicle details                
-- Author		: S Sakthi Gopinath
-- Company		: Trinetra Wireless (P) Ltd.
-- History		: <<Date(dd-MON-yyyy)>> Initial Reason                
--				: 11-Jan-2015 SS Created Intial Version               
/******************************************************************************/                
AS                
BEGIN                
SET NOCOUNT ON
              
	DECLARE @HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@DefaultDateFormat INT = 0
	SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,
	@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
	inner join rvlfUser u on u.UserId = up.UserId
	inner join rvlfOrganization o on o.OrganizationId = u.OrganizationId
	WHERE up.UserId = @bigQueryingUser

	SELECT ROW_NUMBER() OVER(ORDER BY b.BoxId ASC) AS Sno,
	b.BoxId,v.VehicleId,v.VehicleDescription,v.LicensePlate,vt.VehicleTypeName,
	ISNULL(m.MakeName,'NA')+' / '+ISNULL(md.ModelName,'NA')+' / '+ (CASE WHEN ISNULL(v.ModelYear,0) = 0 THEN 'NA' ELSE CAST(v.ModelYear AS VARCHAR(6)) END) AS MakeModel,
	(CASE WHEN ISNULL(v.CapacityValue,0) = 0 THEN '-' ELSE CAST(v.CapacityValue AS VARCHAR(5)) END) + 
	(CASE WHEN ISNULL(v.CapacityValue,0) = 0 THEN '' ELSE 
	' - ' + CHOOSE(ISNULL(v.CapacityUnit,0),'No of seats','Kilos / Tons') END) AS Capacity,
	--' - '+ ISNULL(v.CapacityUnit,'nos') END)AS Capacity,
	ISNULL(CAST(v.TankCapacity AS VARCHAR),'-') + (CASE WHEN ISNULL(v.TankCapacity,'0') = '0' THEN '' ELSE ' - '+ 
	ISNULL(CHOOSE(ISNULL(v.CapacityUnits,0),'lts','gal'),'lts') END) AS TankCapacity,
	(CASE WHEN ISNULL(v.VehicleOwnership,0)= 0 THEN '-' WHEN v.VehicleOwnership = 1 THEN 'Own' ELSE 'Lease' END) AS VehicleOwnership,
	(CASE WHEN v.PurchasedDate IS NULL THEN '-' ELSE Convert(varchar,v.PurchasedDate,@DefaultDateFormat) END) AS PurchasedOn,
	Convert(varchar,GETUTCDATE(),@DefaultDateFormat) AS WarrantyExpiredOn,
	Convert(varchar,GETUTCDATE(),@DefaultDateFormat) AS LeaseExpiredOn,
	(CASE WHEN v.LastInsuranceExpired IS NULL THEN '-' ELSE Convert(varchar,v.LastInsuranceExpired,@DefaultDateFormat) END) AS InsuranceExpiredOn,
	(CASE WHEN v.PurchasedDate IS NULL THEN 'NA' ELSE CAST(DATEDIFF(hour,v.PurchasedDate,GETDATE()) /8766 AS VARCHAR(3)) END) AS Age,
	ISNULL(h.Odometer,0) AS Odometer,CAST((100.0 - CAST(((50000.00 - CAST(ISNULL(h.Odometer,0) AS DECIMAL(15,2)))/50000.00) AS DECIMAL(15,2))) AS VARCHAR(16)) AS LifeSpan,
	(CASE WHEN v.LastInsuranceExpired IS NULL THEN 0 WHEN DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),GETUTCDATE())) > v.LastInsuranceExpired THEN 1 ELSE 0 END) AS IsInsuranceExpired,
	(CASE WHEN v.WarrantyExpiryDate IS NULL THEN 0 WHEN DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),GETUTCDATE())) > v.WarrantyExpiryDate THEN 1 ELSE 0 END) AS IsWarrantyExpired,
	(CASE WHEN v.LeaseExpiryDate IS NULL THEN 0 WHEN DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),GETUTCDATE())) > v.LeaseExpiryDate THEN 1 ELSE 0 END) AS IsLeaseExpired,
	--(CASE WHEN v.LastInsuranceExpired IS NULL THEN 0 WHEN DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),GETUTCDATE())) > v.LastInsuranceExpired THEN 1 ELSE 0 END) AS IsInsuranceExpired,
	--(CASE WHEN v.LastInsuranceExpired IS NULL THEN 0 WHEN DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),GETUTCDATE())) > v.LastInsuranceExpired THEN 1 ELSE 0 END) AS IsWarrantyExpired,
	--(CASE WHEN v.LastInsuranceExpired IS NULL THEN 0 WHEN DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),GETUTCDATE())) > v.LastInsuranceExpired THEN 1 ELSE 0 END) AS IsLeaseExpired,
	(CASE WHEN v.VehicleOwnership IS NULL THEN 0 WHEN v.VehicleOwnership = 0 THEN 0 WHEN v.VehicleOwnership = 1 THEN 1 END) AS VehicleOwn,
	(CASE WHEN v.VehicleOwnership IS NULL THEN 0 WHEN v.VehicleOwnership = 0 THEN 0 WHEN v.VehicleOwnership = 2 THEN 1 END) AS VehicleLease,
	(CASE WHEN (100.0 - CAST(((50000.00 - CAST(ISNULL(h.Odometer,0) AS DECIMAL(15,2)))/50000.00) AS DECIMAL(15,2))) >= 100.00 THEN 1 ELSE 0 END) AS VehicleLifeSpan,
	o.OrganizationDisplayName AS OrgDisplayName,
	--Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,
	--Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,        
	PasGenerateddate = Convert(varchar,DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),GETUTCDATE())),@DefaultDateFormat)+ ' ' 
	+ Convert(varchar,cast(DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),GETUTCDATE())) as Time),22)
	--dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE())        
	FROM rvlfBoxId b INNER JOIN rvlfVehicleAssignment va ON va.BoxId = b.BoxId
	INNER JOIN rvlfMsgInHst h ON h.MessageInId=b.MessageInID
	INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId
	INNER JOIN rvlfVehicleType vt ON vt.VehicleTypeId=v.VehicleTypeId
	INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=v.VehicleId
	INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId
	INNER JOIN rvlfOrganization o ON o.OrganizationId=f.OrganizationId
	LEFT OUTER JOIN rvlfMake m ON v.MakeId = m.MakeId
	LEFT OUTER JOIN rvlfModel md ON v.ModelId = md.ModelId
	WHERE 
	(@bigFleetID IS NULL OR @bigFleetID = '' OR f.FleetId IN (@bigFleetID)) AND
	(@intBoxID IS NULL OR @intBoxID = '' OR @intBoxID='0' OR b.BoxId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND
	b.OrganizationId = @bigOrganizationID

SET NOCOUNT OFF
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleExpiredDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

                     
CREATE Procedure [dbo].[rvlf_sp_GetVehicleExpiredDetails]              
AS                    
/******************************************************************************/                    
-- Name  : [rvlf_sp_GetVehicleExpiredDetails]                    
-- Description : To get the vehicle expired details based on the current date                    
-- Author  : V.Narayanasamy                    
-- Company  : Angler Technologies                    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                    
--    : 27-July-2010 VN Created initial version                    
--    : 27-July-2010 VN Created initial version                    
--    : 14-Oct-2011  Sakthi - SMS Expiry based on boxid                    
/******************************************************************************/                    
BEGIN                    
 --UPDATE THE ADDRESS FILED NULLL FOR INVALID ADDRESS                    
 UPDATE rvlfMsgInHst SET StreetAddress = NULL, IsProcessed = 1 WHERE LATITUDE<>0 AND Longitude<>0 AND VALIDGPS=0 AND (StreetAddress = 'Address Not Found!' OR StreetAddress IS NULL OR StreetAddress ='N/A')                     
                     
 --UPDATE THE EMAIL AND SMS SENTING                     
 IF EXISTS(SELECT VehicleId FROM rvlfVehicle WHERE (CAST(DATEDIFF(d,LastInsuranceExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastInsuranceExpired, DATEADD(YEAR,1,LastInsuranceExpired))as int)*1.00)>=1.00                    
    OR (CAST(DATEDIFF(d,LastPermitExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastPermitExpired, DATEADD(YEAR,1,LastPermitExpired))as int)*1.00)>=1.00                    
    OR (CAST(DATEDIFF(d,LastFCDate,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastFCDate, DATEADD(YEAR,5,LastFCDate))as int)*1.00)>=1.00)                    
   BEGIN                    
    UPDATE rvlfVehicle SET ISEMAILSENT=0,ISSMSSENT=0 WHERE VehicleId IN(SELECT VehicleId FROM rvlfVehicle WHERE (CAST(DATEDIFF(d,LastInsuranceExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastInsuranceExpired, DATEADD(YEAR,1,LastInsuranceExpired))as int)*1.00)>=1.00                    
    OR (CAST(DATEDIFF(d,LastPermitExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastPermitExpired, DATEADD(YEAR,1,LastPermitExpired))as int)*1.00)>=1.00                    
    OR (CAST(DATEDIFF(d,LastFCDate,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastFCDate, DATEADD(YEAR,5,LastFCDate))as int)*1.00)>=1.00)                    
   END                    
 DECLARE @vcVehExpiredList varchar(max)=null                    
 DECLARE @TBLEXPIREDLIST TABLE                    
 (                    
  VehId bigint,                    
  VehicleName varchar(50),                    
  DisplayName varchar(20),                    
  RenewalDate varchar(30),                    
  ExpiredDate varchar(30),                    
  Remainingdays varchar(20),                      
  EmailList varchar(200),                    
  OrgId bigint,                    
  ExpType tinyint,                    
  MobileNo varchar(20),                    
  Expiry numeric(5,2)                     
 )                    
 INSERT INTO @TBLEXPIREDLIST (VehId,VehicleName,DisplayName,RenewalDate,ExpiredDate,Remainingdays,EmailList,OrgId,ExpType,MobileNo,Expiry)                    
 SELECT VehicleId,VehicleDescription,V.VehicleDescription ,convert(varchar, LastInsuranceExpired,106),                    
    convert(varchar, DATEADD(YEAR,1,LastInsuranceExpired),106),                        
    CASE WHEN DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,1,LastInsuranceExpired))>0                     
     THEN CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,1,LastInsuranceExpired))) as varchar(5)) +' day(s)'                     
     ELSE CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,1,LastInsuranceExpired))) as varchar(5))+' day(s) overdue' END,           
    U.Email,V.OrganizationId,1,U.MobileNo,                    
    CAST((CAST(DATEDIFF(d,LastInsuranceExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastInsuranceExpired, DATEADD(YEAR,1,LastInsuranceExpired))as int)*1.00)AS NUMERIC(7,2))                       
   FROM rvlfVehicle V                    
    INNER JOIN rvlfUser U ON U.OrganizationId=V.OrganizationId                     
    WHERE (CAST(DATEDIFF(d,LastInsuranceExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastInsuranceExpired, DATEADD(YEAR,1,LastInsuranceExpired))as int)*1.00)>=0.75                        
    AND U.UserName='Administrator'                    
    AND V.LastInsuranceExpired IS NOT NULL                  
    AND (V.ISEMAILSENT=0 OR V.ISSMSSENT=0) and v.OrganizationID=86                   
 INSERT INTO @TBLEXPIREDLIST (VehId,VehicleName,DisplayName,RenewalDate,ExpiredDate,Remainingdays,EmailList,OrgId,ExpType,MobileNo,Expiry)                    
 SELECT VehicleId,VehicleDescription,V.VehicleDescription ,convert(varchar, LastPermitExpired,106),                    
    convert(varchar, DATEADD(YEAR,1,LastPermitExpired),106),                    
    CASE WHEN DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,1,LastPermitExpired))>0                     
     THEN CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,1,LastPermitExpired))) as varchar(5)) +' day(s)'                      
     ELSE CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,1,LastPermitExpired))) as varchar(5)) +' day(s) overdue' END,                    
    U.Email,V.OrganizationId,2,U.MobileNo,                    
    CAST((CAST(DATEDIFF(d,LastPermitExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastPermitExpired, DATEADD(YEAR,1,LastPermitExpired))as int)*1.00)AS NUMERIC(7,2))                       
   FROM rvlfVehicle V                    
    INNER JOIN rvlfUser U ON U.OrganizationId=V.OrganizationId                     
    WHERE (CAST(DATEDIFF(d,LastPermitExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastPermitExpired, DATEADD(YEAR,1,LastPermitExpired))as int)*1.00)>=0.75                        
    AND U.UserName='Administrator'                     
    AND V.LastPermitExpired IS NOT NULL                    
    AND (V.ISEMAILSENT=0 OR V.ISSMSSENT=0) and v.OrganizationID=86                     
                        
 INSERT INTO @TBLEXPIREDLIST (VehId,VehicleName,DisplayName,RenewalDate,ExpiredDate,Remainingdays,EmailList,OrgId,ExpType,MobileNo,Expiry)                      
 SELECT VehicleId,VehicleDescription,V.VehicleDescription ,convert(varchar, LastFCDate,106),                    
    convert(varchar, DATEADD(YEAR,5,LastFCDate),106),                    
    CASE WHEN DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,5,LastFCDate))>0                     
     THEN CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,5,LastFCDate))) as varchar(5)) +' day(s)'                      
     ELSE CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,5,LastFCDate))) as varchar(5)) +' day(s) overdue' END,                    
    U.Email,V.OrganizationId,3 ,U.MobileNo,                    
    CAST((CAST(DATEDIFF(d,LastFCDate,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastFCDate, DATEADD(YEAR,5,LastFCDate))as int)*1.00)AS NUMERIC(7,2))                    
   FROM rvlfVehicle V                    
    INNER JOIN rvlfUser U ON U.OrganizationId=V.OrganizationId                     
    WHERE (CAST(DATEDIFF(d,LastFCDate,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastFCDate, DATEADD(YEAR,5,LastFCDate))as int)*1.00)>=0.75                     
    AND U.UserName='Administrator'                    
    AND V.LastFCDate IS NOT NULL                    
    AND (V.ISEMAILSENT=0 OR V.ISSMSSENT=0) and v.OrganizationID=86                     
                       
 DECLARE @TBLEMAIL TABLE                    
 (                    
  VehExpiryList varchar(max),                    
  Exptype tinyint,                    
  Vehid VARCHAR(MAX),                    
  VehNotificationList varchar(max)                    
 )                    
 DECLARE @COUNT INT=0                    
 DECLARE @inc INT=1                    
                    
                     
 SELECT @COUNT=count(b.a) FROM(SELECT COUNT(*)as a FROM @TBLEXPIREDLIST GROUP BY OrgId,ExpType)as b                    
                    
WHILE (@inc<=@COUNT)                    
 BEGIN                    
  DECLARE @vcVehlist varchar(max)=NULL          
  DECLARE @OrgId BIGINT=NULL                    
  DECLARE @Exptype tinyint=NULL                    
  DECLARE @EMAIL VARCHAR(MAX)=NULL                    
  DECLARE @VEHID VARCHAR(MAX)=NULL                      
  SELECT @OrgId=OrgId,@Exptype=ExpType FROM @TBLEXPIREDLIST where Expiry is not null GROUP BY OrgId,ExpType ORDER BY OrgId,ExpType                     
  SELECT @vcVehlist = ISNULL(@vcVehlist+'','')+ ('<tr><td><font face="arial" size="2px">'+VehicleName                         
      +'</font></td><td><font face="arial" size="2px">'+ DisplayName +'</font></td><td><font face="arial" size="2px">'+                    
      CAST(RenewalDate AS VARCHAR) +'</font></td><td><font face="arial" size="2px">'+                    
      CAST(ExpiredDate AS VARCHAR) +'</font></td><td><font face="arial" size="2px">'+                    
      CAST(Remainingdays AS VARCHAR)                     
      +' </font></td></tr>'),                    
     @VEHID =COALESCE(@VEHID,'')+CONVERT(VARCHAR,VehId)+',',                    
     @EMAIL=EmailList,@Exptype=ExpType                      
      from @TBLEXPIREDLIST where OrgId=@OrgId and ExpType=@Exptype                     
                              
  SET @VEHID = SUBSTRING(@VEHID,0,LEN(@VEHID))                    
                          
  UPDATE @TBLEXPIREDLIST SET Expiry =null WHERE OrgId=@OrgId AND ExpType=@Exptype                     
  INSERT INTO @TBLEMAIL(VehExpiryList,Exptype,Vehid,VehNotificationList)                    
   VALUES(@vcVehlist,@Exptype,@VEHID,@EMAIL)                         
  SET @inc=@inc+1                    
 END                    
                     
 --INSERT INTO @TBLEMAIL(VehExpiryList,Exptype,Vehid,VehNotificationList)     -- SELECT ('<tr><td><font face="arial" size="2px">'+DisplayName                          
 --     +'</font></td><td><font face="arial" size="2px">'+ DriverName  +'</font></td><td><font face="arial" size="2px">'+                          
 --     CAST(LicenseExpiresOn AS VARCHAR(12)) +'</font></td><td><font face="arial" size="2px">'+                    
 --     CAST((CASE WHEN DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(WEEK,-1,LicenseExpiresOn))>0                     
 --      THEN CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),LicenseExpiresOn)) as varchar(5)) +' day(s)'                     
 --      ELSE CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),LicenseExpiresOn)) as varchar(5))+' day(s) overdue' END) AS VARCHAR)                     
 --     +' </font></td></tr>'),4,NULL,@EMAIL  FROM rvlfDriverMaster                       
 --  WHERE DATEADD(WEEK,-1,LicenseExpiresOn)<=CONVERT(date,getdate())                    
                    
DECLARE @TBLDRIVEREXPIREDLIST TABLE                        
 (                      
  vcDriverName varchar(max),                    
  vcDisplayName varchar(max),                    
  VOrgId bigint,                    
  VLicenseExpiresOn datetime                    
 )                       
 DECLARE @TBLDriverExpirySummary TABLE                        
 (                        
  TOrgId BIGINT,                    
  Rno int                       
 )                      
                     
  --select @vcOrg = OrganizationName from rvlfOrganization where OrganizationId = @OrgId                    
   
 DECLARE @DrCOUNT INT=0                        
 DECLARE @Drinc INT=1                        
                     
                        
 INSERT INTO @TBLDRIVEREXPIREDLIST (vcDriverName,vcDisplayName , VOrgId,VLicenseExpiresOn)                          
   SELECT DriverName,DisplayName,OrganizationID,LicenseExpiresOn FROM rvlfDriverMaster                     
   WHERE DATEADD(WEEK,-1,LicenseExpiresOn)<=CONVERT(date,getdate())                    
                         
 SELECT @DrCOUNT=count(b.a) FROM(SELECT COUNT(*)as a FROM @TBLDRIVEREXPIREDLIST GROUP BY vOrgId)as b                        
 --SELECT @DrCOUNT=count(*) FROM rvlfDriverMaster WHERE DATEADD(WEEK,-1,LicenseExpiresOn)<=CONVERT(date,getdate())                    
 insert into @TBLDriverExpirySummary(TOrgId,Rno) SELECT VOrgId, ROW_NUMBER() OVER (ORDER BY VOrgId)  FROM @TBLDRIVEREXPIREDLIST  GROUP BY VOrgId ORDER BY VOrgId                         
  WHILE (@Drinc<=@DrCOUNT)                        
    BEGIN                             
       DECLARE @VDriverlist varchar(max)=NULL                    
       --SELECT @vcOrg=VOrgId  FROM @TBLDRIVEREXPIREDLIST  GROUP BY VOrgId ORDER BY VOrgId                    
                    
      SELECT @VDriverlist = ISNULL(@VDriverlist+'','')+ ('<tr><td><font face="arial" size="2px">'+ vcDriverName                              
   +'</font></td><td><font face="arial" size="2px">'+ vcDisplayName  +'</font></td><td><font face="arial" size="2px">'+                              
  CAST(VLicenseExpiresOn AS VARCHAR(12)) +'</font></td><td><font face="arial" size="2px">'+                        
  CAST((CASE WHEN DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(WEEK,-1,VLicenseExpiresOn))>0                         
  THEN CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),VLicenseExpiresOn)) as varchar(5)) +' day(s)'                         
  ELSE CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),VLicenseExpiresOn)) as varchar(5))+' day(s) overdue' END) AS VARCHAR)                         
  +' </font></td></tr>') FROM @TBLDRIVEREXPIREDLIST                           
  WHERE VOrgId = (select TOrgId from @TBLDriverExpirySummary where Rno = @Drinc)                    
                    
  INSERT INTO @TBLEMAIL(VehExpiryList,Exptype,Vehid,VehNotificationList) values(@VDriverlist,4,NULL,@EMAIL)                        
                      
 SET @Drinc=@Drinc+1                        
 END                         
                     
INSERT INTO @TBLEXPIREDLIST(DisplayName,ExpiredDate,Remainingdays,Exptype,OrgId)                    
  SELECT DisplayName,CAST(LicenseExpiresOn AS VARCHAR(12)),                   
      CAST((CASE WHEN DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(WEEK,-1,LicenseExpiresOn))>0                     
       THEN CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),LicenseExpiresOn)) as varchar(5)) +' day(s)'                     
       ELSE CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),LicenseExpiresOn)) as varchar(5))+' day(s) overdue' END) AS VARCHAR)                     
      ,4,OrganizationID FROM rvlfDriverMaster                       
   WHERE DATEADD(WEEK,-1,LicenseExpiresOn)<=CONVERT(date,getdate())                    
                     
 --GET THE EMIAL NOTIFICATION LIST                    
 SELECT (CASE WHEN EXPTYPE=1 THEN '<font face="arial" size="2px"><p><strong>Dear Admin,</strong></p></font><font face="arial" size="2px"><p>'                    
     +'Below are the Insurance expiry details of Vehicle(s):</p><table style="width: 574px; height: 70px;" border=1><tr><td>'                    
     +'<strong><font face="arial" size="2px">Vehicle Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Display Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Last Renewal Date</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Expires On</font></strong></td><td>'             
 +'<strong><font face="arial" size="2px">Due</font></strong></td></tr>'+                      
     (                    
      VehExpiryList                     
     )                    
     +'</table><p>This is for your information</p><p><b>Best Regards, </b></p></font><p>'                    
     +'<a border="0" href="http://www.trinetrawireless.com/">'                    
     +'<img border="0" src="http://www.trinetrawireless.com/images/logo.png" style="width: 100px; height: 36px;" />'                    
     +'</a></p><hr /><p><font face="arial" size="1px">This is a system generated email - do not reply</font></p>'                    
    WHEN EXPTYPE=2 THEN '<font face="arial" size="2px"><p><strong>Dear Admin,</strong></p></font><font face="arial" size="2px"><p>'                    
     +'Below are the Permit expiry details of Vehicle(s):</p><table style="width: 574px; height: 70px;" border=1><tr><td>'                    
     +'<strong><font face="arial" size="2px">Vehicle Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Display Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Last Renewal Date</font></strong></td><td>'             
     +'<strong><font face="arial" size="2px">Expires On</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Due</font></strong></td></tr>'+                      
     (                    
      VehExpiryList                     
     )                    
     +'</table><p>This is for your information</p><p><b>Best Regards, </b></p></font><p>'                    
     +'<a border="0" href="http://www.trinetrawireless.com/">'                   
     +'<img border="0" src="http://www.trinetrawireless.com/images/logo.png" style="width: 100px; height: 36px;" />'                    
     +'</a></p><hr /><p><font face="arial" size="1px">This is a system generated email - do not reply</font></p>'                    
    WHEN EXPTYPE=3 THEN '<font face="arial" size="2px"><p><strong>Dear Admin,</strong></p></font><font face="arial" size="2px"><p>'                    
     +'Below are the FC expiry details of Vehicle(s):</p><table style="width: 574px; height: 70px;" border=1><tr><td>'                    
     +'<strong><font face="arial" size="2px">Vehicle Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Display Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Last Renewal Date</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Expires On</font></strong></td><td>'               
     +'<strong><font face="arial" size="2px">Due</font></strong></td></tr>'+                      
     (                    
      VehExpiryList                     
     )                    
     +'</table><p>This is for your information</p><p><b>Best Regards, </b></p></font><p>'                    
     +'<a border="0" href="http://www.trinetrawireless.com/">'                    
     +'<img border="0" src="http://www.trinetrawireless.com/images/logo.png" style="width: 100px; height: 36px;" />'                    
     +'</a></p><hr /><p><font face="arial" size="1px">This is a system generated email - do not reply</font></p>'                    
    WHEN EXPTYPE=4 THEN '<font face="arial" size="2px"><p><strong>Dear Admin,</strong></p></font><font face="arial" size="2px"><p>'                    
     +'Below are the License expiry details of Driver(s):</p><table style="width: 574px; height: 70px;" border=1><tr><td>'                    
     +'<strong><font face="arial" size="2px">Driver Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Display Name</font></strong></td><td>'                         
     +'<strong><font face="arial" size="2px">Expires On</font></strong></td><td>'            
     +'<strong><font face="arial" size="2px">Due</font></strong></td></tr>'+                      
     (                    
      VehExpiryList                     
     )                    
     +'</table><p>This is for your information</p><p><b>Best Regards, </b></p></font><p>'                    
     +'<a border="0" href="http://www.trinetrawireless.com/">'                    
     +'<img border="0" src="http://www.trinetrawireless.com/images/logo.png" style="width: 100px; height: 36px;" />'                    
     +'</a></p><hr /><p><font face="arial" size="1px">This is a system generated email - do not reply</font></p>'                    
     --END)AS VehExpiryList,'narayanasamy@angleritech.com,sathish@angleritech.com,shreeprakaash@angleritech.com'as VehNotificationList,VehId,Exptype                      
     END)AS VehExpiryList, 'internal@trinetrawireless.com' as VehNotificationList,VehId,Exptype                      
    FROM @TBLEMAIL WHERE Exptype IS NULL                    
                      
 --GET THE SMS NOTIFICATION LIST                    
 SELECT top 1 (CASE WHEN EXPTYPE=1 THEN ('Vehicle : '+DisplayName+ '\nInsurance Expiry Date : '+ExpiredDate + '\nDue : '+Remainingdays)                    
     WHEN ExpType=2 THEN ('Vehicle : '+DisplayName+ '\nPermit Expiry Date : '+ExpiredDate + '\nDue : '+Remainingdays)                    
     WHEN ExpType=3 THEN ('Vehicle : '+DisplayName+ '\nFC Expiry Date : '+ExpiredDate + '\nDue : '+Remainingdays)                        
     WHEN ExpType=4 THEN ('Driver : '+DisplayName+ '\nLicense Expiry Date : '+ExpiredDate + '\nDue : '+Remainingdays)                             
    END)as MessageTemplate ,null as MobileNo,VehId,DisplayName,OrgId ,dbo.rvlf_fn_getsmssettings(OrgId) as SMSsettings            
                        
  FROM @TBLEXPIREDLIST  --where (getdate() <'08-Nov-2015 11:59 PM' or GETDATE()>'09-nov-2015 4:00 AM') 
            
                      
  --GET THE SMS EXPIRY DETAILS BASED ON THE BOXID AND ORGANIZATION                    
                      
  DECLARE @vcDeviceStatus VARCHAR(MAX) = NULL                    
                 
  SELECT @vcDeviceStatus = ISNULL(@vcDeviceStatus+'','') +('<tr><td>' +O.OrganizationDisplayName + '</td>' +                     
  '<td>' +CAST(BoxId AS VARCHAR) + '</td>' + '<td>' +VehicleDescription+ '</td>' + '<td>' +                     
  CASE WHEN COUNT(MessageInID)>(O.MaxSMSLimit-1) THEN CAST(COUNT(MessageInID) AS VARCHAR)+ ' - Stoped' ELSE CAST(COUNT(MessageInID) AS VARCHAR) END+ '</td>' +                    
  '<td>' +CASE WHEN SUBSTRING(NS.MOBILENO,0,3)=91 THEN 'Domestic' ELSE 'International' END) + '</td></tr>'                     
   FROM rvlfNotificationLog NS                     
    INNER JOIN rvlfOrganization O ON O.OrganizationId =NS.OrganizationID                         
  WHERE (IsSMSSent  = 1 )   and o.OrganizationID=86                  
   AND SMSProcessedDate IS NOT NULL AND DATEPART(MONTH, OriginDateTime) = DATEPART(MONTH, GETUTCDATE())                      
   AND  DATEPART(YEAR,OriginDateTime) = DATEPART(YEAR, GETUTCDATE())                     
   --AND CONVERT(DATE,SMSProcessedDate) BETWEEN '2011-06-23' AND '2011-07-22'                    
   AND NS.MobileNo IS NOT NULL AND NS.MobileNo !='' --and (getdate() <'08-Nov-2015 11:59 PM' or GETDATE()>'09-nov-2015 4:00 AM')                    
  GROUP BY BOXID,O.OrganizationDisplayName,VehicleDescription,SUBSTRING(NS.MOBILENO,0,3),O.MaxSMSLimit,O.SMSReminder                    
  HAVING  COUNT(MessageInID)>=O.SMSReminder                    
  ORDER BY OrganizationDisplayName ,BoxId                     
                    
 SELECT '<div><p><font face="arial" size="2px"><b>Dear All,</b><br /><br /><p>Below are the SMS Details for the month of'+SUBSTRING(CONVERT(VARCHAR,GETUTCDATE(),106),3,15) + ' close to 300:</p>'                    
      + '<table border="1" cellpadding="0" cellspacing="0" style="font-family: Arial; font-size: 12px; width: 700px; height: 70px;">'           
      + '<tr><td><strong><font face="arial" size="2px">Organization Name</font></strong></td><td>'                    
      + '<strong><font face="arial" size="2px">Box ID</font></strong></td><td>'                    
      + '<strong><font face="arial" size="2px">Vehicle Name</font></strong></td><td>'                    
      + '<strong><font face="arial" size="2px">No.ofSMS Sent</font></strong></td><td>'                    
      + '<strong><font face="arial" size="2px">SMS Type</font></strong></td></tr>'                    
      + @vcDeviceStatus + '</table><p><font face="arial" size="2px"><b>Best Regards, </b></font></p>'                    
      + '<p><a border="0" href="http://www.trinetrawireless.com/"><img border="0" src="http://www.trinetrawireless.com/images/logo.png" style="width: 100px; height: 36px;" /></a></p>'                    
      + '<hr /><font face="arial" size="1px">This is system generated mail</font></div>' AS VehicleSMSStatus,                    
   'internal@trinetrawireless.com' as VehNotificationList,'TRINETRA | Organization SMS Notification' as SMSsub                    
                               
--select Sno,VehicleID,GeozoneID,OrganizationId,MessageTemplate,ContactNo as MobileNo from rvlfRFIDSchoolSMSNotification where IsSMSSent = 0  

--SMS notification                          
select Sno,Sno as VehId ,VehicleID,a.GeozoneID,a.OrganizationId as OrgId,'Msg:Your Children\nName : AbulAzad\n Info: Started from School at : Oct  7 2014  6:22AM -Trinetra' as MessageTemplate1,                        
MessageTemplate AS MessageTemplate,--as  VehicleSMSStatus,                        
'gopalakrishnan@angleritech.com' as VehNotificationList,'TRINETRA | RFID SMS Notification'  as SMSsub,                        
a.ContactNo as MobileNo,dbo.rvlf_fn_getsmssettings(a.OrganizationId) as SMSsettings ,'' as DisplayName           
 from rvlfRFIDSchoolSMSNotification a inner join rvlfStudentMaster b on a.StudentID=b.StudentMasterID        
where (IsSMSSent = 0 or IsSMSSent is null) and a.ContactNo is not null and a.ContactNo !='' and MessageTemplate is not null 
--and (getdate() <'08-Nov-2015 11:59 PM' or GETDATE()>'09-nov-2015 4:00 AM')

 --and NotificationType in (1,3)        
and a.MsgType <> 7

UNION ALL  --For sending Headcount notification to Reporting Person -- Included by Anbarasu.E 09-sep-2015    
    
 SELECT	Sno, Sno as VehId, VehicleID, a.GeozoneID, a.OrganizationId as OrgId,    
		'Msg:Your Children\nName : AbulAzad\n Info: Started from School at : Oct  7 2014  6:22AM -Trinetra' as MessageTemplate1, MessageTemplate as MessageTemplate,    
		u.Email as VehNotificationList, 'TRINETRA | RFID SMS Notification' as SMSsub, a.ContactNo as MobileNo,
		dbo.rvlf_fn_getsmssettings(a.OrganizationId) as SMSsettings,'' as DisplayName         
 FROM	rvlfRFIDSchoolSMSNotification  a inner join rvlfUser u on a.StudentID=u.UserId    
 WHERE	(IsSMSSent = 0 or IsSMSSent is null) and (a.ContactNo is not null and a.ContactNo !='') and a.MsgType = 7
 --and (getdate() <'08-Nov-2015 11:59 PM' or GETDATE()>'09-nov-2015 4:00 AM')
          

--Email notification         
select Sno,Sno as VehId ,VehicleID,a.GeozoneID,a.OrganizationId as OrgId,'Msg:Your Children\nName : AbulAzad\n Info: Started from School at : Oct  7 2014  6:22AM -Trinetra' as MessageTemplate1,MessageTemplate ,--as  VehicleSMSStatus,                   
--b.EmailAddress as VehNotificationList,    
'gopalakrishnan@angleritech.com' as VehNotificationList,      
'TRINETRA | RFID SMS Notification'  as SMSsub,a.ContactNo as MobileNo          
 from rvlfRFIDSchoolSMSNotification  a inner join rvlfStudentMaster b on a.StudentID=b.StudentMasterID           
 where (IsSMSSent = 0 or IsSMSSent is null) and EmailAddress is not null  and EmailAddress !='' --and b.NotificationType in (2,3)      
 and a.MsgType <> 7 and Sno=0 -- this is to skip email notificaiton
 

UNION ALL  --For sending Headcount notification to Reporting Person -- Included by Anbarasu.E 09-sep-2015    
    
 SELECT Sno, Sno as VehId, VehicleID, a.GeozoneID, a.OrganizationId as OrgId,    
		'Msg:Your Children\nName : AbulAzad\n Info: Started from School at : Oct  7 2014  6:22AM -Trinetra' as MessageTemplate1, MessageTemplate,    
		u.Email as VehNotificationList, 'TRINETRA | RFID SMS Notification' as SMSsub, a.ContactNo as MobileNo      
 FROM	rvlfRFIDSchoolSMSNotification  a inner join rvlfUser u on a.StudentID=u.UserId    
 WHERE	(IsSMSSent = 0 or IsSMSSent is null) and (Email is not null  and Email !='') 
 and a.MsgType = 7 and	Sno=0 -- this is to skip email notificaiton
 
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleExpiredDetails_bkp]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

                     
CREATE Procedure [dbo].[rvlf_sp_GetVehicleExpiredDetails_bkp]              
AS                    
/******************************************************************************/                    
-- Name  : [rvlf_sp_GetVehicleExpiredDetails]                    
-- Description : To get the vehicle expired details based on the current date                    
-- Author  : V.Narayanasamy                    
-- Company  : Angler Technologies                    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                    
--    : 27-July-2010 VN Created initial version                    
--    : 27-July-2010 VN Created initial version                    
--    : 14-Oct-2011  Sakthi - SMS Expiry based on boxid                    
/******************************************************************************/                    
BEGIN                    
 --UPDATE THE ADDRESS FILED NULLL FOR INVALID ADDRESS                    
 UPDATE rvlfMsgInHst SET StreetAddress = NULL, IsProcessed = 1 WHERE LATITUDE<>0 AND Longitude<>0 AND VALIDGPS=0 AND (StreetAddress = 'Address Not Found!' OR StreetAddress IS NULL OR StreetAddress ='N/A')                     
                     
 --UPDATE THE EMAIL AND SMS SENTING                     
 IF EXISTS(SELECT VehicleId FROM rvlfVehicle WHERE (CAST(DATEDIFF(d,LastInsuranceExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastInsuranceExpired, DATEADD(YEAR,1,LastInsuranceExpired))as int)*1.00)>=1.00                    
    OR (CAST(DATEDIFF(d,LastPermitExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastPermitExpired, DATEADD(YEAR,1,LastPermitExpired))as int)*1.00)>=1.00                    
    OR (CAST(DATEDIFF(d,LastFCDate,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastFCDate, DATEADD(YEAR,5,LastFCDate))as int)*1.00)>=1.00)                    
   BEGIN                    
    UPDATE rvlfVehicle SET ISEMAILSENT=0,ISSMSSENT=0 WHERE VehicleId IN(SELECT VehicleId FROM rvlfVehicle WHERE (CAST(DATEDIFF(d,LastInsuranceExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastInsuranceExpired, DATEADD(YEAR,1,LastInsuranceExpired))as int)*1.00)>=1.00                    
    OR (CAST(DATEDIFF(d,LastPermitExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastPermitExpired, DATEADD(YEAR,1,LastPermitExpired))as int)*1.00)>=1.00                    
    OR (CAST(DATEDIFF(d,LastFCDate,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastFCDate, DATEADD(YEAR,5,LastFCDate))as int)*1.00)>=1.00)                    
   END                    
 DECLARE @vcVehExpiredList varchar(max)=null                    
 DECLARE @TBLEXPIREDLIST TABLE                    
 (                    
  VehId bigint,                    
  VehicleName varchar(50),                    
  DisplayName varchar(20),                    
  RenewalDate varchar(30),                    
  ExpiredDate varchar(30),                    
  Remainingdays varchar(20),                      
  EmailList varchar(200),                    
  OrgId bigint,                    
  ExpType tinyint,                    
  MobileNo varchar(20),                    
  Expiry numeric(5,2)                     
 )                    
 INSERT INTO @TBLEXPIREDLIST (VehId,VehicleName,DisplayName,RenewalDate,ExpiredDate,Remainingdays,EmailList,OrgId,ExpType,MobileNo,Expiry)                    
 SELECT VehicleId,VehicleDescription,V.VehicleDescription ,convert(varchar, LastInsuranceExpired,106),                    
    convert(varchar, DATEADD(YEAR,1,LastInsuranceExpired),106),                        
    CASE WHEN DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,1,LastInsuranceExpired))>0                     
     THEN CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,1,LastInsuranceExpired))) as varchar(5)) +' day(s)'                     
     ELSE CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,1,LastInsuranceExpired))) as varchar(5))+' day(s) overdue' END,           
    U.Email,V.OrganizationId,1,U.MobileNo,                    
    CAST((CAST(DATEDIFF(d,LastInsuranceExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastInsuranceExpired, DATEADD(YEAR,1,LastInsuranceExpired))as int)*1.00)AS NUMERIC(7,2))                       
   FROM rvlfVehicle V                    
    INNER JOIN rvlfUser U ON U.OrganizationId=V.OrganizationId                     
    WHERE (CAST(DATEDIFF(d,LastInsuranceExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastInsuranceExpired, DATEADD(YEAR,1,LastInsuranceExpired))as int)*1.00)>=0.75                        
    AND U.UserName='Administrator'                    
    AND V.LastInsuranceExpired IS NOT NULL                  
    AND (V.ISEMAILSENT=0 OR V.ISSMSSENT=0)                    
 INSERT INTO @TBLEXPIREDLIST (VehId,VehicleName,DisplayName,RenewalDate,ExpiredDate,Remainingdays,EmailList,OrgId,ExpType,MobileNo,Expiry)                    
 SELECT VehicleId,VehicleDescription,V.VehicleDescription ,convert(varchar, LastPermitExpired,106),                    
    convert(varchar, DATEADD(YEAR,1,LastPermitExpired),106),                    
    CASE WHEN DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,1,LastPermitExpired))>0                     
     THEN CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,1,LastPermitExpired))) as varchar(5)) +' day(s)'                      
     ELSE CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,1,LastPermitExpired))) as varchar(5)) +' day(s) overdue' END,                    
    U.Email,V.OrganizationId,2,U.MobileNo,                    
    CAST((CAST(DATEDIFF(d,LastPermitExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastPermitExpired, DATEADD(YEAR,1,LastPermitExpired))as int)*1.00)AS NUMERIC(7,2))                       
   FROM rvlfVehicle V                    
    INNER JOIN rvlfUser U ON U.OrganizationId=V.OrganizationId                     
    WHERE (CAST(DATEDIFF(d,LastPermitExpired,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastPermitExpired, DATEADD(YEAR,1,LastPermitExpired))as int)*1.00)>=0.75                        
    AND U.UserName='Administrator'                     
    AND V.LastPermitExpired IS NOT NULL                    
    AND (V.ISEMAILSENT=0 OR V.ISSMSSENT=0)                      
                        
 INSERT INTO @TBLEXPIREDLIST (VehId,VehicleName,DisplayName,RenewalDate,ExpiredDate,Remainingdays,EmailList,OrgId,ExpType,MobileNo,Expiry)                      
 SELECT VehicleId,VehicleDescription,V.VehicleDescription ,convert(varchar, LastFCDate,106),                    
    convert(varchar, DATEADD(YEAR,5,LastFCDate),106),                    
    CASE WHEN DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,5,LastFCDate))>0                     
     THEN CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,5,LastFCDate))) as varchar(5)) +' day(s)'                      
     ELSE CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(YEAR,5,LastFCDate))) as varchar(5)) +' day(s) overdue' END,                    
    U.Email,V.OrganizationId,3 ,U.MobileNo,                    
    CAST((CAST(DATEDIFF(d,LastFCDate,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastFCDate, DATEADD(YEAR,5,LastFCDate))as int)*1.00)AS NUMERIC(7,2))                    
   FROM rvlfVehicle V                    
    INNER JOIN rvlfUser U ON U.OrganizationId=V.OrganizationId                     
    WHERE (CAST(DATEDIFF(d,LastFCDate,GETDATE())as int)*1.00)/                    
    (CAST(DATEDIFF(d,LastFCDate, DATEADD(YEAR,5,LastFCDate))as int)*1.00)>=0.75                     
    AND U.UserName='Administrator'                    
    AND V.LastFCDate IS NOT NULL                    
    AND (V.ISEMAILSENT=0 OR V.ISSMSSENT=0)                      
                       
 DECLARE @TBLEMAIL TABLE                    
 (                    
  VehExpiryList varchar(max),                    
  Exptype tinyint,                    
  Vehid VARCHAR(MAX),                    
  VehNotificationList varchar(max)                    
 )                    
 DECLARE @COUNT INT=0                    
 DECLARE @inc INT=1                    
                    
                     
 SELECT @COUNT=count(b.a) FROM(SELECT COUNT(*)as a FROM @TBLEXPIREDLIST GROUP BY OrgId,ExpType)as b                    
                    
WHILE (@inc<=@COUNT)                    
 BEGIN                    
  DECLARE @vcVehlist varchar(max)=NULL          
  DECLARE @OrgId BIGINT=NULL                    
  DECLARE @Exptype tinyint=NULL                    
  DECLARE @EMAIL VARCHAR(MAX)=NULL                    
  DECLARE @VEHID VARCHAR(MAX)=NULL                      
  SELECT @OrgId=OrgId,@Exptype=ExpType FROM @TBLEXPIREDLIST where Expiry is not null GROUP BY OrgId,ExpType ORDER BY OrgId,ExpType                     
  SELECT @vcVehlist = ISNULL(@vcVehlist+'','')+ ('<tr><td><font face="arial" size="2px">'+VehicleName                         
      +'</font></td><td><font face="arial" size="2px">'+ DisplayName +'</font></td><td><font face="arial" size="2px">'+                    
      CAST(RenewalDate AS VARCHAR) +'</font></td><td><font face="arial" size="2px">'+                    
      CAST(ExpiredDate AS VARCHAR) +'</font></td><td><font face="arial" size="2px">'+                    
      CAST(Remainingdays AS VARCHAR)                     
      +' </font></td></tr>'),                    
     @VEHID =COALESCE(@VEHID,'')+CONVERT(VARCHAR,VehId)+',',                    
     @EMAIL=EmailList,@Exptype=ExpType                      
      from @TBLEXPIREDLIST where OrgId=@OrgId and ExpType=@Exptype                     
                              
  SET @VEHID = SUBSTRING(@VEHID,0,LEN(@VEHID))                    
                          
  UPDATE @TBLEXPIREDLIST SET Expiry =null WHERE OrgId=@OrgId AND ExpType=@Exptype                     
  INSERT INTO @TBLEMAIL(VehExpiryList,Exptype,Vehid,VehNotificationList)                    
   VALUES(@vcVehlist,@Exptype,@VEHID,@EMAIL)                         
  SET @inc=@inc+1                    
 END                    
                     
 --INSERT INTO @TBLEMAIL(VehExpiryList,Exptype,Vehid,VehNotificationList)     -- SELECT ('<tr><td><font face="arial" size="2px">'+DisplayName                          
 --     +'</font></td><td><font face="arial" size="2px">'+ DriverName  +'</font></td><td><font face="arial" size="2px">'+                          
 --     CAST(LicenseExpiresOn AS VARCHAR(12)) +'</font></td><td><font face="arial" size="2px">'+                    
 --     CAST((CASE WHEN DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(WEEK,-1,LicenseExpiresOn))>0                     
 --      THEN CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),LicenseExpiresOn)) as varchar(5)) +' day(s)'                     
 --      ELSE CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),LicenseExpiresOn)) as varchar(5))+' day(s) overdue' END) AS VARCHAR)                     
 --     +' </font></td></tr>'),4,NULL,@EMAIL  FROM rvlfDriverMaster                       
 --  WHERE DATEADD(WEEK,-1,LicenseExpiresOn)<=CONVERT(date,getdate())                    
                    
DECLARE @TBLDRIVEREXPIREDLIST TABLE                        
 (                      
  vcDriverName varchar(max),                    
  vcDisplayName varchar(max),                    
  VOrgId bigint,                    
  VLicenseExpiresOn datetime                    
 )                       
 DECLARE @TBLDriverExpirySummary TABLE                        
 (                        
  TOrgId BIGINT,                    
  Rno int                       
 )                      
                     
  --select @vcOrg = OrganizationName from rvlfOrganization where OrganizationId = @OrgId                    
   
 DECLARE @DrCOUNT INT=0                        
 DECLARE @Drinc INT=1                        
                     
                        
 INSERT INTO @TBLDRIVEREXPIREDLIST (vcDriverName,vcDisplayName , VOrgId,VLicenseExpiresOn)                          
   SELECT DriverName,DisplayName,OrganizationID,LicenseExpiresOn FROM rvlfDriverMaster                     
   WHERE DATEADD(WEEK,-1,LicenseExpiresOn)<=CONVERT(date,getdate())                    
                         
 SELECT @DrCOUNT=count(b.a) FROM(SELECT COUNT(*)as a FROM @TBLDRIVEREXPIREDLIST GROUP BY vOrgId)as b                        
 --SELECT @DrCOUNT=count(*) FROM rvlfDriverMaster WHERE DATEADD(WEEK,-1,LicenseExpiresOn)<=CONVERT(date,getdate())                    
 insert into @TBLDriverExpirySummary(TOrgId,Rno) SELECT VOrgId, ROW_NUMBER() OVER (ORDER BY VOrgId)  FROM @TBLDRIVEREXPIREDLIST  GROUP BY VOrgId ORDER BY VOrgId                         
  WHILE (@Drinc<=@DrCOUNT)                        
    BEGIN                             
       DECLARE @VDriverlist varchar(max)=NULL                    
       --SELECT @vcOrg=VOrgId  FROM @TBLDRIVEREXPIREDLIST  GROUP BY VOrgId ORDER BY VOrgId                    
                    
      SELECT @VDriverlist = ISNULL(@VDriverlist+'','')+ ('<tr><td><font face="arial" size="2px">'+ vcDriverName                              
   +'</font></td><td><font face="arial" size="2px">'+ vcDisplayName  +'</font></td><td><font face="arial" size="2px">'+                              
  CAST(VLicenseExpiresOn AS VARCHAR(12)) +'</font></td><td><font face="arial" size="2px">'+                        
  CAST((CASE WHEN DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(WEEK,-1,VLicenseExpiresOn))>0                         
  THEN CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),VLicenseExpiresOn)) as varchar(5)) +' day(s)'                         
  ELSE CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),VLicenseExpiresOn)) as varchar(5))+' day(s) overdue' END) AS VARCHAR)                         
  +' </font></td></tr>') FROM @TBLDRIVEREXPIREDLIST                           
  WHERE VOrgId = (select TOrgId from @TBLDriverExpirySummary where Rno = @Drinc)                    
                    
  INSERT INTO @TBLEMAIL(VehExpiryList,Exptype,Vehid,VehNotificationList) values(@VDriverlist,4,NULL,@EMAIL)                        
                      
 SET @Drinc=@Drinc+1                        
 END                         
                     
INSERT INTO @TBLEXPIREDLIST(DisplayName,ExpiredDate,Remainingdays,Exptype,OrgId)                    
  SELECT DisplayName,CAST(LicenseExpiresOn AS VARCHAR(12)),                   
      CAST((CASE WHEN DATEDIFF(DAY,SYSUTCDATETIME(),DATEADD(WEEK,-1,LicenseExpiresOn))>0                     
       THEN CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),LicenseExpiresOn)) as varchar(5)) +' day(s)'                     
       ELSE CAST(ABS(DATEDIFF(DAY,SYSUTCDATETIME(),LicenseExpiresOn)) as varchar(5))+' day(s) overdue' END) AS VARCHAR)                     
      ,4,OrganizationID FROM rvlfDriverMaster                       
   WHERE DATEADD(WEEK,-1,LicenseExpiresOn)<=CONVERT(date,getdate())                    
                     
 --GET THE EMIAL NOTIFICATION LIST                    
 SELECT (CASE WHEN EXPTYPE=1 THEN '<font face="arial" size="2px"><p><strong>Dear Admin,</strong></p></font><font face="arial" size="2px"><p>'                    
     +'Below are the Insurance expiry details of Vehicle(s):</p><table style="width: 574px; height: 70px;" border=1><tr><td>'                    
     +'<strong><font face="arial" size="2px">Vehicle Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Display Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Last Renewal Date</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Expires On</font></strong></td><td>'             
 +'<strong><font face="arial" size="2px">Due</font></strong></td></tr>'+                      
     (                    
      VehExpiryList                     
     )                    
     +'</table><p>This is for your information</p><p><b>Best Regards, </b></p></font><p>'                    
     +'<a border="0" href="http://www.trinetrawireless.com/">'                    
     +'<img border="0" src="http://www.trinetrawireless.com/images/logo.png" style="width: 100px; height: 36px;" />'                    
     +'</a></p><hr /><p><font face="arial" size="1px">This is a system generated email - do not reply</font></p>'                    
    WHEN EXPTYPE=2 THEN '<font face="arial" size="2px"><p><strong>Dear Admin,</strong></p></font><font face="arial" size="2px"><p>'                    
     +'Below are the Permit expiry details of Vehicle(s):</p><table style="width: 574px; height: 70px;" border=1><tr><td>'                    
     +'<strong><font face="arial" size="2px">Vehicle Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Display Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Last Renewal Date</font></strong></td><td>'             
     +'<strong><font face="arial" size="2px">Expires On</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Due</font></strong></td></tr>'+                      
     (                    
      VehExpiryList                     
     )                    
     +'</table><p>This is for your information</p><p><b>Best Regards, </b></p></font><p>'                    
     +'<a border="0" href="http://www.trinetrawireless.com/">'                   
     +'<img border="0" src="http://www.trinetrawireless.com/images/logo.png" style="width: 100px; height: 36px;" />'                    
     +'</a></p><hr /><p><font face="arial" size="1px">This is a system generated email - do not reply</font></p>'                    
    WHEN EXPTYPE=3 THEN '<font face="arial" size="2px"><p><strong>Dear Admin,</strong></p></font><font face="arial" size="2px"><p>'                    
     +'Below are the FC expiry details of Vehicle(s):</p><table style="width: 574px; height: 70px;" border=1><tr><td>'                    
     +'<strong><font face="arial" size="2px">Vehicle Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Display Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Last Renewal Date</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Expires On</font></strong></td><td>'               
     +'<strong><font face="arial" size="2px">Due</font></strong></td></tr>'+                      
     (                    
      VehExpiryList                     
     )                    
     +'</table><p>This is for your information</p><p><b>Best Regards, </b></p></font><p>'                    
     +'<a border="0" href="http://www.trinetrawireless.com/">'                    
     +'<img border="0" src="http://www.trinetrawireless.com/images/logo.png" style="width: 100px; height: 36px;" />'                    
     +'</a></p><hr /><p><font face="arial" size="1px">This is a system generated email - do not reply</font></p>'                    
    WHEN EXPTYPE=4 THEN '<font face="arial" size="2px"><p><strong>Dear Admin,</strong></p></font><font face="arial" size="2px"><p>'                    
     +'Below are the License expiry details of Driver(s):</p><table style="width: 574px; height: 70px;" border=1><tr><td>'                    
     +'<strong><font face="arial" size="2px">Driver Name</font></strong></td><td>'                    
     +'<strong><font face="arial" size="2px">Display Name</font></strong></td><td>'                         
     +'<strong><font face="arial" size="2px">Expires On</font></strong></td><td>'          
     +'<strong><font face="arial" size="2px">Due</font></strong></td></tr>'+                      
     (                    
      VehExpiryList                     
     )                    
     +'</table><p>This is for your information</p><p><b>Best Regards, </b></p></font><p>'                    
     +'<a border="0" href="http://www.trinetrawireless.com/">'                    
     +'<img border="0" src="http://www.trinetrawireless.com/images/logo.png" style="width: 100px; height: 36px;" />'                    
     +'</a></p><hr /><p><font face="arial" size="1px">This is a system generated email - do not reply</font></p>'                    
     --END)AS VehExpiryList,'narayanasamy@angleritech.com,sathish@angleritech.com,shreeprakaash@angleritech.com'as VehNotificationList,VehId,Exptype                      
     END)AS VehExpiryList, 'internal@trinetrawireless.com' as VehNotificationList,VehId,Exptype                      
    FROM @TBLEMAIL WHERE Exptype IS NULL                    
                      
 --GET THE SMS NOTIFICATION LIST                    
 SELECT top 1 (CASE WHEN EXPTYPE=1 THEN ('Vehicle : '+DisplayName+ '\nInsurance Expiry Date : '+ExpiredDate + '\nDue : '+Remainingdays)                    
     WHEN ExpType=2 THEN ('Vehicle : '+DisplayName+ '\nPermit Expiry Date : '+ExpiredDate + '\nDue : '+Remainingdays)                    
     WHEN ExpType=3 THEN ('Vehicle : '+DisplayName+ '\nFC Expiry Date : '+ExpiredDate + '\nDue : '+Remainingdays)                        
     WHEN ExpType=4 THEN ('Driver : '+DisplayName+ '\nLicense Expiry Date : '+ExpiredDate + '\nDue : '+Remainingdays)                             
    END)as MessageTemplate ,null as MobileNo,VehId,DisplayName,OrgId ,dbo.rvlf_fn_getsmssettings(OrgId) as SMSsettings            
                        
  FROM @TBLEXPIREDLIST  --where (getdate() <'08-Nov-2015 11:59 PM' or GETDATE()>'09-nov-2015 4:00 AM') 
            
                      
  --GET THE SMS EXPIRY DETAILS BASED ON THE BOXID AND ORGANIZATION                    
                      
  DECLARE @vcDeviceStatus VARCHAR(MAX) = NULL                    
                 
  SELECT @vcDeviceStatus = ISNULL(@vcDeviceStatus+'','') +('<tr><td>' +O.OrganizationDisplayName + '</td>' +                     
  '<td>' +CAST(BoxId AS VARCHAR) + '</td>' + '<td>' +VehicleDescription+ '</td>' + '<td>' +                     
  CASE WHEN COUNT(MessageInID)>(O.MaxSMSLimit-1) THEN CAST(COUNT(MessageInID) AS VARCHAR)+ ' - Stoped' ELSE CAST(COUNT(MessageInID) AS VARCHAR) END+ '</td>' +                    
  '<td>' +CASE WHEN SUBSTRING(NS.MOBILENO,0,3)=91 THEN 'Domestic' ELSE 'International' END) + '</td></tr>'                     
   FROM rvlfNotificationLog NS                     
    INNER JOIN rvlfOrganization O ON O.OrganizationId =NS.OrganizationID                         
  WHERE (IsSMSSent  = 1 )                     
   AND SMSProcessedDate IS NOT NULL AND DATEPART(MONTH, OriginDateTime) = DATEPART(MONTH, GETUTCDATE())                      
   AND  DATEPART(YEAR,OriginDateTime) = DATEPART(YEAR, GETUTCDATE())                     
   --AND CONVERT(DATE,SMSProcessedDate) BETWEEN '2011-06-23' AND '2011-07-22'                    
   AND NS.MobileNo IS NOT NULL AND NS.MobileNo !='' --and (getdate() <'08-Nov-2015 11:59 PM' or GETDATE()>'09-nov-2015 4:00 AM')                    
  GROUP BY BOXID,O.OrganizationDisplayName,VehicleDescription,SUBSTRING(NS.MOBILENO,0,3),O.MaxSMSLimit,O.SMSReminder                    
  HAVING  COUNT(MessageInID)>=O.SMSReminder                    
  ORDER BY OrganizationDisplayName ,BoxId                     
                    
 SELECT '<div><p><font face="arial" size="2px"><b>Dear All,</b><br /><br /><p>Below are the SMS Details for the month of'+SUBSTRING(CONVERT(VARCHAR,GETUTCDATE(),106),3,15) + ' close to 300:</p>'                    
      + '<table border="1" cellpadding="0" cellspacing="0" style="font-family: Arial; font-size: 12px; width: 700px; height: 70px;">'           
      + '<tr><td><strong><font face="arial" size="2px">Organization Name</font></strong></td><td>'                    
      + '<strong><font face="arial" size="2px">Box ID</font></strong></td><td>'                    
      + '<strong><font face="arial" size="2px">Vehicle Name</font></strong></td><td>'                    
      + '<strong><font face="arial" size="2px">No.ofSMS Sent</font></strong></td><td>'                    
      + '<strong><font face="arial" size="2px">SMS Type</font></strong></td></tr>'                    
      + @vcDeviceStatus + '</table><p><font face="arial" size="2px"><b>Best Regards, </b></font></p>'                    
      + '<p><a border="0" href="http://www.trinetrawireless.com/"><img border="0" src="http://www.trinetrawireless.com/images/logo.png" style="width: 100px; height: 36px;" /></a></p>'                    
      + '<hr /><font face="arial" size="1px">This is system generated mail</font></div>' AS VehicleSMSStatus,                    
   'internal@trinetrawireless.com' as VehNotificationList,'TRINETRA | Organization SMS Notification' as SMSsub                    
                               
--select Sno,VehicleID,GeozoneID,OrganizationId,MessageTemplate,ContactNo as MobileNo from rvlfRFIDSchoolSMSNotification where IsSMSSent = 0  

--SMS notification                          
select Sno,Sno as VehId ,VehicleID,a.GeozoneID,a.OrganizationId as OrgId,'Msg:Your Children\nName : AbulAzad\n Info: Started from School at : Oct  7 2014  6:22AM -Trinetra' as MessageTemplate1,                        
MessageTemplate AS MessageTemplate,--as  VehicleSMSStatus,                        
'gopalakrishnan@angleritech.com' as VehNotificationList,'TRINETRA | RFID SMS Notification'  as SMSsub,                        
a.ContactNo as MobileNo,dbo.rvlf_fn_getsmssettings(a.OrganizationId) as SMSsettings ,'' as DisplayName           
 from rvlfRFIDSchoolSMSNotification a inner join rvlfStudentMaster b on a.StudentID=b.StudentMasterID        
where (IsSMSSent = 0 or IsSMSSent is null) and a.ContactNo is not null and a.ContactNo !='' and MessageTemplate is not null 
--and (getdate() <'08-Nov-2015 11:59 PM' or GETDATE()>'09-nov-2015 4:00 AM')

 --and NotificationType in (1,3)        
and a.MsgType <> 7

UNION ALL  --For sending Headcount notification to Reporting Person -- Included by Anbarasu.E 09-sep-2015    
    
 SELECT	Sno, Sno as VehId, VehicleID, a.GeozoneID, a.OrganizationId as OrgId,    
		'Msg:Your Children\nName : AbulAzad\n Info: Started from School at : Oct  7 2014  6:22AM -Trinetra' as MessageTemplate1, MessageTemplate as MessageTemplate,    
		u.Email as VehNotificationList, 'TRINETRA | RFID SMS Notification' as SMSsub, a.ContactNo as MobileNo,
		dbo.rvlf_fn_getsmssettings(a.OrganizationId) as SMSsettings,'' as DisplayName         
 FROM	rvlfRFIDSchoolSMSNotification  a inner join rvlfUser u on a.StudentID=u.UserId    
 WHERE	(IsSMSSent = 0 or IsSMSSent is null) and (a.ContactNo is not null and a.ContactNo !='') and a.MsgType = 7
 --and (getdate() <'08-Nov-2015 11:59 PM' or GETDATE()>'09-nov-2015 4:00 AM')
          

--Email notification         
select Sno,Sno as VehId ,VehicleID,a.GeozoneID,a.OrganizationId as OrgId,'Msg:Your Children\nName : AbulAzad\n Info: Started from School at : Oct  7 2014  6:22AM -Trinetra' as MessageTemplate1,MessageTemplate ,--as  VehicleSMSStatus,                   
--b.EmailAddress as VehNotificationList,    
'gopalakrishnan@angleritech.com' as VehNotificationList,      
'TRINETRA | RFID SMS Notification'  as SMSsub,a.ContactNo as MobileNo          
 from rvlfRFIDSchoolSMSNotification  a inner join rvlfStudentMaster b on a.StudentID=b.StudentMasterID           
 where (IsSMSSent = 0 or IsSMSSent is null) and EmailAddress is not null  and EmailAddress !='' --and b.NotificationType in (2,3)      
 and a.MsgType <> 7 and Sno=0 -- this is to skip email notificaiton


UNION ALL  --For sending Headcount notification to Reporting Person -- Included by Anbarasu.E 09-sep-2015    
    
 SELECT Sno, Sno as VehId, VehicleID, a.GeozoneID, a.OrganizationId as OrgId,    
		'Msg:Your Children\nName : AbulAzad\n Info: Started from School at : Oct  7 2014  6:22AM -Trinetra' as MessageTemplate1, MessageTemplate,    
		u.Email as VehNotificationList, 'TRINETRA | RFID SMS Notification' as SMSsub, a.ContactNo as MobileNo      
 FROM	rvlfRFIDSchoolSMSNotification  a inner join rvlfUser u on a.StudentID=u.UserId    
 WHERE	(IsSMSSent = 0 or IsSMSSent is null) and (Email is not null  and Email !='') 
 and a.MsgType = 7 and	Sno=0 -- this is to skip email notificaiton
 
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleHistory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- RVLT_SP_GetLatLng2 90,'12/01/2010 08:00:00','12/08/2010 16:00:00',2000,'desc',17

CREATE procedure [dbo].[rvlf_sp_GetVehicleHistory] 
(
	@BoxID varchar(50),
	@startdate as datetime,
	@enddate datetime,    
    @orderby varchar(10),
    @bigQueryingUser bigint = 0
)
as
/******************************************************************************/
--	Name		:	[rvlf_sp_GetVehicleHistory] 50,'12/01/2010 08:00:00','12/08/2010 16:00:00','desc',17
--	Description	:	To get the messages that needs to be shown in the grid
--	Author		:	T. Sathish Kumar
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	11-Dec-2009 MJJC	Included message & Command restrictions
--				:	29-Dec-2009 MJJC	Restricted the response display of the commands sent by Angler Admin
--				:	11-Jan-2010 MJJC	To get the message details from the function
--				:	25-Jan-2010 MJJC	To update the alarm details function parameters
--				:	28-Jan-2010 MJJC	To have a field for status for exporting.
--				:	29-Jan-2010 MJJC	To return the message details for Send geozone IDs from its description
--				:	06-Feb-2010	MJJC	Checked whether the communication details is null or not.
--				:	26-Apr-2010 MJJC	Done the related change for shoing speed with violation
--				:	16-Jun-2010	MJJC	Included the function for the map it.
--				:	26-July-2010 VN		To display the speed with duration msg without speed.
--				:   30-July-2010 LK	    Changed the current location indication logic
--				:   08-Oct-2010 TSK	    Fine tuned the Proc to optimize
--				:   08-Dec-2010 LK	    Made Vehicle fuel fill message visible for only AnglerAdmin
/******************************************************************************/                       
Begin

	------- Included by Kumuthini on 16-July-09 ---------------------

	DECLARE @HoursToBeAdded INT = 0
	DECLARE @MinsToBeAdded INT = 0
	DECLARE @Distance varchar(20)
	DECLARE @vcOrganizatiionID  bigint 
	
	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,
		   @vcOrganizatiionID = u.OrganizationId
    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
    
    --print @HoursToBeAdded
    --print @MinsToBeAdded
    
	--DECLARE @userIds table (userId bigint)
	
	--IF @vcOrganizatiionID > 1 
	--	INSERT INTO @userIds SELECT UserID FROM rvlfUser WHERE OrganizationId = @vcOrganizatiionID 
    
    -------------------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))
	----------------------------------------------------------------------------------------------------------

	DECLARE @intTotalRecords int
	SELECT @intTotalRecords = COUNT(H.MessageInID) 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  
		LEFT OUTER join rvlfTripDetails t ON h.MessageInID = t.StartMessageInID
		LEFT OUTER JOIN rvlfTripDetails d ON h.MessageInID = d.EndMessageInID
    where VA.BoxId = @BoxID and OriginDateTime between 
    CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109)
    and 
		CT.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s 
			WHERE s.ModuleId = 26 and s.UserGroupId IN 
			(SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))
    and H.ValidGps=0 
    IF @intTotalRecords < 2000
		BEGIN
		   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(3))+@Distance  ,'-')+'~#~'+						
						Convert(varchar,[TimeStamp],101)+' '+ SubString(Convert(varchar,[TimeStamp],9),12,9) + SUBSTRING(Convert(varchar,[TimeStamp],9), 25, 2) + '~#~' +						
						CAST(Heading as varchar(3))+'~#~'+ISNULL(cast(a.Distance as varchar(5)),'')+'~#~'+ cast(isNull(IgnitionStatus,0) as CHAR(1))+'~#~'+Landmark						
						+'~#~'+MessageDetails+'~#~'+CAST(MessageInID AS varchar(40))+'~&~'', this.checked, this.id);'
						as mapitFunction
					   from (
			select distinct(H.MessageInID), VA.BoxID as DeviceID, ValidGPS, H.Latitude as Latitude, H.Longitude as Longitude,
			H.NearestLandMark as Distance, 
			/***************** Changed the Speed as numeric data type by Jaya Chitra on 25-Aug-2009******************/
			Case WHEN H.BoxMsgInTypeId =51 THEN NULL ELSE CAST(Speed  * @ConversionFactor as int) END  as Speed, 
			CASE WHEN H.Speed = 0 OR H.ValidGps > 0 THEN -1 ELSE CAST(Heading as varchar(3))  END as Heading, 
			DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [Timestamp], 
			DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,DateTimeReceived)) as DateTimeReceived,
			v.VehicleDescription, BoxMsgInTypeName as Message, H.BoxMsgInTypeId as BoxMsgInTypeId ,
					Case WHEN H.BoxMsgInTypeId = 28 THEN CT.BoxMsgInTypeDesc 
					     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 = 51 THEN 
						 'Speed Violated for ' +
				--To disply the speed with duration without speed
						--CAST(CAST(Speed  * @ConversionFactor as int) AS varchar(3))+' ' +
						 --@Distance +
						 '(' +dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'
					ELSE
					dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime )--CT.BoxMsgInTypeDesc 
					END 
					as MessageDetails,
						0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,
						 case WHEN (H.LandMarkID IS NULL or H.LandMarkID = 0) THEN ISNULL(H.StreetAddress,'
						 Address is not resolved') ELSE 
						 ISNULL(L.LandmarkName, ISNULL(H.StreetAddress,'Address is not resolved'))
						 END as Address,@Distance as Units,
						CASE 
						WHEN H.ValidGps > 0 OR H.BoxMsgInTypeId IN (9, 14,15,16,17,24) OR Speed = 0 then '-'
						WHEN H.Heading between 335 and 360 THEN 'N'
						 WHEN H.Heading between 0 and 25 THEN 'N'
						WHEN H.Heading between 25 and 65 THEN 'NE'
						WHEN H.Heading between 65 and 115 THEN 'E'
						WHEN H.Heading between 115 and 155 THEN 'SE'
						WHEN H.Heading between 155 and 210 THEN 'S'
						WHEN H.Heading between 210 and 245 THEN 'SW'
						WHEN H.Heading between 245 and 300 THEN 'W'
						WHEN H.Heading between 300 and 335 THEN 'NW' END as Direction ,						
					
						+'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,
						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 = 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,
								ISNULL(CASE WHEN (L.LandMarkID IS NULL OR H.LandMarkID = 0) THEN '-' ELSE L.LandmarkName END,'-')
								AS Landmark,L.LandmarkName as LandmarkName, L.Latitude as LandmarkLatitude, 
								L.Longitude as LandmarkLongitude, L.Radius as LandmarkRadius,
								 L.StreetAddress As LandMarkAddress,L.LandmarkID
			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.BoxId = @BoxID and OriginDateTime between
			CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109)
			and 
			--H.BoxMsgInTypeId <>19 and--blocked the ipupdates for Gitex
			(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
			UNION ALL
			/***************** Changed the Speed as NULL by Jaya Chitra on 25-Aug-2009******************/
				select  NULL as MessageInID,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,NULL as Speed, 0 as Heading,
				DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [Timestamp],
				DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as SentDateTime, 
				V.VehicleDescription,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId ,
				CASE WHEN OH.BoxCmdOutTypeId = 39 OR OH.BoxCmdOutTypeId = 4 THEN dbo.rvlf_fn_GetCmdMsgDetails(OH.CustomProp + ',', OH.BoxCmdOutTypeId, VA.BoxID) 
				     ELSE BoxcmdTypeDesc END as MessageDetails
				,OH.UserId,Priority,
				/**************** Changed the Acknowledgement to be return based on the value ************/
				CASE WHEN Acknowledged = 1 THEN 'True' 
						WHEN Acknowledged = 0 THEN 'False' 
						WHEN  Acknowledged = 2 THEN 'Success'
						WHEN  Acknowledged = 3 THEN 'Update Failed'
						WHEN  Acknowledged = 4 THEN 'CRC Incorrect'
						WHEN  Acknowledged = 5 THEN 'No Communication'
						WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'
						ELSE 'Nothing' END AS Acknowledged,
				CASE WHEN Acknowledged = 1 THEN 'Acknowledged' 
						WHEN Acknowledged = 0 THEN 'Not Acknowledged' 
						WHEN  Acknowledged = 2 THEN 'Success'
						WHEN  Acknowledged = 3 THEN 'Upgrade Failed'
						WHEN  Acknowledged = 4 THEN 'CRC Incorrect'
						WHEN  Acknowledged = 5 THEN 'No Communication'
						WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'
						ELSE '' END AS AckStatus,
				'N/A' as Address,@Distance as Units,'' as Direction ,/*null as mapitFunction,*/'setValue('' '')' as jsFunction,
				NULL as IgnitionStatus, NULL as StreetAddress, NULL as Landmark,NULL as LandmarkName, 
				NULL as LandmarkLatitude, NULL as LandmarkLongitude, NULL as LandmarkRadius,
				NULL As LandMarkAddress, NULL as LandmarkID
				from rvlfMsgOutHst OH
				INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID
				INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId
				WHERE VA.BoxId = @BoxID and SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)
					AND --OH.BoxCmdOutTypeId <> 22 				
					CT.OperationTypeId IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s 
					WHERE s.ModuleId = 22 and s.UserGroupId IN 
					(SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))
			) as a order by Timestamp desc, MessageInID desc		
			
	END
	ELSE
		BEGIN
			SELECT 'Exceeds Threshold' as ResultValue
		END
End

--exec RVLT_SP_GetLatLng2 @enddate='2010-08-11 20:00:00',@VehicleId=N'24',@orderby=N'desc',@startdate='2010-08-11 03:00:00',@interval=2000,@bigQueryingUser=17
--exec [dbo].[RVLT_SP_GetLatLng2] 46,'7/28/2010 8:00:00 AM','7/30/2010 11:30:00 PM',2000,'desc',19










GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleID]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 create proc [dbo].[rvlf_sp_GetVehicleID]
 @vehiclename varchar(500)=null
 as
 --Get vehicle nid using the name in the WebAPI
 begin
 select * from rvlfVehicle where vehicledescription = @vehiclename
 end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicleName]
@VehicleId BIGINT = NULL,
@OrganizationId bigint = NULL
AS
/*************************************************************************************      
Procedure Name		  : rvlf_sp_GetVehicleName  
Purpose               : Retrieve the list of Vehicle type details
Created by            : T Kanimozhi    
Created date          : 16-May-18
History			      : TK Created initial version   
**************************************************************************************/   
BEGIN
SET NOCOUNT ON

	SELECT  VehicleId, VehicleDescription FROM rvlfVehicle WHERE OrganizationId = @OrganizationId 	

SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleNamesTyre]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetVehicleNamesTyre]
@bigOrganizationId bigint = Null
AS
/******************************************************************************/
--	Name		  : rvlf_sp_GetVehicleNamesTyre 6
--	Description	  :	To get all the VehicleNames  
--	Author		  :	Kapil
--	Created Date  : 22-Feb-2014
--  Modified Date : 
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 	
	
	SET ANSI_WARNINGS OFF;
	
   --SELECT  VendorId,VendorName FROM rvlfTyreVendorMaster where IsDelete =0 and IsActive =1 and OrganizationId= @bigOrganizationId
       
    SELECT veh.VehicleId, veh.VehicleDescription,Va.BoxID,    
    ISNULL((select top 1 Odometer from rvlfMsgInHst where BoxId IN (Va.BoxID) order by DateTimeReceived desc) ,0)as odo  from rvlfVehicle VEH	 
        
	left join rvlfVehicleAssignment VA on VA.VehicleId = VEH.VehicleId
	WHERE veh.OrganizationId =@bigOrganizationId 		     
	select M.TyreId,TyreCode,TyreLifetime,TotalQuantity,ISNULL(UsedQuantity,0) as UsedQty, (TotalQuantity-ISNULL(UsedQuantity,0)) Available from rvlfTyreMaster M
	left join rvlfTyreStock S on S.BrandID = M.BrandID
	--left join rvlfTyreStock S on S.BrandID = M.BrandID		
	where IsDelete = 0 AND M.OrganizationId = @bigOrganizationId	
	and  (TotalQuantity-ISNULL(UsedQuantity,0)) > 0		
	select  'T' +CAST( MAX(TyreMappingId)+1 AS VARCHAR) AS TID from rvlfTyreVehicleMapping
	--select TyreId, TotalQuantity,ISNULL(UsedQuantity,0) as UsedQty, (TotalQuantity-ISNULL(UsedQuantity,0)) Available from rvlfTyreStock
    		
	SET NOCOUNT OFF
END

--select * from rvlfTyreVehicleMapping
--select TyreId from  rvlfTyreStock WHERE Available > 0
--select * from rvlfTyreHistory

 --select CONVERT(date,GETUTCDATE()-1)

 
 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleNearingMaintenance]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetVehicleNearingMaintenance]                      
@bigOrganizationID BIGINT = 0,                      
@bigFleetId bigint = NULL ,          
@bigVehicleId bigint = NULL,      
@bigPlanId bigint = NULL  ,                 
@bigVehicleTypeId bigint = NULL,      
@tiServiceType int = NULL ,                     
@intNearingPercentage int = NULL,      
@dtFromDate datetime = NULL  ,                    
@dtToDate datetime = NULL ,                    
@bigQueryingUser bigint = NUll      
AS                      
/**************************************************************************************/                      
-- Name        : rvlf_sp_GetVehicleNearingMaintenance 6,null,Null,null,null,0, null, null, null,420                      
-- Description : To get the vehicles that were nearing to the maintenance                      
-- Author      : Kumuthini. L                      
-- Company     : Angler Technologies                      
-- History     : <<Date(dd-MON-yyyy)>> Initial Reason                      
--             : 19-Jun-2010  Kumuthini Created Intial Version                       
--             : 25-Jun-2010  Kumuthini  Included the User Preferences                      
--             : 07-Oct-2010  Jeyanthi   Included PlanId, ServiceType, Nearing Percentage and Duration Percentage                      
--             : 17-Aug-2011 Ranjith Date format included                  
--             : 10-Apr-2011 Selvakumar Service type include for Concrete Mixer                  
--      : 9-Oct-2013 Gopal new field Overduebynew,ReadingswhenDue included for export    
/**************************************************************************************/                      
	BEGIN           
	
		SET NOCOUNT ON                 
		DECLARE @Distance varchar(20)                      
		DECLARE @ConversionFactor numeric (10,4) = 1.0                     
		DECLARE @DefaultDateFormat INT = 0                    
		SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.621371 ELSE 1.0 END,                      
		@Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END,                    
		@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                      
		-- ****** Distance Travelled and Engine Hrs Calculation for last 2 weeks ******                      
		DECLARE @dtLastStartDate DateTime = CONVERT(DATETIME,CONVERT(Date, DATEADD(DD, -14 , GETDATE())))                      
		DECLARE @dtLastEndDate DateTime = CONVERT(DATETIME, CONVERT(Date, DATEADD(DD, -1 , GETDATE())))                      
		-- Distance Travelled for Last 2 Weeks                      
		DECLARE @tblUtilizationBoxes TABLE                      
		(                      
			SlNo int identity(1,1), boxid nvarchar(200), VehicleDescription varchar(250), VehicleName varchar(50),                      
			StartOdometer bigint,MaxOdometer bigint, SetOdometer bigint,EndOdometer bigint                      
		)                      
		INSERT INTO @tblUtilizationBoxes (BoxID, VehicleName, VehicleDescription )
		
		SELECT va.BoxId, v.VehicleDescription as VehicleName, v.VehicleDescription                       
		FROM rvlfVehicle v                      
		INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId                      
		WHERE v.OrganizationId = @bigOrganizationID                      
		DECLARE @dtOdometerSetDate DateTime=Null, @SetOdometer bigint=0                      
		DECLARE @MaxOdometer bigint=0,@StartOdometer bigint=0,@EndOdometer bigint=0                      
		DECLARE @intCounter int                      
		SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes    
		
		DECLARE @intboxid nvarchar(200)=''                      
		WHILE @intCounter IS NOT NULL                      
			BEGIN                     
				SET @dtOdometerSetDate=NULL;SET @SetOdometer=0; SET @MaxOdometer=0;SET @StartOdometer=0; SET @EndOdometer=0;                      
				SELECT @intBoxID = BoxID FROM @tblUtilizationBoxes WHERE slno = @intCounter                      
				SELECT TOP 1 @dtOdometerSetDate=SentDateTime, @SetOdometer=CustomProp FROM rvlfMsgOutHst                     
				WHERE BoxCmdOutTypeId =14 and BoxId=@intBoxID and SentDateTime between               
				@dtLastStartDate and @dtLastEndDate order by SentDateTime desc                      

				IF @dtOdometerSetDate IS NOT NULL                      
					BEGIN                      
						SELECT @MaxOdometer=(SELECT TOP 1 Max(Odometer)
						--SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,                       
						--(CHARINDEX(';',CustomProp, CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9))) 
						FROM rvlfMsgInHst                       
						WHERE BoxId = @intBoxID                      
						AND OriginDateTime between @dtLastStartDate and @dtOdometerSetDate                       
						AND CustomProp LIKE '%Odometer%'  and BoxMsgInTypeId <> 77)                            
					END              
					
				SET @StartOdometer=(SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,                      
				(CHARINDEX(';',CustomProp,                      
				CHARINDEX('Odometer=',CustomProp,1))) -                      
				(CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst                       
				WHERE                       
				BoxId = @intBoxID                      
				AND OriginDateTime between @dtLastStartDate and @dtLastEndDate                       
				AND CustomProp LIKE '%Odometer%'  and BoxMsgInTypeId <> 77 and Odometer > 0                    
				ORDER BY OriginDateTime ASC)                            
				SET @EndOdometer = (SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,                      
				(CHARINDEX(';',CustomProp,                      
				CHARINDEX('Odometer=',CustomProp,1))) -                      
				(CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst                       
				WHERE                       
				BoxId = @intBoxID                      
				AND OriginDateTime between @dtLastStartDate and @dtLastEndDate                       
				AND CustomProp LIKE '%Odometer%'   and BoxMsgInTypeId <> 77   and Odometer > 0                 
				ORDER BY OriginDateTime DESC)                       
				UPDATE @tblUtilizationBoxes SET StartOdometer=@StartOdometer,EndOdometer=@EndOdometer,                      
				SetOdometer =@SetOdometer,MaxOdometer=@MaxOdometer  Where BoxID=@intBoxID                        
				SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes WHERE SlNo < @intCounter                      
			END       
			
		CREATE TABLE #tempDistance(boxid nvarchar(200), DistanceTravelled bigint)                       
		INSERT INTO #tempDistance(BoxId, DistanceTravelled)                      
		SELECT BoxID, ISNULL(CASE WHEN SetOdometer = 0 THEN CEILING((EndOdometer - StartOdometer)* @ConversionFactor)                       
		ELSE CEILING(((MaxOdometer - StartOdometer) + (EndOdometer - SetOdometer)) * @ConversionFactor) END, 0) AS DistanceTravelled       
		FROM @tblUtilizationBoxes                       
		ORDER BY (EndOdometer - StartOdometer) DESC                      
		-- Engine Hours for Last 2 Weeks                
		CREATE TABLE #tempEngineHrs(boxid nvarchar(200), EngineHrs bigint)                       
		--INSERT INTO #tempEngineHrs(BoxId, EngineHrs)                     
		--SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,                      
		--    CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -                       
		--    ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'                      
		--FROM rvlfMsgInHst h                
		--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                      
		--INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                      
		--WHERE                      
		-- v.OrganizationId = @bigOrganizationID                      
		-- AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate                       
		-- AND h.BoxMsgInTypeId = 3                      
		--GROUP BY h.BoxId        
		if(@tiServiceType=3)              
			BEGIN                   
				INSERT INTO #tempEngineHrs(BoxId, EngineHrs)              
				SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,                      
				CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -              
				( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'                      
				FROM rvlfMsgInHst h                       
				INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                      
				INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                      
				WHERE                      
				v.OrganizationId = @bigOrganizationID                      
				AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate  and  CustomProp like '%Sensor_NUM=2;%' AND CustomProp like '%SENSOR_DURATION=%'            
				AND h.BoxMsgInTypeId = 3 AND h.BoxMsgInTypeId <> 77                    
				GROUP BY h.BoxId                
			END              
		ELSE              
			BEGIN              
				INSERT INTO #tempEngineHrs(BoxId, EngineHrs)            
				SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,                      
				CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -                       
				( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) * 60 AS 'EngineHrs'                      
				FROM rvlfMsgInHst h                       
				INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                      
				INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                      
				WHERE                      
				v.OrganizationId = @bigOrganizationID                      
				AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate  and  CustomProp like '%Sensor_NUM=3;%' AND CustomProp like '%SENSOR_DURATION=%'                     
				AND h.BoxMsgInTypeId = 3    AND h.BoxMsgInTypeId <> 77                     
				GROUP BY h.BoxId               
			END     
		CREATE TABLE #tempLastReadings(VehicleId bigint, DistanceTravelled bigint, EngineHrs bigint)                      
		INSERT INTO #tempLastReadings(VehicleId, DistanceTravelled, EngineHrs)                       
		SELECT va.VehicleId, d.DistanceTravelled, ISNULL(e.EngineHrs, 0) FROM #tempDistance d                      
		LEFT OUTER JOIN #tempEngineHrs e ON e.BoxId = d.BoxId                      
		INNER JOIN rvlfVehicleAssignment va ON d.BoxId = va.BoxId           
		--select t.*, rvlfVehicleAssignment.VehicleId from #tempDistance t                      
		--inner join rvlfVehicleAssignment on t.BoxId = rvlfVehicleAssignment.BoxId                      
		DROP TABLE #tempEngineHrs                      
		DROP TABLE #tempDistance                      
		-- ****** Get Nearing Maintenance ******                      
		CREATE TABLE #temp(ServiceDetailsId bigint, VehiclePlanId bigint, PlanDetailsId bigint, VehicleId bigint,  PlanName varchar(100), ServiceType tinyint, Frequency tinyint, ServicesPlanned varchar(2000),
		ServiceCategoryId bigint, DueOn varchar(35), CurrentReadings FLOAT, Nearing bigint, IsRecurring bit,                       
		ServicesDone varchar(2000), ExpectedDueOn bigint, CurrentValues Varchar(30))                      

		INSERT INTO #temp(ServiceDetailsId, VehiclePlanId, PlanDetailsId, VehicleId, PlanName, ServiceType, Frequency,                       
		DueOn, CurrentReadings, Nearing, IsRecurring, ServicesDone, ExpectedDueOn, CurrentValues)                      
		
		SELECT vm.ServiceDetailsId, vm.VehiclePlanId, vm.PlanDetailsId, vp.VehicleId, mp.PlanName, vm.ServiceType, vm.Frequency,                       
		CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 1  OR vm.ServiceType = 3 THEN CONVERT(VARCHAR(35), vm.DueOn) ELSE CONVERT(VARCHAR(10), vm.DueOnDate, 101) END AS DueOn,                      
		CASE WHEN vm.ServiceType = 0  OR vm.ServiceType = 3 THEN  CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0))AS FLOAT)/(3600)AS Decimal(18,2))                      
		WHEN vm.ServiceType = 1 THEN cr.CurrentOdometerReading                       
		WHEN vm.ServiceType = 2 THEN (                      
		CASE WHEN vm.Frequency = 0 THEN DATEDIFF(D, vm.StartDate, GETUTCDATE())                       
		WHEN vm.Frequency = 1 THEN DATEDIFF(M, vm.StartDate, GETUTCDATE())                      
		WHEN vm.Frequency = 2 THEN DATEDIFF(YEAR, vm.StartDate, GETUTCDATE()) END                      
		)                      
		END AS CurrentReadings, NearingPercentage AS Nearing, mp.RecurringService, dbo.rvlf_fn_GetMaintenanceServices(1, null, vm.ServiceDetailsId) AS ServicesDone,                      
		(CASE WHEN vm.ServiceType = 2 THEN 0                      
		WHEN vm.ServiceType = 0  OR vm.ServiceType = 3 THEN (CASE WHEN lr.EngineHrs = 0 THEN 0 ELSE ISNULL(CAST(CAST((14 * (vm.DueOn - (cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0))) / lr.EngineHrs) as FLOAT)/3600 As DEcimal(18,2)),0) END
		)                                   
		WHEN vm.ServiceType = 1 THEN (CASE WHEN lr.DistanceTravelled = 0 THEN 0 ELSE ((14 * (vm.DueOn - cr.CurrentOdometerReading)) / lr.DistanceTravelled) END)                       
		ELSE '' END)  AS ExpectedDueOn,                      
		CONVERT(VARCHAR(100), COnvert(varchar(100),ISNULL(CAST(CAST(cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0) AS FLOAT)/3600 AS DECIMAL(18,2)),0)))  + ' hrs; ' + CONVERT(VARCHAR(100), CONVERT(FLOAT, ROUND((ISNULL(cr.CurrentOdometerReading, 0) * @ConversionFactor), 0, 2)))+ ' ' + @Distance AS CurrentValues                      
		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 rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                      
		INNER JOIN #tempLastReadings lr ON lr.VehicleId = v.VehicleId                      
		WHERE mp.OrganizationId = @bigOrganizationID AND vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1                       
		AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId)                      
		AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR vp.VehicleId = @bigVehicleId)                      
		AND (@bigVehicleTypeId IS NULL OR @bigVehicleTypeId='' OR v.VehicleTypeId = @bigVehicleTypeId)                      
		AND (@bigPlanId IS NULL OR @bigPlanId='' OR vp.PlanId = @bigPlanId)                      
		AND (@tiServiceType IS NULL OR @tiServiceType='' OR vm.ServiceType = @tiServiceType)                      
		AND (@dtFromDate IS NULL OR vm.DueOnDate BETWEEN @dtFromDate AND @dtToDate)                      
		AND NearingPercentage >= pd.Notification1 AND IsNearing = 1         
		
		Select *,case when (Frequency=3 OR Frequency =4) then OverdueBy + '; ' + DueBy else OverdueBy end as Overduebynew from ( --gopal                 
		SELECT distinct(t.ServiceDetailsId), t.VehiclePlanId, t.PlanDetailsId, t.VehicleId, v.VehicleDescription AS VehicleName, t.PlanName,                     
		CASE WHEN t.ServiceType = 0 THEN 'Engine Hours'                    
		WHEN t.ServiceType = 1 THEN 'Odometer'                    
		WHEN t.ServiceType = 2 THEN 'Time Based' ELSE 'Concrete Mix Hours' END AS ServiceType,                    
		t.Frequency,REPLACE(t.ServicesPlanned,',', ', ') as ServicesPlanned, 1 AS ServiceCategoryId, t.Nearing, t.IsRecurring, t.ServicesDone, @Distance AS DistanceUnits,                      
		CONVERT(VARCHAR(35), CASE WHEN t.ServiceType = 1 THEN CONVERT(VARCHAR(35),(t.DueOn* @ConversionFactor))          
		WHEN t.ServiceType = 0 or t.ServiceType = 3 THEN (Convert(varchar(30),(t.DueOn)))ELSE t.DueOn END) AS DueOn,                      
		CONVERT(BIGINT, CASE WHEN t.ServiceType = 1 THEN (t.CurrentReadings * @ConversionFactor) ELSE t.CurrentReadings END) AS CurrentReadings,         
		CASE WHEN t.ServiceType = 0  THEN CONVERT(Varchar(10), t.CurrentReadings - t.DueOn) + ' hrs'                      
		WHEN t.ServiceType = 3  THEN CONVERT(Varchar(10), t.CurrentReadings -  t.DueOn)  + ' hrs'                   
		WHEN t.ServiceType = 1 THEN CONVERT(Varchar(10),CONVERT(BIGINT, ((t.CurrentReadings - t.DueOn) * @ConversionFactor))) + ' ' + @Distance                      
		WHEN t.ServiceType = 2 THEN (CASE WHEN DATEDIFF(D, GETUTCDATE(), t.DueOn) >= 0                       
		THEN (CASE WHEN DATEDIFF(D, GETUTCDATE(), t.DueOn) / 365 > 0 THEN CONVERT(Varchar(10), (DATEDIFF(D, GETUTCDATE(), t.DueOn) / 365)) + ' yrs left'                      
		WHEN DATEDIFF(D, GETUTCDATE(), t.DueOn) / 31 > 0 THEN CONVERT(Varchar(6), (DATEDIFF(D, GETUTCDATE(), t.DueOn) / 31)) + ' months left'                      
		ELSE  CONVERT(Varchar(6), DATEDIFF(D, GETUTCDATE(), t.DueOn)) + ' days left' END                      
		)                    
		ELSE (CASE WHEN DATEDIFF(D, t.DueOn, GETUTCDATE()) / 365 > 0 THEN CONVERT(Varchar(10), (DATEDIFF(D, t.DueOn, GETUTCDATE()) / 365)) + ' yrs overdue'                      
		WHEN DATEDIFF(D, t.DueOn, GETUTCDATE()) / 31 > 0 THEN CONVERT(Varchar(6), (DATEDIFF(D, t.DueOn, GETUTCDATE()) / 31)) + ' months overdue'                      
		ELSE  CONVERT(Varchar(10), DATEDIFF(D, t.DueOn, GETUTCDATE())) + ' days overdue' END                      
		)                       
		END)                       
		ELSE NULL END AS DueBy, pd.ServiceInterval,                     
		--Convert(varchar,vm.RescheduledOn,@DefaultDateFormat)AS ReScheduledOn,                    
		ISNULL(Convert(varchar,vm.RescheduledOn,@DefaultDateFormat), '-')AS ReScheduledOn,                    
		vm.RescheduledOn AS ReScheduledOnSort, pd.PlanId,                       
		Convert(varchar,(CASE WHEN t.ServiceType = 2 THEN t.DueOn                       
		WHEN t.ServiceType = 0 OR t.ServiceType = 1  OR t.ServiceType = 3 THEN (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETDATE()) ELSE     GETDATE() END) END)                      
		ELSE '' END),@DefaultDateFormat) AS ExpectedDueOnDate,
		(CASE WHEN t.ServiceType = 2 THEN t.DueOn                       
		WHEN t.ServiceType = 0 OR t.ServiceType = 1  OR t.ServiceType = 3 THEN (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETDATE()) ELSE GETDATE() END) END)                      
		ELSE '' END) AS ExpectedDueOnDateSort, 
		CASE WHEN t.ServiceType = 2 THEN CONVERT(VARCHAR(10), DATEDIFF(D, t.DueOn, GETUTCDATE())) + ' days'  WHEN t.ServiceType = 0 OR t.ServiceType = 1 OR t.ServiceType = 3  THEN CONVERT(VARCHAR(10), DATEDIFF(D, (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETUTCDATE()) ELSE GETUTCDATE() END) END), GETUTCDATE())) + ' days'                      
		ELSE NULL END AS OverdueBy, t.CurrentValues, 
		Cast(Cast((vm.EngineHrsOnDue) AS FLOAT) / 3600 as Decimal(18,2)) as EngineHrsOnDue ,
		CASE WHEN vm.OdometerReadingOnDue IS NULL THEN vm.OdometerReadingOnDue ELSE CONVERT(INT, ROUND((vm.OdometerReadingOnDue * @ConversionFactor), 0, 0)) END AS OdometerReadingOnDue,  
		(CASE WHEN EXISTS (SELECT msd.ServiceDetailsId FROM rvlfMaintenanceServiceDetails msd WHERE msd.ServiceDetailsId = t.ServiceDetailsId) THEN 0 ELSE 1 END) AS SkipStatus, 
		Case when  t.Frequency=3 then CAST(( CONVERT(VARCHAR(35), CASE WHEN t.ServiceType = 1 THEN CONVERT(VARCHAR(35),CONVERT(BIGINT,(t.DueOn * @ConversionFactor))) ELSE t.DueOn END)) as varchar(10))+' hrs; '+  cast((ISNULL(CASE WHEN vm.OdometerReadingOnDue IS NULL THEN vm.OdometerReadingOnDue ELSE CONVERT(INT, ROUND((vm.OdometerReadingOnDue * @ConversionFactor), 0, 0)) END,0)) as varchar(10))      + @Distance          
		when  t.Frequency =4 then CAST((CAST(ISNULL(Cast(Cast((vm.EngineHrsOnDue) AS FLOAT) / 3600 as Decimal(18,2)),0) as varchar(10)) + ' hrs; ') as varchar(10))+ CAST((CONVERT(VARCHAR(35), CASE WHEN t.ServiceType = 1 THEN CONVERT(VARCHAR(35),CONVERT(BIGINT,(t.DueOn * @ConversionFactor))) ELSE t.DueOn END)) as varchar(10)) + @Distance      
		else      
		CAST(ISNULL(Cast(Cast((vm.EngineHrsOnDue) AS FLOAT) / 3600 as Decimal(18,2)),0) as varchar(10)) + ' hrs; '+CAST((CASE WHEN vm.OdometerReadingOnDue IS NULL THEN vm.OdometerReadingOnDue ELSE CONVERT(INT, ROUND((vm.OdometerReadingOnDue * @ConversionFactor),0, 0)) END) as varchar(10))  +@Distance      End as ReadingswhenDue                      
		FROM #temp t                      
		INNER JOIN rvlfVehicleMaintenanceService vm ON vm.ServiceDetailsId = t.ServiceDetailsId                      
		INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId                       
		INNER JOIN rvlfVehicle v ON v.VehicleId = t.VehicleId                      
		INNER JOIN #tempLastReadings lr ON lr.VehicleId = v.VehicleId                      
		WHERE (@intNearingPercentage IS NULL OR @intNearingPercentage='' OR                      
		(Nearing > @intNearingPercentage                       
		AND Nearing <= (CASE WHEN @intNearingPercentage = 20 THEN 30                      
		WHEN @intNearingPercentage = 30 THEN 40                      WHEN @intNearingPercentage = 40 THEN 50                      
		WHEN @intNearingPercentage = 50 THEN 60                      
		WHEN @intNearingPercentage = 60 THEN 70                      
		WHEN @intNearingPercentage = 70 THEN 80                      
		WHEN @intNearingPercentage = 80 THEN 90                       
		WHEN @intNearingPercentage = 90 THEN 100                      
		WHEN @intNearingPercentage = 100 THEN 125                      
		WHEN @intNearingPercentage = 125 THEN 150                      
		ELSE 100000 END))) AND (@tiServiceType IS NULL OR @tiServiceType='' OR t.ServiceType = @tiServiceType)                      
		) as a ORDER BY Nearing DESC                      
		DROP TABLE #temp                      
		DROP TABLE #tempLastReadings                      
		SET NOCOUNT OFF                      
	END 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleNearingMaintenance_20210626]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[rvlf_sp_GetVehicleNearingMaintenance_20210626]                      
	@bigOrganizationID BIGINT = 0,                      
	@bigFleetId bigint = NULL ,          
	@bigVehicleId bigint = NULL,      
	@bigPlanId bigint = NULL  ,                 
	@bigVehicleTypeId bigint = NULL,      
	@tiServiceType int = NULL ,                     
	@intNearingPercentage int = NULL,      
	@dtFromDate datetime = NULL  ,                    
	@dtToDate datetime = NULL ,                    
	@bigQueryingUser bigint = NUll
	--,@CustomerID int=null       
AS                      
/**************************************************************************************/                      
-- Name        : rvlf_sp_GetVehicleNearingMaintenance 6,null,null,null,null,null, null, null,null, 564,0                      
-- Description : To get the vehicles that were nearing to the maintenance                      
-- Author      : Kumuthini. L                      
-- Company     : Angler Technologies                      
-- History     : <<Date(dd-MON-yyyy)>> Initial Reason                      
--             : 19-Jun-2010  Kumuthini Created Intial Version                       
--             : 25-Jun-2010  Kumuthini  Included the User Preferences                      
--             : 07-Oct-2010  Jeyanthi   Included PlanId, ServiceType, Nearing Percentage and Duration Percentage                      
--             : 17-Aug-2011 Ranjith Date format included                  
--             : 10-Apr-2011 Selvakumar Service type include for Concrete Mixer                  
--      : 9-Oct-2013 Gopal new field Overduebynew,ReadingswhenDue included for export    
/**************************************************************************************/                      
	BEGIN                      
		SET NOCOUNT ON                 
		DECLARE @Distance varchar(20)                      
		DECLARE @ConversionFactor numeric (10,2) = 1.0                     
		DECLARE @DefaultDateFormat INT = 0                    
		SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.621371 ELSE 1.000000 END,                      
		@Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END,                    
		@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                      
		-- ****** Distance Travelled and Engine Hrs Calculation for last 2 weeks ******                      
		DECLARE @dtLastStartDate DateTime = CONVERT(DATETIME,CONVERT(Date, DATEADD(DD, -14 , GETDATE())))                      
		DECLARE @dtLastEndDate DateTime = CONVERT(DATETIME, CONVERT(Date, DATEADD(DD, -1 , GETDATE())))                      
		-- Distance Travelled for Last 2 Weeks                      
		DECLARE @tblUtilizationBoxes TABLE                      
		(                      
			SlNo int identity(1,1), BoxID varchar(100), VehicleDescription varchar(250), VehicleName varchar(50),                      
			StartOdometer bigint,MaxOdometer bigint, SetOdometer bigint,EndOdometer bigint                      
		)                      
		INSERT INTO @tblUtilizationBoxes (BoxID, VehicleName, VehicleDescription )                      
		SELECT va.BoxId, v.VehicleDescription as VehicleName, v.VehicleDescription                       
		FROM rvlfVehicle v                      
		INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId                      
		WHERE v.OrganizationId = @bigOrganizationID                      
		DECLARE @dtOdometerSetDate DateTime=Null, @SetOdometer bigint=0                      
		DECLARE @MaxOdometer bigint=0,@StartOdometer bigint=0,@EndOdometer bigint=0                      
		DECLARE @intCounter int                      
		SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes                       
		DECLARE @intBoxID varchar(100)=''                      
		WHILE @intCounter IS NOT NULL                      
			BEGIN                     
				SET @dtOdometerSetDate=NULL;SET @SetOdometer=0; SET @MaxOdometer=0;SET @StartOdometer=0; SET @EndOdometer=0;                      
				SELECT @intBoxID = BoxID FROM @tblUtilizationBoxes WHERE slno = @intCounter                      
				--SELECT TOP 1 @dtOdometerSetDate=SentDateTime, @SetOdometer=CustomProp FROM rvlfMsgOutHst                     
				--   WHERE BoxCmdOutTypeId =14 and BoxId=@intBoxID and SentDateTime between               
				--   @dtLastStartDate and @dtLastEndDate order by SentDateTime desc                      
				IF @dtOdometerSetDate IS NOT NULL                      
					BEGIN                      
						SELECT @MaxOdometer=(SELECT TOP 1 Max(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,                      
						(CHARINDEX(';',CustomProp,                      
						CHARINDEX('Odometer=',CustomProp,1))) -                      
						(CHARINDEX('Odometer=',CustomProp,1)+9))) FROM rvlfMsgInHst                       
						WHERE                       
						BoxId = @intBoxID                      
						AND OriginDateTime between @dtLastStartDate and @dtOdometerSetDate                       
						AND CustomProp LIKE '%Odometer%'  and BoxMsgInTypeId <> 77)                            
					END                      
				SET @StartOdometer=(SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9, 
				(CHARINDEX(';',CustomProp, CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst WHERE BoxId = @intBoxID                      
				AND OriginDateTime between @dtLastStartDate and @dtLastEndDate                       
				AND CustomProp LIKE '%Odometer%'  and BoxMsgInTypeId <> 77 and Odometer > 0                    
				ORDER BY OriginDateTime ASC)                            
				SET @EndOdometer = (SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,                      
				(CHARINDEX(';',CustomProp,                      
				CHARINDEX('Odometer=',CustomProp,1))) -                      
				(CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst                       
				WHERE                       
				BoxId = @intBoxID                      
				AND OriginDateTime between @dtLastStartDate and @dtLastEndDate                       
				AND CustomProp LIKE '%Odometer%'   and BoxMsgInTypeId <> 77   and Odometer > 0                 
				ORDER BY OriginDateTime DESC)                       
				UPDATE @tblUtilizationBoxes SET StartOdometer=@StartOdometer,EndOdometer=@EndOdometer,                      
				SetOdometer =@SetOdometer,MaxOdometer=@MaxOdometer  Where BoxID=@intBoxID                        
				SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes WHERE SlNo < @intCounter                      
			END                      
		Declare  @tempDistance TABLE(BoxId varchar(100), DistanceTravelled bigint)                       
		INSERT INTO @tempDistance(BoxId, DistanceTravelled)                      
		SELECT BoxID, ISNULL(CASE WHEN SetOdometer = 0 THEN CEILING((EndOdometer - StartOdometer)* @ConversionFactor)                       
		ELSE CEILING(((MaxOdometer - StartOdometer) + (EndOdometer - SetOdometer)) * @ConversionFactor) END, 0) AS DistanceTravelled                      
		FROM @tblUtilizationBoxes                       
		ORDER BY (EndOdometer - StartOdometer) DESC                      
		-- Engine Hours for Last 2 Weeks                
		DECLARE  @tempEngineHrs TABLE (BoxId varchar(100), EngineHrs bigint)                       
		--INSERT INTO #tempEngineHrs(BoxId, EngineHrs)                     
		--SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,                      
		--    CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -                       
		--    ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'                      
		--FROM rvlfMsgInHst h                
		--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                      
		--INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                      
		--WHERE                      
		-- v.OrganizationId = @bigOrganizationID                      
		-- AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate                       
		-- AND h.BoxMsgInTypeId = 3                      
		--GROUP BY h.BoxId                      
		--if(@tiServiceType=3)              
		--BEGIN                   
		--INSERT INTO #tempEngineHrs(BoxId, EngineHrs)              
		--SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,                      
		-- CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -              
		-- ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'                      
		--FROM rvlfMsgInHst h                       
		--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                      
		--INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                      
		--WHERE                      
		-- v.OrganizationId = @bigOrganizationID                      
		-- AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate  and  CustomProp like '%Sensor_NUM=2;%' AND CustomProp like '%SENSOR_DURATION=%'            
		-- AND h.BoxMsgInTypeId = 3 AND h.BoxMsgInTypeId <> 77                    
		--GROUP BY h.BoxId                
		--END              
		--ELSE              
		--BEGIN      
		--INSERT INTO #tempEngineHrs(BoxId, EngineHrs)                             
		--SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,                      
		-- CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -                       
		-- ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) * 60 AS 'EngineHrs'                      
		--FROM rvlfMsgInHst h                       
		--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                      
		--INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                      
		--WHERE                      
		-- v.OrganizationId = @bigOrganizationID                      
		-- AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate  and  CustomProp like '%Sensor_NUM=3;%' AND CustomProp like '%SENSOR_DURATION=%'                     AND h.BoxMsgInTypeId = 3    AND h.BoxMsgInTypeId <> 77                     
		--GROUP BY h.BoxId              
		--END                      
		if(@tiServiceType=3)              
			BEGIN   
				INSERT INTO @tempEngineHrs(BoxId, EngineHrs)              
				Select a.boxid,sum(EngineHrs) from (
				SELECT h.BoxId, 
				(case when vt.VehicleTypeId in (1,2) and isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR1=',';'),0) > p.RC1 
				then isnull(Datediff(HH,max(origindatetime),min(Origindatetime)),0) 
				when vt.VehicleTypeId in (3,4) and isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR1=',';'),0) > p.RC1 and isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR2=',';'),0) > p.RC2
				then isnull(Datediff(HH,max(origindatetime),min(Origindatetime)),0) 
				else 0 end)  AS 'EngineHrs'                      
				FROM rvlfMsgInHst h                       
				inner join rvlfParamRange p on h.BoxId=p.Boxid
				inner join rvlfMAKDevices md on md.BoxId=h.BoxId
				inner join rvlfVehicleType vt on vt.VehicleTypeId=md.SubTypeId
				INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                      
				INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                      
				WHERE                      
				v.OrganizationId = @bigOrganizationID  
				-- isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR1=',';'),0) > p.RC1                  
				AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate              
				AND h.BoxMsgInTypeId in (1,8)                 
				GROUP BY h.BoxId,vt.VehicleTypeId,h.CustomProp,p.RC1,p.RC2) as a group by a.BoxId     
			END              
		ELSE              
			BEGIN              
				INSERT INTO @tempEngineHrs(BoxId, EngineHrs)
				Select a.boxid,sum(EngineHrs) from (
				SELECT h.BoxId,
				(case when vt.VehicleTypeId in (1,2) and isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR1=',';'),0) > p.RC1 
				then isnull(Datediff(HH,max(origindatetime),min(Origindatetime)),0) 
				when vt.VehicleTypeId in (1,2) and isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR1=',';'),0) > p.RC1 and isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR2=',';'),0) > p.RC2
				then isnull(Datediff(HH,max(origindatetime),min(Origindatetime)),0) 
				else 0 end)  AS 'EngineHrs'                   
				FROM rvlfMsgInHst h               
				inner join rvlfParamRange p on h.BoxId=p.Boxid          
				inner join rvlfMAKDevices md on md.BoxId=h.BoxId
				inner join rvlfVehicleType vt on vt.VehicleTypeId=md.SubTypeId
				INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                      
				INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                      
				WHERE                      
				v.OrganizationId = @bigOrganizationID       
				--isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR1=',';'),0) < p.RC1               
				AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate              
				AND h.BoxMsgInTypeId in (1,8)            
				GROUP BY h.BoxId,vt.VehicleTypeId,h.CustomProp,p.RC1,p.RC2) as a group by a.BoxId                    
			END 
		--CREATE TABLE #tempLastReadings(VehicleId bigint, DistanceTravelled bigint, EngineHrs bigint)  
		DECLARE @tempLastReadings TABLE (VehicleId bigint, DistanceTravelled bigint, EngineHrs bigint)
		INSERT INTO @tempLastReadings(VehicleId, DistanceTravelled, EngineHrs)                       
		SELECT va.VehicleId, d.DistanceTravelled, ISNULL(e.EngineHrs, 0) FROM @tempDistance d                      
		LEFT OUTER JOIN @tempEngineHrs e ON e.BoxId = d.BoxId                      
		INNER JOIN rvlfMAKDevices va ON d.BoxId = va.BoxId           
		--select t.*, rvlfVehicleAssignment.VehicleId from #tempDistance t                      
		--inner join rvlfVehicleAssignment on t.BoxId = rvlfVehicleAssignment.BoxId                      
		--DROP TABLE #tempEngineHrs                      
		--DROP TABLE #tempDistance                      
		-- ****** Get Nearing Maintenance ******   
		DECLARE @temp TABLE (ServiceDetailsId bigint, VehiclePlanId bigint, PlanDetailsId bigint, VehicleId bigint,                       
		PlanName varchar(100), ServiceType tinyint, Frequency tinyint, ServicesPlanned varchar(2000),                       
		ServiceCategoryId bigint, DueOn varchar(35), CurrentReadings FLOAT, Nearing int, IsRecurring bit,                       
		ServicesDone varchar(2000), ExpectedDueOn bigint, CurrentValues Varchar(30))                      
		INSERT INTO @temp(ServiceDetailsId, VehiclePlanId, PlanDetailsId, VehicleId, PlanName, ServiceType, Frequency,                       
		DueOn, CurrentReadings, Nearing, IsRecurring, ServicesDone, ExpectedDueOn, CurrentValues)                      
		SELECT vm.ServiceDetailsId, vm.VehiclePlanId, vm.PlanDetailsId, vp.VehicleId, mp.PlanName, vm.ServiceType, vm.Frequency,                       
		CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 1  OR vm.ServiceType = 3 THEN CONVERT(VARCHAR(35), vm.DueOn) ELSE CONVERT(VARCHAR(10), vm.DueOnDate, 101) END AS DueOn,                      
		CASE WHEN vm.ServiceType = 0  OR vm.ServiceType = 3 THEN  CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0))AS FLOAT)/(3600)AS Decimal(18,2))                      
		WHEN vm.ServiceType = 1 THEN cr.CurrentOdometerReading                       
		WHEN vm.ServiceType = 2 THEN (                      
		CASE WHEN vm.Frequency = 0 THEN DATEDIFF(D, vm.StartDate, GETUTCDATE())                       
		WHEN vm.Frequency = 1 THEN DATEDIFF(M, vm.StartDate, GETUTCDATE())                      
		WHEN vm.Frequency = 2 THEN DATEDIFF(YEAR, vm.StartDate, GETUTCDATE()) END                      
		)                      
		END AS CurrentReadings, NearingPercentage AS Nearing, mp.RecurringService, dbo.rvlf_fn_GetMaintenanceServices(1, null, vm.ServiceDetailsId) AS ServicesDone,                      
		--CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3  THEN CONVERT(VARCHAR(10), vm.DueOn) + ' hrs'    
		--     WHEN vm.ServiceType = 1 THEN CONVERT(VARCHAR(10), CONVERT(INT, ROUND((vm.DueOn * @ConversionFactor), 0, 0))) + @Distance    
		--     ELSE CONVERT(VARCHAR(10), vm.DueOnDate, 101) END AS ExpectedDueOn, 
		(CASE WHEN vm.ServiceType = 2 THEN 0                      
		WHEN vm.ServiceType = 0  OR vm.ServiceType = 3 THEN (CASE WHEN lr.EngineHrs = 0 THEN 0 ELSE ISNULL(CAST(CAST((14 * (vm.DueOn - (cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0))) / lr.EngineHrs) as FLOAT)/3600 As DEcimal(18,2)),0) END)           
		WHEN vm.ServiceType = 1 THEN (CASE WHEN lr.DistanceTravelled = 0 THEN 0 ELSE ((14 * (vm.DueOn - cr.CurrentOdometerReading)) / lr.DistanceTravelled) END)              ELSE '' END)  AS ExpectedDueOn,   
		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))) + @Distance    
		WHEN vm.ServiceType = 2 THEN CONVERT(Varchar(11), GETUTCDATE(), @DefaultDateFormat) END AS CurrentValues    
		--CONVERT(VARCHAR(30), COnvert(varchar(30),ISNULL(CAST(CAST(cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0) AS FLOAT)/3600 AS DECIMAL(18,2)),0)))  + ' hrs; ' + CONVERT(VARCHAR(10), CONVERT(INT, ROUND((ISNULL(cr.CurrentOdometerReading, 0) * @ConversionFactor), 0, 0)))+ ' ' + @Distance AS CurrentValues                      
		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 rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId  
		INNER JOIN rvlfMAKDevices MD ON MD.VehicleId= vp.VehicleId                              
		INNER JOIN @tempLastReadings lr ON lr.VehicleId = v.VehicleId                      
		WHERE mp.OrganizationId = @bigOrganizationID AND vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1                       
		AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId)                      
		AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR vp.VehicleId = @bigVehicleId)                      
		AND (@bigVehicleTypeId IS NULL OR @bigVehicleTypeId='' OR v.VehicleTypeId = @bigVehicleTypeId)                      
		AND (@bigPlanId IS NULL OR @bigPlanId='' OR vp.PlanId = @bigPlanId)                      
		AND (@tiServiceType IS NULL OR vm.ServiceType = @tiServiceType)                      
		AND vm.ServiceType in (0,2)
		AND (@dtFromDate IS NULL OR vm.DueOnDate BETWEEN @dtFromDate AND @dtToDate)                      
		AND NearingPercentage >= pd.Notification1 
		AND IsNearing = 1 
		--AND ((@CustomerID is Null) or (@CustomerID = 0) or (MD.CustomerId = @CustomerID)) 
		and vm.ServiceType <> 1                         
		Select *,case when (Frequency=3 OR Frequency =4) then OverdueBy + '; ' + DueBy else OverdueBy end as Overduebynew from ( --gopal                 
		SELECT distinct(t.ServiceDetailsId), t.VehiclePlanId, t.PlanDetailsId, t.VehicleId, v.VehicleDescription AS VehicleName, t.PlanName,                     
		CASE WHEN t.ServiceType = 0 THEN 'Running Hours'                    
		WHEN t.ServiceType = 1 THEN 'Odometer'                    
		WHEN t.ServiceType = 2 THEN 'Time Based' ELSE 'Concrete Mix Hours' END AS ServiceType,                    
		t.Frequency,REPLACE(t.ServicesPlanned,',', ', ') as ServicesPlanned, 1 AS ServiceCategoryId, t.Nearing, t.IsRecurring, t.ServicesDone, @Distance AS DistanceUnits,                      
		CONVERT(VARCHAR(35), CASE WHEN t.ServiceType = 1 THEN CONVERT(VARCHAR(35),(t.DueOn* @ConversionFactor))          
		WHEN t.ServiceType = 0 or t.ServiceType = 3 THEN (Convert(varchar(30),(t.DueOn)))ELSE t.DueOn END) AS DueOn,                      
		CONVERT(BIGINT, CASE WHEN t.ServiceType = 1 THEN (t.CurrentReadings * @ConversionFactor) ELSE t.CurrentReadings END) AS CurrentReadings,         
		CASE WHEN t.ServiceType = 0  THEN 
		
		CONVERT(Varchar(10), (cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0)) - t.DueOn) + ' hrs'                      
		
		--cast(CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3 THEN CONVERT(Varchar(10), (cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0)))
		--WHEN vm.ServiceType = 1 THEN CONVERT(Varchar(10), CONVERT(INT, (cr.CurrentOdometerReading * @ConversionFactor))) + @Distance    
		--WHEN vm.ServiceType = 2 THEN CONVERT(Varchar(10), GETUTCDATE(), 101) END as varchar(100))


		WHEN t.ServiceType = 3  THEN CONVERT(Varchar(10), t.CurrentReadings -  t.DueOn)  + ' hrs'                   
		WHEN t.ServiceType = 1 THEN CONVERT(Varchar(10),CONVERT(BIGINT, ((t.CurrentReadings - t.DueOn) * @ConversionFactor))) + ' ' + @Distance                     
		WHEN t.ServiceType = 2 THEN (CASE WHEN DATEDIFF(D, GETUTCDATE(), t.DueOn) >= 0                       
		THEN (CASE WHEN DATEDIFF(D, GETUTCDATE(), t.DueOn) / 365 > 0 THEN CONVERT(Varchar(10), (DATEDIFF(D, GETUTCDATE(), t.DueOn) / 365)) + ' yrs left'                    
		WHEN DATEDIFF(D, GETUTCDATE(), t.DueOn) / 31 > 0 THEN CONVERT(Varchar(6), (DATEDIFF(D, GETUTCDATE(), t.DueOn) / 31)) + ' months left'                     
		ELSE  CONVERT(Varchar(6), DATEDIFF(D, GETUTCDATE(), t.DueOn)) + ' days left' END)                    
		ELSE (CASE WHEN DATEDIFF(D, t.DueOn, GETUTCDATE()) / 365 > 0 THEN CONVERT(Varchar(10), (DATEDIFF(D, t.DueOn, GETUTCDATE()) / 365)) + ' yrs overdue'                      
		WHEN DATEDIFF(D, t.DueOn, GETUTCDATE()) / 31 > 0 THEN CONVERT(Varchar(6), (DATEDIFF(D, t.DueOn, GETUTCDATE()) / 31)) + ' months overdue'                      
		ELSE  CONVERT(Varchar(10), DATEDIFF(D, t.DueOn, GETUTCDATE())) + ' days overdue' END                      
		)                       
		END)                       
		ELSE NULL END AS DueBy, pd.ServiceInterval,                     
		--Convert(varchar,vm.RescheduledOn,@DefaultDateFormat)AS ReScheduledOn,                    
		ISNULL(Convert(varchar,vm.RescheduledOn,@DefaultDateFormat), '-')AS ReScheduledOn,                    
		vm.RescheduledOn AS ReScheduledOnSort, pd.PlanId,                       
		Convert(varchar,(CASE WHEN t.ServiceType = 2 THEN t.DueOn                       
		WHEN t.ServiceType = 0 OR t.ServiceType = 1  OR t.ServiceType = 3 THEN (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETDATE()) ELSE    
		GETDATE() END) END)                      
		ELSE '' END),@DefaultDateFormat) AS ExpectedDueOnDate,
		(CASE WHEN t.ServiceType = 2 THEN t.DueOn                       
		WHEN t.ServiceType = 0 OR t.ServiceType = 1  OR t.ServiceType = 3 THEN (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETDATE()) ELSE GETDATE() END) END)                      
		ELSE '' END) AS ExpectedDueOnDateSort, 
		CASE WHEN t.ServiceType = 2 THEN CONVERT(VARCHAR(10), DATEDIFF(D, t.DueOn, GETUTCDATE())) + ' days'                      
		WHEN t.ServiceType = 0 OR t.ServiceType = 1 OR t.ServiceType = 3  THEN CONVERT(VARCHAR(10), DATEDIFF(D, (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETUTCDATE()) ELSE GETUTCDATE() END) END), GETUTCDATE())) + ' days'                      
		ELSE NULL END AS OverdueBy, t.CurrentValues, 
		Cast(Cast((vm.EngineHrsOnDue) AS FLOAT) / 3600 as Decimal(18,2)) as EngineHrsOnDue ,
		CASE WHEN vm.OdometerReadingOnDue IS NULL THEN vm.OdometerReadingOnDue ELSE CONVERT(INT, ROUND((vm.OdometerReadingOnDue * @ConversionFactor), 0, 0)) END AS OdometerReadingOnDue,  
		(CASE WHEN EXISTS (SELECT msd.ServiceDetailsId FROM rvlfMaintenanceServiceDetails msd WHERE msd.ServiceDetailsId = t.ServiceDetailsId) THEN 0 ELSE 1 END) AS SkipStatus, 
		Case when  t.Frequency=3 then CAST(( CONVERT(VARCHAR(35), CASE WHEN t.ServiceType = 1 THEN CONVERT(VARCHAR(35),CONVERT(BIGINT,(t.DueOn * @ConversionFactor))) ELSE t.DueOn END)) as varchar(10))+' hrs; '+  cast((ISNULL(CASE WHEN vm.OdometerReadingOnDue IS NULL THEN vm.OdometerReadingOnDue ELSE CONVERT(INT, ROUND((vm.OdometerReadingOnDue * @ConversionFactor), 0, 0)) END,0)) as varchar(10))      + @Distance          
		when  t.Frequency =4 then CAST((CAST(ISNULL(Cast(Cast((vm.EngineHrsOnDue) AS FLOAT) / 3600 as Decimal(18,2)),0) as varchar(10)) + ' hrs; ') as varchar(10))+ CAST((CONVERT(VARCHAR(35), CASE WHEN t.ServiceType = 1 THEN CONVERT(VARCHAR(35),CONVERT(BIGINT,
		(t.DueOn * @ConversionFactor))) ELSE t.DueOn END)) as varchar(10)) + @Distance      
		else      
		CAST(ISNULL(Cast(Cast((vm.EngineHrsOnDue) AS FLOAT) / 3600 as Decimal(18,2)),0) as varchar(10)) + ' hrs; 'End as ReadingswhenDue                      
		FROM @temp t                      
		INNER JOIN rvlfVehicleMaintenanceService vm ON vm.ServiceDetailsId = t.ServiceDetailsId                      
		INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId    
		
		INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId                      
		INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId           
		
		                   
		INNER JOIN rvlfVehicle v ON v.VehicleId = t.VehicleId                      
		INNER JOIN @tempLastReadings lr ON lr.VehicleId = v.VehicleId                      
		WHERE (@intNearingPercentage IS NULL OR @intNearingPercentage='' OR                      
		(Nearing > @intNearingPercentage                       
		AND Nearing <= (CASE WHEN @intNearingPercentage = 20 THEN 30                      
		WHEN @intNearingPercentage = 30 THEN 40                      WHEN @intNearingPercentage = 40 THEN 50                      
		WHEN @intNearingPercentage = 50 THEN 60                      
		WHEN @intNearingPercentage = 60 THEN 70                      
		WHEN @intNearingPercentage = 70 THEN 80                      
		WHEN @intNearingPercentage = 80 THEN 90                       
		WHEN @intNearingPercentage = 90 THEN 100                      
		WHEN @intNearingPercentage = 100 THEN 125                      
		WHEN @intNearingPercentage = 125 THEN 150                      
		ELSE 100000 END))) AND (@tiServiceType IS NULL OR @tiServiceType='' OR t.ServiceType = @tiServiceType)                      
		AND vm.ServiceType in (0,2)
		) as a ORDER BY Nearing DESC                      
		--DROP TABLE #temp                      
		--   DROP TABLE #tempLastReadings                      
		SET NOCOUNT OFF                      
	END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleNearingMaintenance_Test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetVehicleNearingMaintenance_Test]              
@bigOrganizationID BIGINT = NULL,              
@bigFleetId bigint = NULL ,      
@bigVehicleId bigint = NULL,  
@bigPlanId bigint = NULL,              
@bigVehicleTypeId bigint = NULL,  
@tiServiceType int = NULL,              
@intNearingPercentage int = NULL,             
@dtFromDate datetime = NULL,              
@dtToDate datetime = NULL,              
@bigQueryingUser bigint = NULL  
AS              
/**************************************************************************************/              
-- Name        : rvlf_sp_GetVehicleNearingMaintenance_Test 139,null,Null,null,null,0, null, null, 303              
-- Description : To get the vehicles that were nearing to the maintenance              
-- Author      : Kumuthini. L              
-- Company     : Angler Technologies              
-- History     : <<Date(dd-MON-yyyy)>> Initial Reason              
--             : 19-Jun-2010  Kumuthini Created Intial Version               
--             : 25-Jun-2010  Kumuthini  Included the User Preferences              
--             : 07-Oct-2010  Jeyanthi   Included PlanId, ServiceType, Nearing Percentage and Duration Percentage              
--             : 17-Aug-2011 Ranjith Date format included          
--             : 10-Apr-2011 Selvakumar Service type include for Concrete Mixer          
              
/**************************************************************************************/              
BEGIN              
SET NOCOUNT ON         
 DECLARE @Distance varchar(20)              
 DECLARE @ConversionFactor numeric (10,2) = 1.0             
 DECLARE @DefaultDateFormat INT = 0            
              
    SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,              
     @Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END,            
     @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              
               
 -- ****** Distance Travelled and Engine Hrs Calculation for last 2 weeks ******              
 DECLARE @dtLastStartDate DateTime = CONVERT(DATETIME,CONVERT(Date, DATEADD(DD, -14 , GETDATE())))              
    DECLARE @dtLastEndDate DateTime = CONVERT(DATETIME, CONVERT(Date, DATEADD(DD, -1 , GETDATE())))              
               
 -- Distance Travelled for Last 2 Weeks              
     DECLARE @tblUtilizationBoxes TABLE              
 (              
  SlNo int identity(1,1), BoxID int, VehicleDescription varchar(250), VehicleName varchar(50),              
  StartOdometer bigint,MaxOdometer bigint, SetOdometer bigint,EndOdometer bigint              
 )              
              
 INSERT INTO @tblUtilizationBoxes (BoxID, VehicleName, VehicleDescription )              
  SELECT va.BoxId, v.VehicleDescription as VehicleName, v.VehicleDescription               
  FROM rvlfVehicle v              
  INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId              
  WHERE v.OrganizationId = @bigOrganizationID              
                
 DECLARE @dtOdometerSetDate DateTime=Null, @SetOdometer bigint=0              
 DECLARE @MaxOdometer bigint=0,@StartOdometer bigint=0,@EndOdometer bigint=0              
               
    DECLARE @intCounter int              
 SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes               
 DECLARE @intBoxID int=0              
 WHILE @intCounter IS NOT NULL              
  BEGIN              
                 
   SET @dtOdometerSetDate=NULL;SET @SetOdometer=0; SET @MaxOdometer=0;SET @StartOdometer=0; SET @EndOdometer=0;              
                 
   SELECT @intBoxID = BoxID FROM @tblUtilizationBoxes WHERE slno = @intCounter                 
                 
   SELECT TOP 1 @dtOdometerSetDate=SentDateTime, @SetOdometer=CustomProp FROM rvlfMsgOutHst             
      WHERE BoxCmdOutTypeId =14 and BoxId=@intBoxID and SentDateTime between       
      @dtLastStartDate and @dtLastEndDate order by SentDateTime desc              
                  
                 
   IF @dtOdometerSetDate IS NOT NULL              
    BEGIN              
     SELECT @MaxOdometer=(SELECT TOP 1 Max(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,              
      (CHARINDEX(';',CustomProp,              
       CHARINDEX('Odometer=',CustomProp,1))) -              
 (CHARINDEX('Odometer=',CustomProp,1)+9))) FROM rvlfMsgInHst               
      WHERE               
       BoxId = @intBoxID              
       AND OriginDateTime between @dtLastStartDate and @dtOdometerSetDate               
       AND CustomProp LIKE '%Odometer%'  and BoxMsgInTypeId <> 77)                    
                    
    END              
                 
   SET @StartOdometer=(SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,              
       (CHARINDEX(';',CustomProp,              
       CHARINDEX('Odometer=',CustomProp,1))) -              
       (CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst               
      WHERE               
       BoxId = @intBoxID              
       AND OriginDateTime between @dtLastStartDate and @dtLastEndDate               
       AND CustomProp LIKE '%Odometer%'  and BoxMsgInTypeId <> 77             
      ORDER BY OriginDateTime ASC)                    
                   
   SET @EndOdometer = (SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,              
       (CHARINDEX(';',CustomProp,              
       CHARINDEX('Odometer=',CustomProp,1))) -              
       (CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst               
      WHERE               
       BoxId = @intBoxID              
       AND OriginDateTime between @dtLastStartDate and @dtLastEndDate               
       AND CustomProp LIKE '%Odometer%'   and BoxMsgInTypeId <> 77            
      ORDER BY OriginDateTime DESC)               
                    
                 
   UPDATE @tblUtilizationBoxes SET StartOdometer=@StartOdometer,EndOdometer=@EndOdometer,              
    SetOdometer =@SetOdometer,MaxOdometer=@MaxOdometer  Where BoxID=@intBoxID                
                 
   SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes WHERE SlNo < @intCounter              
  END              
                
     CREATE TABLE #tempDistance(BoxId int, DistanceTravelled bigint)               
               
  INSERT INTO #tempDistance(BoxId, DistanceTravelled)              
  SELECT BoxID, ISNULL(CASE WHEN SetOdometer = 0 THEN CEILING((EndOdometer - StartOdometer)* @ConversionFactor)               
  ELSE CEILING(((MaxOdometer - StartOdometer) + (EndOdometer - SetOdometer)) * @ConversionFactor) END, 0) AS DistanceTravelled              
   FROM @tblUtilizationBoxes               
  ORDER BY (EndOdometer - StartOdometer) DESC              
                
  -- Engine Hours for Last 2 Weeks              
               
  CREATE TABLE #tempEngineHrs(BoxId int, EngineHrs bigint)               
               
  --INSERT INTO #tempEngineHrs(BoxId, EngineHrs)             
  --SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,              
  --    CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -               
  --    ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'              
  --FROM rvlfMsgInHst h               
  --INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId              
  --INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId              
  --WHERE              
  -- v.OrganizationId = @bigOrganizationID              
  -- AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate               
  -- AND h.BoxMsgInTypeId = 3              
  --GROUP BY h.BoxId              
             
 if(@tiServiceType=3)      
 BEGIN           
 INSERT INTO #tempEngineHrs(BoxId, EngineHrs)      
 SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,              
  CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -      
  ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'              
 FROM rvlfMsgInHst h               
 INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId              
 INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId              
 WHERE              
  v.OrganizationId = @bigOrganizationID              
  AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate  and  CustomProp like '%Sensor_NUM=2;%' AND CustomProp like '%SENSOR_DURATION=%'    
  AND h.BoxMsgInTypeId = 3 AND h.BoxMsgInTypeId <> 77            
 GROUP BY h.BoxId        
 END      
 ELSE      
 BEGIN      
    
 INSERT INTO #tempEngineHrs(BoxId, EngineHrs)    
         
 SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,              
  CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -               
  ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) * 60 AS 'EngineHrs'              
 FROM rvlfMsgInHst h               
 INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId              
 INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId              
 WHERE              
  v.OrganizationId = @bigOrganizationID              
  AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate  and  CustomProp like '%Sensor_NUM=3;%' AND CustomProp like '%SENSOR_DURATION=%'             
  AND h.BoxMsgInTypeId = 3    AND h.BoxMsgInTypeId <> 77             
 GROUP BY h.BoxId       
  
  
 END              
         
  CREATE TABLE #tempLastReadings(VehicleId bigint, DistanceTravelled bigint, EngineHrs bigint)              
                 
  INSERT INTO #tempLastReadings(VehicleId, DistanceTravelled, EngineHrs)               
  SELECT va.VehicleId, d.DistanceTravelled, ISNULL(e.EngineHrs, 0) FROM #tempDistance d              
  LEFT OUTER JOIN #tempEngineHrs e ON e.BoxId = d.BoxId              
  INNER JOIN rvlfVehicleAssignment va ON d.BoxId = va.BoxId              
                
  --select t.*, rvlfVehicleAssignment.VehicleId from #tempDistance t              
  --inner join rvlfVehicleAssignment on t.BoxId = rvlfVehicleAssignment.BoxId              
                
  DROP TABLE #tempEngineHrs              
  DROP TABLE #tempDistance              
       
 -- ****** Get Nearing Maintenance ******              
 CREATE TABLE #temp(ServiceDetailsId bigint, VehiclePlanId bigint, PlanDetailsId bigint, VehicleId bigint,               
 PlanName varchar(100), ServiceType tinyint, Frequency tinyint, ServicesPlanned varchar(2000),               
 ServiceCategoryId bigint, DueOn varchar(35), CurrentReadings FLOAT, Nearing int, IsRecurring bit,               
 ServicesDone varchar(2000), ExpectedDueOn bigint, CurrentValues Varchar(30))              
               
 INSERT INTO #temp(ServiceDetailsId, VehiclePlanId, PlanDetailsId, VehicleId, PlanName, ServiceType, Frequency,               
 DueOn, CurrentReadings, Nearing, IsRecurring, ServicesDone, ExpectedDueOn, CurrentValues)              
    SELECT vm.ServiceDetailsId, vm.VehiclePlanId, vm.PlanDetailsId, vp.VehicleId, mp.PlanName, vm.ServiceType, vm.Frequency,               
 CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 1  OR vm.ServiceType = 3 THEN CONVERT(VARCHAR(35), vm.DueOn) ELSE CONVERT(VARCHAR(10), vm.DueOnDate, 101) END AS DueOn,              
 CASE WHEN vm.ServiceType = 0  OR vm.ServiceType = 3 THEN  CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0))AS FLOAT)/(3600)AS Decimal(18,2))              
   WHEN vm.ServiceType = 1 THEN cr.CurrentOdometerReading               
   WHEN vm.ServiceType = 2 THEN (              
               CASE WHEN vm.Frequency = 0 THEN DATEDIFF(D, vm.StartDate, GETUTCDATE())               
                    WHEN vm.Frequency = 1 THEN DATEDIFF(M, vm.StartDate, GETUTCDATE())              
                    WHEN vm.Frequency = 2 THEN DATEDIFF(YEAR, vm.StartDate, GETUTCDATE()) END              
               )              
 END AS CurrentReadings, NearingPercentage AS Nearing, mp.RecurringService, dbo.rvlf_fn_GetMaintenanceServices(1, null, vm.ServiceDetailsId) AS ServicesDone,              
(CASE WHEN vm.ServiceType = 2 THEN 0              
       WHEN vm.ServiceType = 0  OR vm.ServiceType = 3 THEN (CASE WHEN lr.EngineHrs = 0 THEN 0 ELSE ISNULL(CAST(CAST((14 * (vm.DueOn - (cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0))) / lr.EngineHrs) as FLOAT)/3600 As DEcimal(18,2)),0) END)     
         
       WHEN vm.ServiceType = 1 THEN (CASE WHEN lr.DistanceTravelled = 0 THEN 0 ELSE ((14 * (vm.DueOn - cr.CurrentOdometerReading)) / lr.DistanceTravelled) END)               
       ELSE '' END)  AS ExpectedDueOn,              
 CONVERT(VARCHAR(30), COnvert(varchar(30),ISNULL(CAST(CAST(cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0) AS FLOAT)/3600 AS DECIMAL(18,2)),0)))  + ' hrs; ' + CONVERT(VARCHAR(10), CONVERT(INT, ROUND((ISNULL(cr.CurrentOdometerReading, 0) * @ConversionFactor), 0, 0)))+ ' ' + @Distance AS CurrentValues              
 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 rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId              
 INNER JOIN #tempLastReadings lr ON lr.VehicleId = v.VehicleId              
 WHERE mp.OrganizationId = @bigOrganizationID AND vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1               
 AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId)              
 AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR vp.VehicleId = @bigVehicleId)              
 AND (@bigVehicleTypeId IS NULL OR @bigVehicleTypeId='' OR v.VehicleTypeId = @bigVehicleTypeId)              
 AND (@bigPlanId IS NULL OR @bigPlanId='' OR vp.PlanId = @bigPlanId)              
 AND (@tiServiceType IS NULL OR @tiServiceType='' OR vm.ServiceType = @tiServiceType)              
 AND (@dtFromDate IS NULL OR vm.DueOnDate BETWEEN @dtFromDate AND @dtToDate)              
 AND NearingPercentage >= pd.Notification1 AND IsNearing = 1              
   
   
 SELECT distinct(t.ServiceDetailsId), t.VehiclePlanId, t.PlanDetailsId, t.VehicleId, v.VehicleDescription AS VehicleName, t.PlanName,             
 CASE WHEN t.ServiceType = 0 THEN 'Engine Hours'            
   WHEN t.ServiceType = 1 THEN 'Odometer'            
   WHEN t.ServiceType = 2 THEN 'Time Based' ELSE 'Concrete Mix Hours' END AS ServiceType,            
 t.Frequency,REPLACE(t.ServicesPlanned,',', ', ') as ServicesPlanned, 1 AS ServiceCategoryId, t.Nearing, t.IsRecurring, t.ServicesDone, @Distance AS DistanceUnits,              
     CONVERT(VARCHAR(35), CASE WHEN t.ServiceType = 1 THEN CONVERT(VARCHAR(35),(t.DueOn* @ConversionFactor))  
     WHEN t.ServiceType = 0 or t.ServiceType = 3 THEN (Convert(varchar(30),(t.DueOn)))ELSE t.DueOn END) AS DueOn,              
     CONVERT(BIGINT, CASE WHEN t.ServiceType = 1 THEN (t.CurrentReadings * @ConversionFactor) ELSE t.CurrentReadings END) AS CurrentReadings,               
     CASE WHEN t.ServiceType = 0  THEN CONVERT(Varchar(10), t.CurrentReadings - t.DueOn) + ' hrs'              
    WHEN t.ServiceType = 3  THEN CONVERT(Varchar(10), t.CurrentReadings -  t.DueOn)  + ' hrs'           
          WHEN t.ServiceType = 1 THEN CONVERT(Varchar(10),CONVERT(BIGINT, ((t.CurrentReadings - t.DueOn) * @ConversionFactor))) + ' ' + @Distance              
          WHEN t.ServiceType = 2 THEN (CASE WHEN DATEDIFF(D, GETUTCDATE(), t.DueOn) >= 0               
                  THEN (CASE WHEN DATEDIFF(D, GETUTCDATE(), t.DueOn) / 365 > 0 THEN CONVERT(Varchar(10), (DATEDIFF(D, GETUTCDATE(), t.DueOn) / 365)) + ' yrs left'              
              WHEN DATEDIFF(D, GETUTCDATE(), t.DueOn) / 31 > 0 THEN CONVERT(Varchar(6), (DATEDIFF(D, GETUTCDATE(), t.DueOn) / 31)) + ' months left'              
              ELSE  CONVERT(Varchar(6), DATEDIFF(D, GETUTCDATE(), t.DueOn)) + ' days left' END              
                       )            
                  ELSE (CASE WHEN DATEDIFF(D, t.DueOn, GETUTCDATE()) / 365 > 0 THEN CONVERT(Varchar(10), (DATEDIFF(D, t.DueOn, GETUTCDATE()) / 365)) + ' yrs overdue'              
              WHEN DATEDIFF(D, t.DueOn, GETUTCDATE()) / 31 > 0 THEN CONVERT(Varchar(6), (DATEDIFF(D, t.DueOn, GETUTCDATE()) / 31)) + ' months overdue'              
              ELSE  CONVERT(Varchar(10), DATEDIFF(D, t.DueOn, GETUTCDATE())) + ' days overdue' END              
                       )               
                  END)               
          ELSE NULL END AS DueBy, pd.ServiceInterval,             
          --Convert(varchar,vm.RescheduledOn,@DefaultDateFormat)AS ReScheduledOn,            
         ISNULL(Convert(varchar,vm.RescheduledOn,@DefaultDateFormat), '-')AS ReScheduledOn,            
         vm.RescheduledOn AS ReScheduledOnSort, pd.PlanId,               
                      
          Convert(varchar,(CASE WHEN t.ServiceType = 2 THEN t.DueOn               
                WHEN t.ServiceType = 0 OR t.ServiceType = 1  OR t.ServiceType = 3 THEN (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETDATE()) ELSE GETDATE() END) END)              
          ELSE '' END),@DefaultDateFormat) AS ExpectedDueOnDate,              
          (CASE WHEN t.ServiceType = 2 THEN t.DueOn               
                WHEN t.ServiceType = 0 OR t.ServiceType = 1  OR t.ServiceType = 3 THEN (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETDATE()) ELSE GETDATE() END) END)              
          ELSE '' END) AS ExpectedDueOnDateSort,                
          CASE WHEN t.ServiceType = 2 THEN CONVERT(VARCHAR(10), DATEDIFF(D, t.DueOn, GETUTCDATE())) + ' days'              
               WHEN t.ServiceType = 0 OR t.ServiceType = 1 OR t.ServiceType = 3  THEN CONVERT(VARCHAR(10), DATEDIFF(D, (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETUTCDATE()) ELSE GETUTCDATE() END) END), GETUTCDATE())) + ' days'              
          ELSE NULL END AS OverdueBy, t.CurrentValues, Cast(Cast((vm.EngineHrsOnDue) AS FLOAT) / 3600 as Decimal(18,2)) as EngineHrsOnDue , CASE WHEN vm.OdometerReadingOnDue IS NULL THEN vm.OdometerReadingOnDue ELSE CONVERT(INT, ROUND((vm.OdometerReadingOnDue * @ConversionFactor), 0, 0)) END AS OdometerReadingOnDue,    
          (CASE WHEN EXISTS (SELECT msd.ServiceDetailsId FROM rvlfMaintenanceServiceDetails msd WHERE msd.ServiceDetailsId = t.ServiceDetailsId) THEN 0 ELSE 1 END) AS SkipStatus              
 FROM #temp t              
 INNER JOIN rvlfVehicleMaintenanceService vm ON vm.ServiceDetailsId = t.ServiceDetailsId              
 INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId               
 INNER JOIN rvlfVehicle v ON v.VehicleId = t.VehicleId              
 INNER JOIN #tempLastReadings lr ON lr.VehicleId = v.VehicleId              
 WHERE (@intNearingPercentage IS NULL OR @intNearingPercentage='' OR              
  (Nearing > @intNearingPercentage               
   AND Nearing <= (CASE WHEN @intNearingPercentage = 20 THEN 30              
          WHEN @intNearingPercentage = 30 THEN 40                        WHEN @intNearingPercentage = 40 THEN 50              
          WHEN @intNearingPercentage = 50 THEN 60              
          WHEN @intNearingPercentage = 60 THEN 70              
    WHEN @intNearingPercentage = 70 THEN 80              
    WHEN @intNearingPercentage = 80 THEN 90               
    WHEN @intNearingPercentage = 90 THEN 100              
    WHEN @intNearingPercentage = 100 THEN 125              
    WHEN @intNearingPercentage = 125 THEN 150              
    ELSE 100000 END))) AND (@tiServiceType IS NULL OR @tiServiceType='' OR t.ServiceType = @tiServiceType)              
    ORDER BY t.Nearing DESC              
                   
 DROP TABLE #temp              
    DROP TABLE #tempLastReadings              
                  
SET NOCOUNT OFF              
END 



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleNearingMaintenance_VXL]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create  PROCEDURE [dbo].[rvlf_sp_GetVehicleNearingMaintenance_VXL]                      
 @bigOrganizationID BIGINT = 0,                      
 @bigFleetId bigint = NULL ,          
 @bigVehicleId bigint = NULL,      
@bigPlanId bigint = NULL  ,                 
  @bigVehicleTypeId bigint = NULL,      
 @tiServiceType int = NULL ,                     
@intNearingPercentage int = NULL,      
 @dtFromDate datetime = NULL  ,                    
 @dtToDate datetime = NULL ,                    
 @bigQueryingUser bigint = NUll      
AS                      
/**************************************************************************************/                      
-- Name        : rvlf_sp_GetVehicleNearingMaintenance_VXL 276,null,Null,null,null,0, null, null, null,303                      
-- Description : To get the vehicles that were nearing to the maintenance                      
-- Author      : Kumuthini. L                      
-- Company     : Angler Technologies                      
-- History     : <<Date(dd-MON-yyyy)>> Initial Reason                      
--             : 19-Jun-2010  Kumuthini Created Intial Version                       
--             : 25-Jun-2010  Kumuthini  Included the User Preferences                      
--             : 07-Oct-2010  Jeyanthi   Included PlanId, ServiceType, Nearing Percentage and Duration Percentage                      
--             : 17-Aug-2011 Ranjith Date format included                  
--             : 10-Apr-2011 Selvakumar Service type include for Concrete Mixer                  
--      : 9-Oct-2013 Gopal new field Overduebynew,ReadingswhenDue included for export    
/**************************************************************************************/                      
BEGIN                      
SET NOCOUNT ON                 
 DECLARE @Distance varchar(20)                      
 DECLARE @ConversionFactor numeric (10,2) = 1.0                     
 DECLARE @DefaultDateFormat INT = 0                    
                      
    SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                      
     @Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END,                    
     @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                      
                       
 -- ****** Distance Travelled and Engine Hrs Calculation for last 2 weeks ******                      
 DECLARE @dtLastStartDate DateTime = CONVERT(DATETIME,CONVERT(Date, DATEADD(DD, -14 , GETDATE())))                      
    DECLARE @dtLastEndDate DateTime = CONVERT(DATETIME, CONVERT(Date, DATEADD(DD, -1 , GETDATE())))                      
                       
 -- Distance Travelled for Last 2 Weeks                      
     DECLARE @tblUtilizationBoxes TABLE                      
 (                      
  SlNo int identity(1,1), BoxID varchar(100), VehicleDescription varchar(250), VehicleName varchar(50),                      
  StartOdometer bigint,MaxOdometer bigint, SetOdometer bigint,EndOdometer bigint                      
 )                      
                      
 INSERT INTO @tblUtilizationBoxes (BoxID, VehicleName, VehicleDescription )                      
  SELECT va.BoxId, v.VehicleDescription as VehicleName, v.VehicleDescription                       
  FROM rvlfVehicle v                      
  INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId                      
  WHERE v.OrganizationId = @bigOrganizationID                      
                        
 DECLARE @dtOdometerSetDate DateTime=Null, @SetOdometer bigint=0                      
 DECLARE @MaxOdometer bigint=0,@StartOdometer bigint=0,@EndOdometer bigint=0                      
                   
    DECLARE @intCounter int                      
 SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes                       
 DECLARE @intBoxID varchar(100)=''                      
 WHILE @intCounter IS NOT NULL                      
  BEGIN                     
                         
   SET @dtOdometerSetDate=NULL;SET @SetOdometer=0; SET @MaxOdometer=0;SET @StartOdometer=0; SET @EndOdometer=0;                      
                  
   SELECT @intBoxID = BoxID FROM @tblUtilizationBoxes WHERE slno = @intCounter                      
                         
   SELECT TOP 1 @dtOdometerSetDate=SentDateTime, @SetOdometer=CustomProp FROM rvlfMsgOutHst                     
      WHERE BoxCmdOutTypeId =14 and BoxId=@intBoxID and SentDateTime between               
      @dtLastStartDate and @dtLastEndDate order by SentDateTime desc                      
                          
                         
   IF @dtOdometerSetDate IS NOT NULL                      
    BEGIN                      
     SELECT @MaxOdometer=(SELECT TOP 1 Max(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,                      
      (CHARINDEX(';',CustomProp,                      
       CHARINDEX('Odometer=',CustomProp,1))) -                      
 (CHARINDEX('Odometer=',CustomProp,1)+9))) FROM rvlfMsgInHst                       
      WHERE                       
       BoxId = @intBoxID                      
       AND OriginDateTime between @dtLastStartDate and @dtOdometerSetDate                       
       AND CustomProp LIKE '%Odometer%'  and BoxMsgInTypeId <> 77)                            
                            
    END                      
                         
   SET @StartOdometer=(SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,                      
       (CHARINDEX(';',CustomProp,                      
       CHARINDEX('Odometer=',CustomProp,1))) -                      
       (CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst                       
      WHERE                       
       BoxId = @intBoxID                      
       AND OriginDateTime between @dtLastStartDate and @dtLastEndDate                       
       AND CustomProp LIKE '%Odometer%'  and BoxMsgInTypeId <> 77 and Odometer > 0                    
      ORDER BY OriginDateTime ASC)                            
                           
   SET @EndOdometer = (SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,                      
       (CHARINDEX(';',CustomProp,                      
       CHARINDEX('Odometer=',CustomProp,1))) -                      
       (CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst                       
      WHERE                       
       BoxId = @intBoxID                      
       AND OriginDateTime between @dtLastStartDate and @dtLastEndDate                       
       AND CustomProp LIKE '%Odometer%'   and BoxMsgInTypeId <> 77   and Odometer > 0                 
      ORDER BY OriginDateTime DESC)                       
                            
                         
   UPDATE @tblUtilizationBoxes SET StartOdometer=@StartOdometer,EndOdometer=@EndOdometer,                      
    SetOdometer =@SetOdometer,MaxOdometer=@MaxOdometer  Where BoxID=@intBoxID                        
                         
   SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes WHERE SlNo < @intCounter                      
  END                      
                        
     CREATE TABLE #tempDistance(BoxId varchar(100), DistanceTravelled bigint)                       
                       
  INSERT INTO #tempDistance(BoxId, DistanceTravelled)                      
  SELECT BoxID, ISNULL(CASE WHEN SetOdometer = 0 THEN CEILING((EndOdometer - StartOdometer)* @ConversionFactor)                       
  ELSE CEILING(((MaxOdometer - StartOdometer) + (EndOdometer - SetOdometer)) * @ConversionFactor) END, 0) AS DistanceTravelled                      
   FROM @tblUtilizationBoxes                       
  ORDER BY (EndOdometer - StartOdometer) DESC                      
                        
  -- Engine Hours for Last 2 Weeks                
                       
  CREATE TABLE #tempEngineHrs(BoxId int, EngineHrs bigint)                       
                       
  --INSERT INTO #tempEngineHrs(BoxId, EngineHrs)                     
  --SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,                      
  --    CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -                       
  --    ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'                      
  --FROM rvlfMsgInHst h                
  --INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                      
  --INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                      
  --WHERE                      
  -- v.OrganizationId = @bigOrganizationID                      
  -- AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate                       
  -- AND h.BoxMsgInTypeId = 3                      
  --GROUP BY h.BoxId                      
                     
 if(@tiServiceType=3)              
 BEGIN                   
 INSERT INTO #tempEngineHrs(BoxId, EngineHrs)              
 SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,                      
  CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -              
  ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'                      
 FROM rvlfMsgInHst h                       
 INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                      
 INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                      
 WHERE                      
  v.OrganizationId = @bigOrganizationID                      
  AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate  and  CustomProp like '%Sensor_NUM=2;%' AND CustomProp like '%SENSOR_DURATION=%'            
  AND h.BoxMsgInTypeId = 3 AND h.BoxMsgInTypeId <> 77                    
 GROUP BY h.BoxId                
 END              
 ELSE              
 BEGIN              
            
 INSERT INTO #tempEngineHrs(BoxId, EngineHrs)            
                 
 SELECT h.BoxId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,                      
  CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -                       
  ( CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) * 60 AS 'EngineHrs'                      
 FROM rvlfMsgInHst h                       
 INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                      
 INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                      
 WHERE                      
  v.OrganizationId = @bigOrganizationID                      
  AND h.OriginDateTime between @dtLastStartDate and @dtLastEndDate  and  CustomProp like '%Sensor_NUM=3;%' AND CustomProp like '%SENSOR_DURATION=%'                     
  AND h.BoxMsgInTypeId = 3    AND h.BoxMsgInTypeId <> 77                     
 GROUP BY h.BoxId               
          
          
 END                      
                 
  CREATE TABLE #tempLastReadings(VehicleId bigint, DistanceTravelled bigint, EngineHrs bigint)                      
                         
  INSERT INTO #tempLastReadings(VehicleId, DistanceTravelled, EngineHrs)                       
  SELECT va.VehicleId, d.DistanceTravelled, ISNULL(e.EngineHrs, 0) FROM #tempDistance d                      
  LEFT OUTER JOIN #tempEngineHrs e ON e.BoxId = d.BoxId                      
  INNER JOIN rvlfVehicleAssignment va ON d.BoxId = va.BoxId           
                        
  --select t.*, rvlfVehicleAssignment.VehicleId from #tempDistance t                      
  --inner join rvlfVehicleAssignment on t.BoxId = rvlfVehicleAssignment.BoxId                      
                        
  DROP TABLE #tempEngineHrs                      
  DROP TABLE #tempDistance                      
                        
 -- ****** Get Nearing Maintenance ******                      
 CREATE TABLE #temp(ServiceDetailsId bigint, VehiclePlanId bigint, PlanDetailsId bigint, VehicleId bigint,                       
 PlanName varchar(100), ServiceType tinyint, Frequency tinyint, ServicesPlanned varchar(2000),                       
 ServiceCategoryId bigint, DueOn varchar(35), CurrentReadings FLOAT, Nearing int, IsRecurring bit,                       
 ServicesDone varchar(2000), ExpectedDueOn bigint, CurrentValues Varchar(30))                      
                       
 INSERT INTO #temp(ServiceDetailsId, VehiclePlanId, PlanDetailsId, VehicleId, PlanName, ServiceType, Frequency,                       
 DueOn, CurrentReadings, Nearing, IsRecurring, ServicesDone, ExpectedDueOn, CurrentValues)                      
    SELECT vm.ServiceDetailsId, vm.VehiclePlanId, vm.PlanDetailsId, vp.VehicleId, mp.PlanName, vm.ServiceType, vm.Frequency,                       
 CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 1  OR vm.ServiceType = 3 THEN CONVERT(VARCHAR(35), vm.DueOn) ELSE CONVERT(VARCHAR(10), vm.DueOnDate, 101) END AS DueOn,                      
 CASE WHEN vm.ServiceType = 0  OR vm.ServiceType = 3 THEN  CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0))AS FLOAT)/(3600)AS Decimal(18,2))                      
   WHEN vm.ServiceType = 1 THEN cr.CurrentOdometerReading                       
   WHEN vm.ServiceType = 2 THEN (                      
               CASE WHEN vm.Frequency = 0 THEN DATEDIFF(D, vm.StartDate, GETUTCDATE())                       
                    WHEN vm.Frequency = 1 THEN DATEDIFF(M, vm.StartDate, GETUTCDATE())                      
                    WHEN vm.Frequency = 2 THEN DATEDIFF(YEAR, vm.StartDate, GETUTCDATE()) END                      
               )                      
 END AS CurrentReadings, NearingPercentage AS Nearing, mp.RecurringService, dbo.rvlf_fn_GetMaintenanceServices(1, null, vm.ServiceDetailsId) AS ServicesDone,                      
(CASE WHEN vm.ServiceType = 2 THEN 0                      
       WHEN vm.ServiceType = 0  OR vm.ServiceType = 3 THEN (CASE WHEN lr.EngineHrs = 0 THEN 0 ELSE ISNULL(CAST(CAST((14 * (vm.DueOn - (cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0))) / lr.EngineHrs) as FLOAT)/3600 As DEcimal(18,2)),0) END)           
        
                 
       WHEN vm.ServiceType = 1 THEN (CASE WHEN lr.DistanceTravelled = 0 THEN 0 ELSE ((14 * (vm.DueOn - cr.CurrentOdometerReading)) / lr.DistanceTravelled) END)                       
       ELSE '' END)  AS ExpectedDueOn,                      
 CONVERT(VARCHAR(30), COnvert(varchar(30),ISNULL(CAST(CAST(cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0) AS FLOAT)/3600 AS DECIMAL(18,2)),0)))  + ' hrs; ' + CONVERT(VARCHAR(10), CONVERT(INT, ROUND((ISNULL(cr.CurrentOdometerReading, 0) * @ConversionFactor), 0, 0)))+ ' ' + @Distance AS CurrentValues                      
 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 rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                      
 INNER JOIN #tempLastReadings lr ON lr.VehicleId = v.VehicleId                      
 WHERE mp.OrganizationId = @bigOrganizationID AND vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1                       
 AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId)                      
 AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR vp.VehicleId = @bigVehicleId)                      
 AND (@bigVehicleTypeId IS NULL OR @bigVehicleTypeId='' OR v.VehicleTypeId = @bigVehicleTypeId)                      
 AND (@bigPlanId IS NULL OR @bigPlanId='' OR vp.PlanId = @bigPlanId)                      
 AND (@tiServiceType IS NULL OR @tiServiceType='' OR vm.ServiceType = @tiServiceType)                      
 AND (@dtFromDate IS NULL OR vm.DueOnDate BETWEEN @dtFromDate AND @dtToDate)                      
 AND NearingPercentage >= pd.Notification1 AND IsNearing = 1                      
           
           
 Select *,case when (Frequency=3 OR Frequency =4) then OverdueBy + '; ' + DueBy else OverdueBy end as Overduebynew from ( --gopal                 
 SELECT distinct(t.ServiceDetailsId), t.VehiclePlanId, t.PlanDetailsId, t.VehicleId, v.VehicleDescription AS VehicleName, t.PlanName,                     
 CASE WHEN t.ServiceType = 0 THEN 'Engine Hours'                    
   WHEN t.ServiceType = 1 THEN 'Odometer'                    
   WHEN t.ServiceType = 2 THEN 'Time Based' ELSE 'Concrete Mix Hours' END AS ServiceType,                    
 t.Frequency,REPLACE(t.ServicesPlanned,',', ', ') as ServicesPlanned, 1 AS ServiceCategoryId, t.Nearing, t.IsRecurring, t.ServicesDone, @Distance AS DistanceUnits,                      
     CONVERT(VARCHAR(35), CASE WHEN t.ServiceType = 1 THEN CONVERT(VARCHAR(35),(t.DueOn* @ConversionFactor))          
     WHEN t.ServiceType = 0 or t.ServiceType = 3 THEN (Convert(varchar(30),(t.DueOn)))ELSE t.DueOn END) AS DueOn,                      
     CONVERT(BIGINT, CASE WHEN t.ServiceType = 1 THEN (t.CurrentReadings * @ConversionFactor) ELSE t.CurrentReadings END) AS CurrentReadings,         
     CASE WHEN t.ServiceType = 0  THEN CONVERT(Varchar(10), t.CurrentReadings - t.DueOn) + ' hrs'                      
    WHEN t.ServiceType = 3  THEN CONVERT(Varchar(10), t.CurrentReadings -  t.DueOn)  + ' hrs'                   
          WHEN t.ServiceType = 1 THEN CONVERT(Varchar(10),CONVERT(BIGINT, ((t.CurrentReadings - t.DueOn) * @ConversionFactor))) + ' ' + @Distance                      
          WHEN t.ServiceType = 2 THEN (CASE WHEN DATEDIFF(D, GETUTCDATE(), t.DueOn) >= 0                       
                  THEN (CASE WHEN DATEDIFF(D, GETUTCDATE(), t.DueOn) / 365 > 0 THEN CONVERT(Varchar(10), (DATEDIFF(D, GETUTCDATE(), t.DueOn) / 365)) + ' yrs left'                      
              WHEN DATEDIFF(D, GETUTCDATE(), t.DueOn) / 31 > 0 THEN CONVERT(Varchar(6), (DATEDIFF(D, GETUTCDATE(), t.DueOn) / 31)) + ' months left'                      
              ELSE  CONVERT(Varchar(6), DATEDIFF(D, GETUTCDATE(), t.DueOn)) + ' days left' END                      
                       )                    
                  ELSE (CASE WHEN DATEDIFF(D, t.DueOn, GETUTCDATE()) / 365 > 0 THEN CONVERT(Varchar(10), (DATEDIFF(D, t.DueOn, GETUTCDATE()) / 365)) + ' yrs overdue'                      
              WHEN DATEDIFF(D, t.DueOn, GETUTCDATE()) / 31 > 0 THEN CONVERT(Varchar(6), (DATEDIFF(D, t.DueOn, GETUTCDATE()) / 31)) + ' months overdue'                      
              ELSE  CONVERT(Varchar(10), DATEDIFF(D, t.DueOn, GETUTCDATE())) + ' days overdue' END                      
                       )                       
                  END)                       
          ELSE NULL END AS DueBy, pd.ServiceInterval,                     
          --Convert(varchar,vm.RescheduledOn,@DefaultDateFormat)AS ReScheduledOn,                    
         ISNULL(Convert(varchar,vm.RescheduledOn,@DefaultDateFormat), '-')AS ReScheduledOn,                    
         vm.RescheduledOn AS ReScheduledOnSort, pd.PlanId,                       
                              
          Convert(varchar,(CASE WHEN t.ServiceType = 2 THEN t.DueOn                       
                WHEN t.ServiceType = 0 OR t.ServiceType = 1  OR t.ServiceType = 3 THEN (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETDATE()) ELSE    

 
                GETDATE() END) END)                      
          ELSE '' END),@DefaultDateFormat) AS ExpectedDueOnDate,
                                
          (CASE WHEN t.ServiceType = 2 THEN t.DueOn                       
                WHEN t.ServiceType = 0 OR t.ServiceType = 1  OR t.ServiceType = 3 THEN (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETDATE()) ELSE GETDATE() END) END)                      
          ELSE '' END) AS ExpectedDueOnDateSort, 
                                 
          CASE WHEN t.ServiceType = 2 THEN CONVERT(VARCHAR(10), DATEDIFF(D, t.DueOn, GETUTCDATE())) + ' days'                      
               WHEN t.ServiceType = 0 OR t.ServiceType = 1 OR t.ServiceType = 3  THEN CONVERT(VARCHAR(10), DATEDIFF(D, (CASE WHEN t.Nearing >= 100 AND vm.OverdueDate IS NOT NULL THEN vm.OverdueDate ELSE (CASE WHEN t.ExpectedDueOn > 0 THEN DATEADD(DD, t.ExpectedDueOn, GETUTCDATE()) ELSE GETUTCDATE() END) END), GETUTCDATE())) + ' days'                      
          ELSE NULL END AS OverdueBy, t.CurrentValues, 
          Cast(Cast((vm.EngineHrsOnDue) AS FLOAT) / 3600 as Decimal(18,2)) as EngineHrsOnDue ,
          
           CASE WHEN vm.OdometerReadingOnDue IS NULL THEN vm.OdometerReadingOnDue ELSE CONVERT(INT, ROUND((vm.OdometerReadingOnDue * @ConversionFactor), 0, 0)) END AS OdometerReadingOnDue,  
          
          (CASE WHEN EXISTS (SELECT msd.ServiceDetailsId FROM rvlfMaintenanceServiceDetails msd WHERE msd.ServiceDetailsId = t.ServiceDetailsId) THEN 0 ELSE 1 END) AS SkipStatus, 
          
           
          Case when  t.Frequency=3 then CAST(( CONVERT(VARCHAR(35), CASE WHEN t.ServiceType = 1 THEN CONVERT(VARCHAR(35),CONVERT(BIGINT,(t.DueOn * @ConversionFactor))) ELSE t.DueOn END)) as varchar(10))+' hrs; '+  cast((ISNULL(CASE WHEN vm.OdometerReadingOnDue IS NULL THEN vm.OdometerReadingOnDue ELSE CONVERT(INT, ROUND((vm.OdometerReadingOnDue * @ConversionFactor), 0, 0)) END,0)) as varchar(10))      + @Distance          
   when  t.Frequency =4 then CAST((CAST(ISNULL(Cast(Cast((vm.EngineHrsOnDue) AS FLOAT) / 3600 as Decimal(18,2)),0) as varchar(10)) + ' hrs; ') as varchar(10))+ CAST((CONVERT(VARCHAR(35), CASE WHEN t.ServiceType = 1 THEN CONVERT(VARCHAR(35),CONVERT(BIGINT,(t.DueOn * @ConversionFactor))) ELSE t.DueOn END)) as varchar(10)) + @Distance      
  else      
    CAST(ISNULL(Cast(Cast((vm.EngineHrsOnDue) AS FLOAT) / 3600 as Decimal(18,2)),0) as varchar(10)) + ' hrs; '+CAST((CASE WHEN vm.OdometerReadingOnDue IS NULL THEN vm.OdometerReadingOnDue ELSE CONVERT(INT, ROUND((vm.OdometerReadingOnDue * @ConversionFactor),0, 0)) END) as varchar(10))  +@Distance      
End as ReadingswhenDue                      
 FROM #temp t                      
 INNER JOIN rvlfVehicleMaintenanceService vm ON vm.ServiceDetailsId = t.ServiceDetailsId                      
 INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId                       
 INNER JOIN rvlfVehicle v ON v.VehicleId = t.VehicleId                      
 INNER JOIN #tempLastReadings lr ON lr.VehicleId = v.VehicleId                      
 WHERE (@intNearingPercentage IS NULL OR @intNearingPercentage='' OR                      
  (Nearing > @intNearingPercentage                       
   AND Nearing <= (CASE WHEN @intNearingPercentage = 20 THEN 30                      
          WHEN @intNearingPercentage = 30 THEN 40                      WHEN @intNearingPercentage = 40 THEN 50                      
          WHEN @intNearingPercentage = 50 THEN 60                      
          WHEN @intNearingPercentage = 60 THEN 70                      
    WHEN @intNearingPercentage = 70 THEN 80                      
    WHEN @intNearingPercentage = 80 THEN 90                       
    WHEN @intNearingPercentage = 90 THEN 100                      
    WHEN @intNearingPercentage = 100 THEN 125                      
    WHEN @intNearingPercentage = 125 THEN 150                      
    ELSE 100000 END))) AND (@tiServiceType IS NULL OR @tiServiceType='' OR t.ServiceType = @tiServiceType)                      
     ) as a ORDER BY Nearing DESC                      
                           
 DROP TABLE #temp                      
    DROP TABLE #tempLastReadings                      
                          
SET NOCOUNT OFF                      
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehiclePlanAssignments]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetVehiclePlanAssignments]                
 @chrType char,                
 @bigOrganizationID bigint,                
 @bigFleetId bigint = NULL,                
 @bigVehicleId bigint = NULL,                
 @bigPlanId bigint = NULL,                
 @tiActiveStatus tinyint = NULL,                
 @tiPlanType tinyint = NULL,                
 @bigQueryingUser bigint = 0
AS                
/**************************************************************************************/                
-- Name  : rvlf_sp_GetVehiclePlanAssignments 'U',6,8,null,4,null,null,18              
-- Description : To get the vehicle assignment details                
-- Author  : Kumuthini. L                
-- Company  : Angler Technologies                
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                
--          : 10-Jun-2010  Created Intial Version                 
--          : 21-Sep-2010     Modified the Assigned Vehicles                 
--          : 16-Aug-2011 Ranjith Date format included   
--   : 9-Oct-2011 Gopal included case TimeBasedStartValue             
/**************************************************************************************/                
BEGIN                
SET NOCOUNT ON                 
                  
 DECLARE @ConversionFactor numeric (10,2) = 1.0                
 DECLARE @HoursToBeAdded INT = 0                
 DECLARE @MinsToBeAdded INT = 0                
 DECLARE @DefaultDateFormat INT = 0    
 	DECLARE @Distance varchar(20)                   
                    
    SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                
           @HoursToBeAdded = tz.HoursToBeAdded, @MinsToBeAdded = tz.MinToBeAdded ,              
           @DefaultDateFormat=(case when  ISNULL(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end),
		   @Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END                   
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz                
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser   
	
	
--declare @CheckUser int =null,@lastname nvarchar(100),@CheckUGid int 
--select @CheckUGid=UserGroupId from rvlfUserGroupAssignment where UserId=@bigQueryingUser
--select @lastname=LastName from rvlfUser where UserId=@UserID
--if((@lastname like '%VXL%' or @lastname like '%trinetra%') or @CheckUGid=1 or @bigOrganizationID=6)
--begin
--	set @CheckUser=null
--end
--else
--begin
--	set @CheckUser=1
--end
	declare @tblFleetuser table(FleetID bigint)
	if(@bigFleetId is null or @bigFleetId=0)
		begin
			insert into @tblFleetuser 
			select FleetId from rvlfFleetUsers where UserId=@bigQueryingUser
		end
	else
		begin
			insert into @tblFleetuser values (@bigFleetId)
		end
                 
 IF(@chrType = 'S') -- Select All Vehicle Plan Assignments                
 BEGIN    
 
           
                  
  SELECT distinct vp.VehiclePlanId, vp.VehicleId, v.VehicleDescription, mp.PlanId, mp.PlanName, mp.RecurringService AS IsRecurring, vp.IsActive,                 
  CASE WHEN vp.EngineHrsStartValue IS NULL THEN 'N/A' ELSE CONVERT(Varchar(15), vp.EngineHrsStartValue) END AS EngineHrsStartValue,                
  CASE WHEN vp.OdometerReadingStartValue IS NULL THEN 'N/A' ELSE CONVERT(Varchar(15), vp.OdometerReadingStartValue) END AS OdometerReadingStartValue,                
  --Convert(varchar,vp.TimeBasedStartValue,@DefaultDateFormat) as TimeBasedStartValue,  
  CASE WHEN vp.TimeBasedStartValue IS NULL THEN 'N/A' ELSE  Convert(varchar,vp.TimeBasedStartValue,@DefaultDateFormat) END as TimeBasedStartValue, --gopal  
  vp.TimeBasedStartValue as TimeBasedStartValueSort, u.DisplayName, DATEADD(n, @MinsToBeAdded, DATEADD(hh, @HoursToBeAdded, vp.AssignedDateTime)) AS AssignedDateTime          
    
      
        
  FROM rvlfVehiclePlanAssignment vp                
  INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId                
  INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId                
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                
  INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId                
  INNER JOIN rvlfUser u ON u.UserId = vp.AssignedBy 
  INNER JOIN rvlfMAKDevices MD ON MD.VehicleId= vp.VehicleId              
  WHERE v.OrganizationId = @bigOrganizationID AND f.FleetId in (Select FleetID from @tblFleetuser) AND ((@bigVehicleId IS NULL) or (@bigVehicleId=0) OR v.VehicleId = @bigVehicleId)                 
  AND (@bigPlanId IS NULL OR vp.PlanId = @bigPlanId) AND vp.AssignedStatus = 1                 
  AND (@tiActiveStatus = 2 OR vp.IsActive = @tiActiveStatus) AND (@tiPlanType = 2 OR mp.RecurringService = @tiPlanType)  
                  
                
    END                
    ELSE IF (@chrType = 'A') -- Get Assigned Vehicles                
    BEGIN                 
    
  -- Select the vehicles assigned to the Maintenance Plan                
  SELECT DISTINCT(v.VehicleId), v.VehicleDescription, vp.IsActive, vp.VehiclePlanId,                
  CAST(CAST((isnull(cr.CurrentEngineHours,0) + ISNULL(v.OpeningEngineHours* 3600, 0))as FLoat )/ 3600 as Decimal(18,2)) AS CurrentEngineHours,(SELECT DueOn FROM rvlfVehicleMaintenanceService ms                
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = ms.PlanDetailsId              
   WHERE mpd.PlanId = @bigPlanId and ms.VehiclePlanId = vp.VehiclePlanId and ms.Status = 0 and(ms.ServiceType = 0 OR ms.ServiceType =3)) AS EngineHrsDueOn,                 
  CONVERT(BIGINT,(cr.CurrentOdometerReading * @ConversionFactor )) AS CurrentOdometerReading,  -- * @ConversionFactor
    CONVERT(BIGINT,((SELECT ISNULL(DueOn, 0) FROM rvlfVehicleMaintenanceService ms                
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = ms.PlanDetailsId                
   WHERE mpd.PlanId = @bigPlanId and ms.VehiclePlanId = vp.VehiclePlanId and ms.Status = 0 and ms.ServiceType = 1)* @ConversionFactor)) AS OdometerReadingDueOn,                
  Convert(varchar,GETDATE(),@DefaultDateFormat) AS CurrentDate,GETDATE() AS CurrentDateSort, Convert(varchar,(SELECT DueOnDate FROM rvlfVehicleMaintenanceService ms                
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = ms.PlanDetailsId                
   WHERE mpd.PlanId = @bigPlanId and ms.VehiclePlanId = vp.VehiclePlanId and ms.Status = 0 and ms.ServiceType = 2),@DefaultDateFormat) AS DueOnDate,                 
   (SELECT DueOnDate FROM rvlfVehicleMaintenanceService ms                
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = ms.PlanDetailsId                
   WHERE mpd.PlanId = @bigPlanId and ms.VehiclePlanId = vp.VehiclePlanId and ms.Status = 0 and ms.ServiceType = 2) AS DueOnDateSort,              
                   
  CASE WHEN EXISTS(SELECT top 1(vm.VehiclePlanId) FROM rvlfVehicleMaintenanceService vm                 
       WHERE vm.VehiclePlanId = vp.VehiclePlanId AND vm.Status = 0 AND                
       (vm.IsNotification1Sent = 1 OR vm.IsNotification2Sent = 1 OR vm.IsNotification1Sent = 1)                
       )                
  THEN 1 ELSE 0 END AssignedStatus,(cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0))  AS CurrentValues           
  FROM rvlfVehicle v                 
  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehicleId = v.VehicleId         
  inner join  rvlfVehicleMaintenanceService vm  on vm.VehiclePlanId = vp.VehiclePlanId              
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                 
  INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = v.VehicleId                
  WHERE (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID)                
   AND vp.PlanId = @bigPlanId AND fv.FleetId in (Select FleetID from @tblFleetuser) AND vp.AssignedStatus = 1                
  ORDER BY VehicleDescription ASC                
                 
    END                
    ELSE IF (@chrType = 'U') -- Get Unassigned Vehicles                
    BEGIN                
                    
        -- Select all the vehicles from the Vehicle Information which is not present in Vehicle Maintenance Plan Assignment                
  SELECT DISTINCT(v.VehicleId), v.VehicleDescription, 'True' AS 'IsActive',                 
  CAST(CAST((isnull(cr.CurrentEngineHours,0) + ISNULL(v.OpeningEngineHours  * 3600, 0)) as Float)/ 3600 as DEcimal(18,2)) AS 'EngineHrsOpeningValue', NULL AS 'EngineHrsSIValue',                
  --ISNULL(cr.CurrentOdometerReading, 0) AS 'OdometerOpeningValue', 
   (case When cr.CurrentOdometerReading >0 and cr.CurrentOdometerReading is not null then CONVERT(BIGINT,(cr.CurrentOdometerReading * @ConversionFactor )) 
 else (Select MAX(isnull(Odometer,0 * @ConversionFactor)) from rvlfMsgInHst h inner join rvlfVehicleAssignment va on va.BoxId =h.BoxId
 where va.VehicleId = v.VehicleId
 )
 end) as 'OdometerOpeningValue',   
  NULL AS 'OdometerSIValue',                 
  '1/1/9000' AS 'TimeBasedSIValue' ,  
  CONVERT(BIGINT,(cr.CurrentOdometerReading * @ConversionFactor)) AS ConvertedCurrentOdometerReading,  
   ISNULL(cr.CurrentOdometerReading, 0) AS 'OdometerOpeningValueDefaultKM',
    (cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0))  AS CurrentValues                   
  FROM rvlfVehicle v                
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId 
           
  LEFT OUTER JOIN rvlfVehicleCurrentReadings cr ON v.VehicleId = cr.VehicleId                  
  WHERE (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID)                
   AND fv.FleetId in (Select FleetID from @tblFleetuser) AND v.VehicleId NOT IN                
      (SELECT vp.VehicleId FROM rvlfVehiclePlanAssignment vp WHERE PlanId = @bigPlanId AND vp.AssignedStatus = 1)                
      ORDER BY VehicleDescription ASC                   
                    
    END                
                    
SET NOCOUNT OFF                
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehiclePlanAssignments_Test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetVehiclePlanAssignments_Test]          
 @chrType char,          
 @bigOrganizationID bigint,          
 @bigFleetId bigint = NULL,          
 @bigVehicleId bigint = NULL,          
 @bigPlanId bigint = NULL,          
 @tiActiveStatus tinyint = NULL,          
 @tiPlanType tinyint = NULL,          
 @bigQueryingUser bigint = 0          
AS          
/**************************************************************************************/          
-- Name  : rvlf_sp_GetVehiclePlanAssignments_Test 'U', 6, 223, null, null, null,87,303        
-- Description : To get the vehicle assignment details          
-- Author  : Kumuthini. L          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--          : 10-Jun-2010  Created Intial Version           
--          : 21-Sep-2010     Modified the Assigned Vehicles           
--          : 16-Aug-2011 Ranjith Date format included        
/**************************************************************************************/          
BEGIN          
SET NOCOUNT ON           
            
 DECLARE @ConversionFactor numeric (10,2) = 1.0          
 DECLARE @HoursToBeAdded INT = 0          
 DECLARE @MinsToBeAdded INT = 0          
 DECLARE @DefaultDateFormat INT = 0        
              
    SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,          
           @HoursToBeAdded = tz.HoursToBeAdded, @MinsToBeAdded = tz.MinToBeAdded ,        
           @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          
           
 IF(@chrType = 'S') -- Select All Vehicle Plan Assignments          
 BEGIN           
            
  SELECT vp.VehiclePlanId, vp.VehicleId, v.VehicleDescription, mp.PlanId, mp.PlanName, mp.RecurringService AS IsRecurring, vp.IsActive,           
  CASE WHEN vp.EngineHrsStartValue IS NULL THEN 'N/A' ELSE CONVERT(Varchar(15), CAST(CAST((vp.EngineHrsStartValue)as FLOAT)/3600 as DEcimal(18,2))) END AS EngineHrsStartValue,          
  CASE WHEN vp.OdometerReadingStartValue IS NULL THEN 'N/A' ELSE CONVERT(Varchar(15), vp.OdometerReadingStartValue) END AS OdometerReadingStartValue,          
  Convert(varchar,vp.TimeBasedStartValue,@DefaultDateFormat) as TimeBasedStartValue,vp.TimeBasedStartValue as TimeBasedStartValueSort, u.DisplayName, DATEADD(n, @MinsToBeAdded, DATEADD(hh, @HoursToBeAdded, vp.AssignedDateTime)) AS AssignedDateTime        
  
  FROM rvlfVehiclePlanAssignment vp          
  INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId          
  INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId          
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId          
  INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId          
  INNER JOIN rvlfUser u ON u.UserId = vp.AssignedBy          
  WHERE v.OrganizationId = @bigOrganizationID AND (@bigFleetId IS NULL OR f.FleetId = @bigFleetId) AND (@bigVehicleId IS NULL OR v.VehicleId = @bigVehicleId)           
  AND (@bigPlanId IS NULL OR vp.PlanId = @bigPlanId) AND vp.AssignedStatus = 1           
  AND (@tiActiveStatus = 2 OR vp.IsActive = @tiActiveStatus) AND (@tiPlanType = 2 OR mp.RecurringService = @tiPlanType)           
          
    END          
    ELSE IF (@chrType = 'A') -- Get Assigned Vehicles          
    BEGIN           
              
  -- Select the vehicles assigned to the Maintenance Plan          
  SELECT DISTINCT(v.VehicleId), v.VehicleDescription, vp.IsActive, vp.VehiclePlanId,          
  CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours* 60, 0))as FLoat )/ 3600 as Decimal(18,2)) AS CurrentEngineHours,(SELECT ISNULL((CAST(CAST((DueOn) as Float)/3600 as Decimal(18,2))), 0) FROM rvlfVehicleMaintenanceService ms          
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = ms.PlanDetailsId          
   WHERE mpd.PlanId = @bigPlanId and ms.VehiclePlanId = vp.VehiclePlanId and ms.Status = 0 and(ms.ServiceType = 0 OR ms.ServiceType =3)) AS EngineHrsDueOn,           
  CONVERT(BIGINT,(cr.CurrentOdometerReading * @ConversionFactor)) AS CurrentOdometerReading,      
    CONVERT(BIGINT,((SELECT ISNULL(DueOn, 0) FROM rvlfVehicleMaintenanceService ms          
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = ms.PlanDetailsId          
   WHERE mpd.PlanId = @bigPlanId and ms.VehiclePlanId = vp.VehiclePlanId and ms.Status = 0 and ms.ServiceType = 1)* @ConversionFactor)) AS OdometerReadingDueOn,          
  Convert(varchar,GETDATE(),@DefaultDateFormat) AS CurrentDate,GETDATE() AS CurrentDateSort, Convert(varchar,(SELECT DueOnDate FROM rvlfVehicleMaintenanceService ms          
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = ms.PlanDetailsId          
   WHERE mpd.PlanId = @bigPlanId and ms.VehiclePlanId = vp.VehiclePlanId and ms.Status = 0 and ms.ServiceType = 2),@DefaultDateFormat) AS DueOnDate,           
   (SELECT DueOnDate FROM rvlfVehicleMaintenanceService ms          
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = ms.PlanDetailsId          
   WHERE mpd.PlanId = @bigPlanId and ms.VehiclePlanId = vp.VehiclePlanId and ms.Status = 0 and ms.ServiceType = 2) AS DueOnDateSort,        
             
  CASE WHEN EXISTS(SELECT top 1(vm.VehiclePlanId) FROM rvlfVehicleMaintenanceService vm           
       WHERE vm.VehiclePlanId = vp.VehiclePlanId AND vm.Status = 0 AND          
       (vm.IsNotification1Sent = 1 OR vm.IsNotification2Sent = 1 OR vm.IsNotification1Sent = 1)          
       )          
  THEN 1 ELSE 0 END AssignedStatus          
  FROM rvlfVehicle v           
  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehicleId = v.VehicleId   
  inner join  rvlfVehicleMaintenanceService vm  on vm.VehiclePlanId = vp.VehiclePlanId        
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId           
  INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = v.VehicleId          
  WHERE (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID)          
   AND vp.PlanId = @bigPlanId AND (@bigFleetId IS NULL OR fv.FleetId = @bigFleetId) AND vp.AssignedStatus = 1          
  ORDER BY VehicleDescription ASC          
           
    END          
    ELSE IF (@chrType = 'U') -- Get Unassigned Vehicles          
    BEGIN          
              
        -- Select all the vehicles from the Vehicle Information which is not present in Vehicle Maintenance Plan Assignment          
  SELECT DISTINCT(v.VehicleId), v.VehicleDescription, 'True' AS 'IsActive',           
  CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours  * 60, 0)) as Float)/ 3600 as DEcimal(18,2)) AS 'EngineHrsOpeningValue', NULL AS 'EngineHrsSIValue',          
  ISNULL(cr.CurrentOdometerReading, 0) AS 'OdometerOpeningValue', NULL AS 'OdometerSIValue',           
  '1/1/9000' AS 'TimeBasedSIValue'          
  FROM rvlfVehicle v          
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId          
  LEFT OUTER JOIN rvlfVehicleCurrentReadings cr ON v.VehicleId = cr.VehicleId            
  WHERE (v.OrganizationId = 139)          
   AND fv.FleetId in(223,247)  AND v.VehicleId  IN          
      (SELECT vp.VehicleId FROM rvlfVehiclePlanAssignment vp WHERE PlanId in(83,84,85,86,87) AND vp.AssignedStatus = 1)          
      ORDER BY VehicleDescription ASC          
              
    END          
              
SET NOCOUNT OFF          
END 


select * from rvlfVehiclePlanAssignment where VehicleId =1644
select * from rvlfFleetVehicles where VehicleId =1644

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehiclePlanAssignments_WO]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetVehiclePlanAssignments_WO]        
 @chrType char,        
 @bigOrganizationID bigint,        
 @bigFleetId bigint = NULL,        
 @bigVehicleId bigint = NULL,        
 @bigPlanId bigint = NULL,         
 @bigQueryingUser bigint = 0        
AS        
/**************************************************************************************/        
-- Name  : rvlf_sp_GetVehiclePlanAssignments_WO 'A', 6, 8, 248, null, 14    
-- Description : To get the vehicle assignment details        
-- Author  : Ranjith . N        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--          : 06-Nov-2015  Created Intial Version         
/**************************************************************************************/        
BEGIN        
SET NOCOUNT ON         
          
 DECLARE @ConversionFactor numeric (10,2) = 1.0        
 DECLARE @HoursToBeAdded INT = 0        
 DECLARE @MinsToBeAdded INT = 0        
 DECLARE @DefaultDateFormat INT = 0      
            
    SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,        
           @HoursToBeAdded = tz.HoursToBeAdded, @MinsToBeAdded = tz.MinToBeAdded ,      
           @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        
         
 IF(@chrType = 'S') -- Select All Vehicle Plan Assignments        
 BEGIN         
          
  SELECT vp.VehiclePlanId, vp.VehicleId, v.VehicleDescription, mp.PlanId, mp.PlanName, mp.RecurringService AS IsRecurring, vp.IsActive,         
  CASE WHEN vp.EngineHrsStartValue IS NULL THEN 'N/A' ELSE CONVERT(Varchar(15), vp.EngineHrsStartValue) END AS EngineHrsStartValue,        
  CASE WHEN vp.OdometerReadingStartValue IS NULL THEN 'N/A' ELSE CONVERT(Varchar(15), vp.OdometerReadingStartValue) END AS OdometerReadingStartValue, 
       
  CASE WHEN vp.TimeBasedStartValue IS NULL THEN 'N/A' ELSE  Convert(varchar,vp.TimeBasedStartValue,@DefaultDateFormat) END as TimeBasedStartValue,
  vp.TimeBasedStartValue as TimeBasedStartValueSort, u.DisplayName, DATEADD(n, @MinsToBeAdded,   
  DATEADD(hh, @HoursToBeAdded, vp.AssignedDateTime)) AS AssignedDateTime, isnull(mp.VAT,0) as VAT        
  /*Change For FleetMaintance */    
  --Convert(varchar,vp.TimeBasedStartValue,@DefaultDateFormat) END as TimeBasedStartValue,vp.TimeBasedStartValue as TimeBasedStartValueSort, u.DisplayName, DATEADD(n, @MinsToBeAdded, DATEADD(hh, @HoursToBeAdded, vp.AssignedDateTime)) AS AssignedDateTime  
        
  FROM rvlfVehiclePlanAssignment vp        
  INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId        
  INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId        
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId        
  INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId        
  INNER JOIN rvlfUser u ON u.UserId = vp.AssignedBy        
  WHERE v.OrganizationId = @bigOrganizationID AND (@bigFleetId IS NULL OR f.FleetId = @bigFleetId) AND (@bigVehicleId IS NULL OR v.VehicleId = @bigVehicleId)         
  AND (@bigPlanId IS NULL OR vp.PlanId = @bigPlanId) AND vp.AssignedStatus = 1           
        
    END        
    ELSE IF (@chrType = 'A') -- Get Assigned Vehicles        
    BEGIN         
            
  -- Select the vehicles assigned to the Maintenance Plan        
  SELECT DISTINCT(v.VehicleId), v.VehicleDescription, vp.IsActive, vp.VehiclePlanId,        
  (cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0)) AS CurrentEngineHours,(SELECT ISNULL(DueOn, 0) FROM rvlfVehicleMaintenanceService ms        
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = ms.PlanDetailsId        
   WHERE mpd.PlanId = @bigPlanId and ms.VehiclePlanId = vp.VehiclePlanId and ms.Status = 0 and (ms.ServiceType = 0 OR ms.ServiceType =3)) AS EngineHrsDueOn,         
  CONVERT(BIGINT,(cr.CurrentOdometerReading * @ConversionFactor)) AS CurrentOdometerReading,        
    CONVERT(BIGINT,((SELECT ISNULL(DueOn, 0) FROM rvlfVehicleMaintenanceService ms        
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = ms.PlanDetailsId        
   WHERE mpd.PlanId = @bigPlanId and ms.VehiclePlanId = vp.VehiclePlanId and ms.Status = 0 and ms.ServiceType = 1)* @ConversionFactor)) AS OdometerReadingDueOn,        
  Convert(varchar,GETDATE(),@DefaultDateFormat) AS CurrentDate,GETDATE() AS CurrentDateSort, Convert(varchar,(SELECT DueOnDate FROM rvlfVehicleMaintenanceService ms        
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = ms.PlanDetailsId        
   WHERE mpd.PlanId = @bigPlanId and ms.VehiclePlanId = vp.VehiclePlanId and ms.Status = 0 and ms.ServiceType = 2),@DefaultDateFormat) AS DueOnDate,         
   (SELECT DueOnDate FROM rvlfVehicleMaintenanceService ms        
   INNER JOIN rvlfMaintenancePlanDetails mpd ON mpd.PlanDetailsId = ms.PlanDetailsId        
   WHERE mpd.PlanId = @bigPlanId and ms.VehiclePlanId = vp.VehiclePlanId and ms.Status = 0 and ms.ServiceType = 2) AS DueOnDateSort,      
           
  CASE WHEN EXISTS(SELECT vm.VehiclePlanId FROM rvlfVehicleMaintenanceService vm         
       WHERE vm.VehiclePlanId = vp.VehiclePlanId AND vm.Status = 0 AND        
       (vm.IsNotification1Sent = 1 OR vm.IsNotification2Sent = 1 OR vm.IsNotification1Sent = 1)        
       )        
  THEN 1 ELSE 0 END AssignedStatus,mp.PlanName ,
  isnull(WG.WONo,0)   as WorkOrderNo,vp.PlanId,
  (Case when WG.Status = 1 then 'WO Generated'
  when WG.Status = 2 then 'WO Approved'  
    when WG.Status = 3 then 'WO Redo'   
  when WG.Status = 4 then 'WO Rejected'  
  when WG.Status = 5 then 'WO Closed'  
  when WG.Status = 6 then 'WO Reopened'  
  else '-'
   end) as WOStatus,isnull(WG.Status,0) as [Status],(Case when isnull(WG.QuotationFile,0) ='0' then 0 else 1 end)  as QuotationFile,
   isnull(mp.VAT,0) as VAT
  FROM rvlfVehicle v         
  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehicleId = v.VehicleId        
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId         
  INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = v.VehicleId  
  inner join rvlfMaintenancePlan mp on  mp.PlanId = vp.PlanId
  left outer join rvlfWOGeneration WG on WG.VehiclePlanId = vp.VehiclePlanId  and WG.IsDelete = 0 
  WHERE (@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID)        
   AND (@bigPlanId IS NULL OR vp.PlanId = @bigPlanId) AND 
   (@bigFleetId IS NULL OR fv.FleetId = @bigFleetId) AND
     (@bigVehicleId IS NULL OR v.VehicleId = @bigVehicleId)    AND      vp.AssignedStatus = 1      
  ORDER BY VehicleDescription ASC        
            
    END        
     
            
SET NOCOUNT OFF        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehiclePlanDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetVehiclePlanDetails]    
 @bigVehicleId bigint = 0,    
 @bigQueryingUser bigint = 0    
AS    
/**************************************************************************************/    
-- Name  : rvlf_sp_GetVehiclePlanDetails   
-- Description : To get the vehicle maintenance plan details    
-- Author  : Kumuthini. L    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
/**************************************************************************************/    
BEGIN    
SET NOCOUNT ON     
     
 DECLARE @Distance varchar(20)    
 DECLARE @ConversionFactor numeric (10,2) = 1.0    
    SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,    
     @Distance = CASE WHEN up.Distance = 0 THEN ' miles' ELSE ' km' END    
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz    
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser    
     
    SELECT DISTINCT vm.ServiceDetailsId, mp.PlanName, dbo.rvlf_fn_GetMaintenanceServices(5, vp.PlanId, null) AS ServicesPlanned,    
 CASE WHEN vm.ServiceType = 0 THEN 'Running Hours'     
         WHEN vm.ServiceType = 1 THEN 'Odometer'   
         WHEN vm.ServiceType = 2 THEN 'Time Based'   
         ELSE 'Concrete Mix Hours' END AS ServiceType,   
    CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3  THEN CONVERT(VARCHAR(10), vm.DueOn) + ' hrs'    
      WHEN vm.ServiceType = 1 THEN CONVERT(VARCHAR(10), CONVERT(INT, ROUND((vm.DueOn * @ConversionFactor), 0, 0))) + @Distance    
      ELSE CONVERT(VARCHAR(10), vm.DueOnDate, 101) END AS DueOn,    
    CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3 THEN CONVERT(Varchar(10), CASt(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0)) AS float)/3600 as Decimal(18,2))) + ' hrs'    
   WHEN vm.ServiceType = 1 THEN CONVERT(Varchar(10), CONVERT(INT, (cr.CurrentOdometerReading * @ConversionFactor))) + @Distance    
   WHEN vm.ServiceType = 2 THEN CONVERT(Varchar(10), GETUTCDATE(), 101) END AS CurrentReading,    
 CASE WHEN mp.RecurringService = 1 THEN (CASE WHEN vm.Frequency = 3 THEN CONVERT(VARCHAR(6), pd.ServiceInterval) + ' hrs'    
      WHEN vm.Frequency = 4 THEN CONVERT(VARCHAR(6), CONVERT(INT, ROUND((pd.ServiceInterval * @ConversionFactor), 0, 0))) + @Distance    
      ELSE CONVERT(VARCHAR(6), pd.ServiceInterval) + (CASE WHEN vm.Frequency = 0 THEN ' days'     
   WHEN vm.Frequency = 1 THEN ' months' ELSE ' Years' END) END) ELSE 'N/A' END AS ServiceInterval    
 FROM rvlfVehicleMaintenanceService vm    
 INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId    
 INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId    
 INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId    
 INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanId = mp.PlanId AND pd.PlanDetailsId = vm.PlanDetailsId    
 INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId    
 WHERE vp.VehicleId = @bigVehicleId AND vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1  and vm.ServiceType <> 1   
    
SET NOCOUNT OFF    
END    
    
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetVehicles]  
 @bigFleedID bigint = null,  
 @bigOrganizationID bigint = null,  
 @bigVehicleID bigint = null,  
 @bigQueryingUser bigint = 0  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetVehicles 1,86
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
 SELECT   
  v.VehicleId, v.Vin, v.LicensePlate, v.MakeId, v.ModelId, '' as MakeName, '' as ModelName,  
  v.VehicleTypeId, t.VehicleTypeName, v.StateProvince, v.ModelYear, v.Color,  
  v.VehicleDescription, v.IconTypeId, v.TimeZone as VehicleTimeZone,  
  v.DayLightSaving as VehicleDayLightSaving, v.Email as VehicleEmail,  
  v.SMS as VehicleSMS, v.Notify as VehicleNotify, v.Critical as VehicleCritical,  
  v.Warning as VehicleWarning , v.AutoAdjustDayLightSaving as VehicleAutoAdjust,  
  f.FleetId, f.FleetName, f.OrganizationId, f.[Description] as FleetDesc,  
  f.Email as FleetEmail, f.SMS as FleetSMS, f.TimeZone as FleetTimezone,  
  f.DayLightSaving as FleetDayLightSaving, f.Notify as FleetNotify,  
  f.Warning as FleetWarning , f.Critical as FleetCritical ,   
  f.AutoAdjustDayLightSaving as FleetAutoAdjust, g.OrganizationName,  
  MD.BoxId, v.VehicleDescription as VehicleName,MD.CustomerId,MD.SubTypeId as DeviceType
 FROM rvlfVehicle v  
 Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
  --INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId   
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
 -- LEFT OUTER JOIN rvlfMake m ON v.MakeId = m.MakeId  
 -- LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId  
  INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
 WHERE  
  --va.IsDeleted = 0 AND   
  (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID) AND  
   (@bigFleedID IS NULL OR @bigFleedID='' OR f.FleetId =@bigFleedID) 
   AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR g.OrganizationId= @bigOrganizationID)  
 ORDER BY v.VehicleDescription ASC
 
 SELECT Distinct (v.VehicleTypeId) AS TypeID, t.VehicleTypeName as TypeName FROM rvlfVehicle v  
 Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
 INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
 INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
 INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId
 INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
 WHERE (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID) AND
(@bigFleedID IS NULL OR @bigFleedID='' OR f.FleetId =@bigFleedID) 
AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR g.OrganizationId= @bigOrganizationID)
   
 SET NOCOUNT OFF  
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicles_Adr]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_GetVehicles_Adr]  
 @bigFleedID bigint = null,  
 @bigOrganizationID bigint = null,  
 @bigVehicleID bigint = null,  
 @bigQueryingUser bigint = 0  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetVehicles_adr 0,86
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
 SELECT   
  v.VehicleId, v.Vin, v.LicensePlate, v.MakeId, v.ModelId, '' as MakeName, '' as ModelName,  
  v.VehicleTypeId, t.VehicleTypeName, v.StateProvince, v.ModelYear, v.Color,  
  v.VehicleDescription, v.IconTypeId, v.TimeZone as VehicleTimeZone,  
  v.DayLightSaving as VehicleDayLightSaving, v.Email as VehicleEmail,  
  v.SMS as VehicleSMS, v.Notify as VehicleNotify, v.Critical as VehicleCritical,  
  v.Warning as VehicleWarning , v.AutoAdjustDayLightSaving as VehicleAutoAdjust,  
  f.FleetId, f.FleetName, f.OrganizationId, f.[Description] as FleetDesc,  
  f.Email as FleetEmail, f.SMS as FleetSMS, f.TimeZone as FleetTimezone,  
  f.DayLightSaving as FleetDayLightSaving, f.Notify as FleetNotify,  
  f.Warning as FleetWarning , f.Critical as FleetCritical ,   
  f.AutoAdjustDayLightSaving as FleetAutoAdjust, g.OrganizationName,  
  MD.BoxId, v.VehicleDescription as VehicleName,MD.CustomerId
 FROM rvlfVehicle v  
 Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
  --INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId   
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
 -- LEFT OUTER JOIN rvlfMake m ON v.MakeId = m.MakeId  
 -- LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId  
  INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
 WHERE   
  --va.IsDeleted = 0 AND   
  (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID) AND  
   (@bigFleedID IS NULL   OR f.FleetId =@bigFleedID) AND  
  (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR g.OrganizationId= @bigOrganizationID)  
 ORDER BY v.VehicleDescription ASC  

  
 SET NOCOUNT OFF  
END 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicles_KPI]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicles_KPI]  
 @bigFleedID bigint = null,  
 @bigOrganizationID bigint = null,  
 @bigVehicleID bigint = null,  
 @bigQueryingUser bigint = 0,
 @KPIID Tinyint =NULL,
 @VehicleTypeId INT =NULL
AS  
/******************************************************************************/  
-- NAME             : rvlf_sp_GetVehicles_KPI 247,6,NULL,547,1,2
-- DESCRIPTION		: TO GETS THE Fleet and Equipment Type,Decvice, OF THE KPI
-- AUTHOR			: Asan Raj N 
-- COMPANY			: TRINETRA WIRELESS (P) LTD
-- HISTORY			: <<DATE(DD-MON-YYYY)>> INITIAL REASON
--					: 04-Jan-2018 NA CREATED INTIAL VERSION
/******************************************************************************/  
BEGIN
 SET NOCOUNT ON   
BEGIN TRY  
     SELECT   
      v.VehicleId, v.Vin, v.LicensePlate, v.MakeId, v.ModelId, '' as MakeName, '' as ModelName,  
      v.VehicleTypeId, t.VehicleTypeName, v.StateProvince, v.ModelYear, v.Color,  
      v.VehicleDescription, v.IconTypeId, v.TimeZone as VehicleTimeZone,  
      v.DayLightSaving as VehicleDayLightSaving, v.Email as VehicleEmail,  
      v.SMS as VehicleSMS, v.Notify as VehicleNotify, v.Critical as VehicleCritical,  
      v.Warning as VehicleWarning , v.AutoAdjustDayLightSaving as VehicleAutoAdjust,  
      f.FleetId, f.FleetName, f.OrganizationId, f.[Description] as FleetDesc,  
      f.Email as FleetEmail, f.SMS as FleetSMS, f.TimeZone as FleetTimezone,  
      f.DayLightSaving as FleetDayLightSaving, f.Notify as FleetNotify,  
      f.Warning as FleetWarning , f.Critical as FleetCritical ,   
      f.AutoAdjustDayLightSaving as FleetAutoAdjust, g.OrganizationName,  
      MD.BoxId, v.VehicleDescription as VehicleName,MD.CustomerId,MD.VFantype
     FROM rvlfVehicle v  
     Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
      --INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId   
      INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
      INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
      INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
     -- LEFT OUTER JOIN rvlfMake m ON v.MakeId = m.MakeId  
     -- LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId  
      INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
     WHERE  
      --va.IsDeleted = 0 AND   
     (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID) AND  
      (@bigFleedID IS NULL OR @bigFleedID='' OR f.FleetId =@bigFleedID) AND  
     (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR g.OrganizationId= @bigOrganizationID) --AND 
	 --(@VehicleTypeId IS NULL OR @VehicleTypeId ='' OR v.VehicleTypeId = @VehicleTypeId) 
	 --AND ((@KPIID IS NULL OR @KPIID ='' OR  @KPIID NOT IN(19,20,21,22)) OR (@KPIID IS NULL OR @KPIID ='' OR  @KPIID IN(19,20,21,22) AND MD.VFantype IS Not null))
     ORDER BY v.VehicleDescription ASC 

      SELECT Distinct (v.VehicleTypeId) AS TypeID, t.VehicleTypeName as TypeName FROM rvlfVehicle v  
      Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
      INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
      INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
      INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId
      INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
      WHERE (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID) AND
      (@bigFleedID IS NULL OR @bigFleedID='' OR f.FleetId =@bigFleedID) AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR g.OrganizationId= @bigOrganizationID) 
      AND ((@KPIID IS NULL OR @KPIID ='' OR @KPIID IN(1,2,3,4,7,8,9,11,12,15,19,20,21,22) AND V.VehicleTypeId IN(1,2,3,4)) OR (@KPIID IS NULL OR @KPIID ='' OR @KPIID IN(5,6) AND V.VehicleTypeId IN(3,4)) OR (@KPIID IS NULL OR @KPIID= '' OR @KPIID IN(10,13) AND V.VehicleTypeId IN(2,4)))
	  
   END TRY 
   BEGIN CATCH
      SELECT ERROR_MESSAGE() AS ERRRORMESSAGE;
   END CATCH
     
 SET NOCOUNT OFF  
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicles_KPI1]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicles_KPI1]  
 @bigFleedID bigint = null,  
 @bigOrganizationID bigint = null,  
 @bigVehicleID bigint = null,  
 @bigQueryingUser bigint = 0,
 @KPIID Tinyint =NULL,
 @VehicleTypeId INT =NULL
AS  
/******************************************************************************/  
-- NAME             : rvlf_sp_GetVehicles_KPI 8,NULL,NULL,398,1,1
-- DESCRIPTION		: TO GETS THE Fleet and Equipment Type,Decvice, OF THE KPI
-- AUTHOR			: Asan Raj N 
-- COMPANY			: TRINETRA WIRELESS (P) LTD
-- HISTORY			: <<DATE(DD-MON-YYYY)>> INITIAL REASON
--					: 04-Jan-2018 NA CREATED INTIAL VERSION
/******************************************************************************/  
BEGIN
 SET NOCOUNT ON   
BEGIN TRY  
   IF(@bigOrganizationID IS NULL)
   BEGIN
     SET @bigOrganizationID = (select OrganizationId from rvlfUser where UserId=@bigQueryingUser)
   END

    SELECT   
      MD.BoxId, v.VehicleId, v.Vin, v.LicensePlate, v.MakeId, v.ModelId, '' as MakeName, '' as ModelName,  
      v.VehicleTypeId, t.VehicleTypeName, v.StateProvince, v.ModelYear, v.Color,  
      v.VehicleDescription, v.IconTypeId, v.TimeZone as VehicleTimeZone,  
     Isnull(MD.VFantype,'0') AS VFantype
     FROM rvlfVehicle v  
        Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid       
        INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
        INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
        INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId     
        INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
     WHERE     
       (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID) AND  
       (@bigFleedID IS NULL OR @bigFleedID='' OR f.FleetId =@bigFleedID) AND  
       (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR g.OrganizationId= @bigOrganizationID) AND 
	   (@VehicleTypeId IS NULL OR @VehicleTypeId ='' OR v.VehicleTypeId = @VehicleTypeId) and IsDelete =0 
	    AND((@KPIID IS NULL OR @KPIID ='' OR  @KPIID NOT IN(19,20,21,22)) OR (@KPIID IS NULL OR @KPIID ='' OR  @KPIID IN(19,20,21,22) AND VFantype NOT IN(0)))
     ORDER BY v.VehicleDescription ASC 

     SELECT Distinct (v.VehicleTypeId) AS TypeID, t.VehicleTypeName as TypeName FROM rvlfVehicle v  
       Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
       INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
       INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
       INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId
       INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
      WHERE (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID) AND
       (@bigFleedID IS NULL OR @bigFleedID='' OR f.FleetId =@bigFleedID) AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR g.OrganizationId= @bigOrganizationID) 
       AND ((@KPIID IS NULL OR @KPIID ='' OR @KPIID IN(1,2,3,4,7,8,9,11,12,15,16,17,18,19,20,21,22) AND V.VehicleTypeId IN(1,2,3,4)) OR (@KPIID IS NULL OR @KPIID ='' OR @KPIID IN(5,6) AND V.VehicleTypeId IN(3,4)) OR (@KPIID IS NULL OR @KPIID= '' OR @KPIID IN(10,13) AND V.VehicleTypeId IN(2,4)))
	  
   END TRY 
   BEGIN CATCH
      SELECT ERROR_MESSAGE() AS ERRRORMESSAGE;
   END CATCH
     
 SET NOCOUNT OFF  
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicles_Live]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetVehicles_Live]    
@BoxIds VARCHAR(MAX)=NULL,
@bigOrganizationID bigint = null,    
@bigQueryingUser bigint = 0    
AS
/*****************************************************************************************/    
-- Procedure	: rvlf_sp_GetVehicles_Live '999982,999988',6,94  
-- Description	: To get the Vehicles based on the organization and BOXIDS if specified.    
-- Author		: S Sakthi Gopinath
-- Company		: Trinetra Wireless (P) Ltd
-- History		: <<Date(dd-MON-yyyy)>> Initial Reason    
--				: 30-Jun-2016 SS Created Intial Version     
--				: 10-Aug-2016 SS Driver column included
/****************************************************************************************/  
BEGIN
SET NOCOUNT ON

	DECLARE @HoursToBeAdded INT = 0  
	DECLARE @MinsToBeAdded INT = 0  
	DECLARE @ConversionFactor numeric (10,2) = 1.0  
	DECLARE @DistanceCaptionPrefix varchar(15)  
	DECLARE @SpeedCaptionPrefix varchar(15)  
	DECLARE @Lang varchar(50)
    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,
	@Lang=isnull(Lang,'LanguageEn')
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz  
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser  
   

   --FIND THE CURRENT DRIVER NAMES BASED ON THE SCHEDULES---------------------------------------------------------                                          
	DECLARE @tblDriverDetails TABLE(Boxid bigint,DisplayName nvarchar(30),DriverName varchar(max))                                          
                                    
	INSERT INTO @tblDriverDetails(Boxid,DisplayName)                                          
	SELECT DA.BoxId,(case when @Lang='LanguageArNew' then isnull(DisplayNameAr,DisplayName) else DisplayName end)DisplayName                                        
	FROM rvlfDriverAssignment DA                                          
	INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=DA.BoxId                                          
	INNER JOIN rvlfFleetVehicles FV ON FV.VehicleId=VA.VehicleId                                          
	INNER JOIN rvlfDriverMaster DM ON DM.DriverId=DA.DriverId                                        
	LEFT OUTER JOIN rvlfIButtonMapping IB ON IB.DriverId<>DM.DriverId and IB.BoxID = VA.BoxId                                           
	WHERE VA.BoxId IN (SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(@BoxIds,','))   
	AND GETUTCDATE() BETWEEN CASE WHEN DA.PunchIn IS NULL THEN DA.FromTime ELSE DA.PunchIn END                                
    AND CASE WHEN DA.PunchOut IS NULL THEN DA.ToTime ELSE DA.PunchOut END                                           
                                         
	--FIND THE MULTI DERIVERS BASED ON THE VEHICLE                                        
	DECLARE @INC INT=0                                          
	SELECT @INC =MIN(BOXID) FROM @tblDriverDetails                                            
	WHILE @INC IS NOT NULL                                          
	BEGIN                                            
		DECLARE @vcDriverNames VARCHAR(MAX)=NULL                                          
		SELECT @vcDriverNames=COALESCE(@vcDriverNames,'')+CONVERT(VARCHAR,DisplayName)+',' FROM @tblDriverDetails WHERE Boxid=@INC                                           
		UPDATE @tblDriverDetails SET DriverName=@vcDriverNames,DisplayName=NULL WHERE Boxid=@INC                                           
		SELECT @INC =MIN(BOXID) FROM @tblDriverDetails WHERE Boxid >@INC                                           
	END                                          
	INSERT INTO @tblDriverDetails (Boxid,DisplayName,DriverName)                   
	SELECT Boxid,'DRIVER',DriverName FROM @tblDriverDetails GROUP BY Boxid,DisplayName,DriverName                                             
	DELETE FROM @tblDriverDetails WHERE DisplayName IS NULL           

	SELECT v.VehicleId, v.Vin, v.LicensePlate, v.MakeId, v.ModelId,@HoursToBeAdded AS HH,@MinsToBeAdded AS MM,
	@ConversionFactor AS CF,@DistanceCaptionPrefix AS DP,@SpeedCaptionPrefix AS SP,
	v.VehicleTypeId, t.VehicleTypeName, v.StateProvince, v.ModelYear, v.Color,
	(case when @Lang='LanguageArNew' then isnull(v.VehicleDescription,v.VehicleDescription) else v.VehicleDescription end) as VehicleDescription, 
	v.IconTypeId, v.TimeZone as VehicleTimeZone,v.DayLightSaving as VehicleDayLightSaving, v.Email as VehicleEmail,
	v.SMS as VehicleSMS, v.Notify as VehicleNotify, v.Critical as VehicleCritical,
	v.Warning as VehicleWarning , v.AutoAdjustDayLightSaving as VehicleAutoAdjust,g.OrganizationName,
	va.BoxId, (case when @Lang='LanguageArNew' then isnull(v.VehicleDescription,v.VehicleDescription) else v.VehicleDescription end) as VehicleName,
	(CASE WHEN d.DisplayName IS NULL OR d.DisplayName='' THEN 'NA' ELSE d.DisplayName END) as DriverName
	FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId     
	INNER JOIN rvlfBoxId b ON b.BoxId = va.BoxId
	INNER JOIN rvlfOrganization g ON v.OrganizationId = g.OrganizationId    
	INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId
	LEFT OUTER JOIN @tblDriverDetails d ON d.BoxId = b.BoxId
	WHERE b.BoxID IN (SELECT FieldValue FROM dbo.rvlf_fn_ConvertArrayToTable(@BoxIds,','))   
	ORDER BY v.VehicleDescription ASC

SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehiclesByTypeId]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetVehiclesByTypeId]  
 @bigFleedID bigint = null,  
 @bigOrganizationID bigint = null,  
 @bigVehicleID bigint = null,  
 @VehicleTypeId int = null,  
 @bigQueryingUser bigint = 0  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetVehicles 176,86,null,1
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
 SELECT   
  v.VehicleId, v.Vin, v.LicensePlate, v.MakeId, v.ModelId, '' as MakeName, '' as ModelName,  
  v.VehicleTypeId, t.VehicleTypeName, v.StateProvince, v.ModelYear, v.Color,  
  v.VehicleDescription, v.IconTypeId, v.TimeZone as VehicleTimeZone,  
  v.DayLightSaving as VehicleDayLightSaving, v.Email as VehicleEmail,  
  v.SMS as VehicleSMS, v.Notify as VehicleNotify, v.Critical as VehicleCritical,  
  v.Warning as VehicleWarning , v.AutoAdjustDayLightSaving as VehicleAutoAdjust,  
  f.FleetId, f.FleetName, f.OrganizationId, f.[Description] as FleetDesc,  
  f.Email as FleetEmail, f.SMS as FleetSMS, f.TimeZone as FleetTimezone,  
  f.DayLightSaving as FleetDayLightSaving, f.Notify as FleetNotify,  
  f.Warning as FleetWarning , f.Critical as FleetCritical ,   
  f.AutoAdjustDayLightSaving as FleetAutoAdjust, g.OrganizationName,  
  MD.BoxId, v.VehicleDescription as VehicleName,MD.CustomerId,MD.SubTypeId as DeviceType
 FROM rvlfVehicle v  
 Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
  --INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId   
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
 -- LEFT OUTER JOIN rvlfMake m ON v.MakeId = m.MakeId  
 -- LEFT OUTER JOIN rvlfModel d ON v.ModelId = d.ModelId  
  INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
 WHERE  
  --va.IsDeleted = 0 AND   
  (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID) AND  
   (@bigFleedID IS NULL OR @bigFleedID='' OR f.FleetId =@bigFleedID) AND
   (@VehicleTypeId IS NULL OR @VehicleTypeId='' OR MD.SubTypeId = @VehicleTypeId)   
   AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR g.OrganizationId= @bigOrganizationID)  
 ORDER BY v.VehicleDescription ASC
 
 SELECT Distinct (v.VehicleTypeId) AS TypeID, t.VehicleTypeName as TypeName FROM rvlfVehicle v  
 Inner Join rvlfmakdevices MD on MD.vehicleid=v.vehicleid
 INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
 INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
 INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId
 INNER JOIN rvlfVehicleType t On v.VehicleTypeId = t.VehicleTypeId  
 WHERE (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID) AND
(@bigFleedID IS NULL OR @bigFleedID='' OR f.FleetId =@bigFleedID) 
AND (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR g.OrganizationId= @bigOrganizationID)
   
 SET NOCOUNT OFF  
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleServiceHistory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetVehicleServiceHistory]         
 @bigOrganizationID bigint,        
 @bigFleetId bigint = NULL,        
 @bigVehicleId bigint = NULL,        
 @tiServiceStatus tinyint = NULL,        
 @bigPlanId bigint = NULL,        
 @tiServiceType int = NULL,        
 @dtFromDate datetime,        
 @dtToDate datetime,        
 @bigQueryingUser bigint = 0        
AS        
/**************************************************************************************/        
-- Name     : rvlf_sp_GetVehicleServiceHistory  6,null,null,null,null,null,'4/1/2018 12:00:00 AM','4/22/2019 12:00:00 AM',564      
-- Description : To get the vehicle maintenance history details        
-- Author   : Kumuthini. L        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--          : 18-Jun-2010  Kumuthini Created Intial Version         
--          :        25-Jun-2010  Kumuthini  Included the User Preferences        
--          :   07-Oct-2010  Jeyanthi Included Plan and Service Type for Retriving Data        
--          :   03-Feb-2010  Kumuthini Included the Adhoc Services        
--          :   16-Aug-2011 Ranjith Date format included   
--   : 9-oct-2013 Gopal TotalPlannedCost1 new field for export pdf     
/**************************************************************************************/        
BEGIN        
SET NOCOUNT ON         
         
 DECLARE @Distance varchar(20)        
 DECLARE @ConversionFactor numeric (10,2) = 1.0      
 DECLARE @DefaultDateFormat INT = 0  
  DECLARE @HoursToBeAdded INT = 0            
 DECLARE @MinsToBeAdded INT = 0      
         
   SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,        
   @Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END,      
   @DefaultDateFormat=(case when  ISNULL(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end),
   @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded        
   FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz        
   ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser         
         
 SELECT ROW_NUMBER() OVER (ORDER BY t.ExecutionDate) AS RefNo, t.* FROM         
 (        
 SELECT DISTINCT md.VehicleId, md.EquipmentName as VehicleDescription, 'Planned' AS 'Type', mp.PlanId, mp.PlanName,
  --CONVERT(varchar,vm.ExecutedOn,@DefaultDateFormat) AS 'ExecutionDate',
 convert(varchar(50),cast(vm.ExecutedOn as date),106) AS 'ExecutionDate',
  cast(vm.ExecutedOn as date) AS 'ExecutionDateSort',            
 @Distance AS DistanceUnits, CASE WHEN vm.Status = 2 THEN 'N/A'      
  ELSE 
  CONVERT(Varchar(20), 
  (CASE WHEN vm.ServiceType = 2 THEN cast(DATEDIFF(DD, vm.DueOnDate, vm.ExecutedOn) as varchar(10))+ ' days' 
  WHEN vm.ServiceType = 0 THEN cast((CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0))AS FLOAT)/(3600)AS Decimal(18,2))- vm.dueon) as varchar(20)) + ' hrs'                         
   ELSE (CASE WHEN vm.OverdueDate IS NOT NULL THEN cast(DATEDIFF(DD, vm.OverdueDate, vm.ExecutedOn) as varchar(20)) ELSE '0' END) END)
  ) 
  
  END AS DelayBy,         
 mp.TotalPlannedCost  
 ,case when mp.TotalPlannedCost =0.00 then 'N/A' else cast(mp.TotalPlannedCost as varchar(10)) end as TotalPlannedCost1    
 , ISNULL(vm.ServiceCost, 0) AS ActualCost,   
 CASE WHEN vm.Status = 0 THEN 'Pending' WHEN vm.Status = 1 THEN 'Completed'         
   WHEN vm.Status = 2 THEN 'Skipped' WHEN vm.Status = 3 THEN 'Dismissed' END AS Status,        
    CASE WHEN vm.ServiceType = 0 THEN 'Running Hours'       
    WHEN vm.ServiceType = 1 THEN 'Odometer'      
    WHEN vm.ServiceType = 2 THEN 'Time Based'          
    ELSE 'Concrete Mix Hours' END AS ServiceType,           
    CONVERT(Varchar(10), ISNULL(vm.EngineHrsOnClose, 0)) + ' hrs; ' +         
    CONVERT(Varchar(7), CONVERT(INT, ROUND((ISNULL(vm.OdometerReadingOnClose, 0) * @ConversionFactor), 0, 0)))        
    + ' ' + @Distance AS ReadingsOnClose,        
    vm.Comments, vm.RescheduledOn, vm.NearingPercentage, vm.ServiceDetailsId,'N/A' as document1,'N/A' as document2,isnull(u.username,'N/A') as ServicedBy, vm.ModifiedDateTime,null as BeforeService,	
    null as AfterService
 FROM rvlfVehicleMaintenanceService vm        
 INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId    
  inner join rvlfMAKDevices md on md.VehicleId=VP.VehicleId
 inner join rvlfVehicleType vt on vt.VehicleTypeId=md.SubTypeId          
 INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId         
 INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId         
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = md.VehicleId       
 INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId            
 left outer join rvlfMaintenanceServiceDetails vms on vms.ServiceDetailsId=vm.ServiceDetailsId
 left outer join rvlfUser u on u.UserId=vms.ServicedBy 
 WHERE mp.OrganizationId = @bigOrganizationID AND vm.Status <> 0 AND (@tiServiceStatus IS NULL OR @tiServiceStatus='' OR vm.Status = @tiServiceStatus)         
 --AND (CONVERT(DATE, vm.ExecutedOn, 101) BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101))        
 AND cast(vm.ExecutedOn as date) BETWEEN  cast(@dtFromDate as date) AND cast(@dtToDate as date)
 AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId) AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR vp.VehicleId = @bigVehicleId)        
 AND (@bigPlanId IS NULL OR @bigPlanId='' OR vp.PlanId = @bigPlanId) AND (@tiServiceType IS NULL OR @tiServiceType='' OR ServiceType = @tiServiceType)        
 AND IsNearing = 1       
         
 UNION        
         
    SELECT DISTINCT md.VehicleId,md.EquipmentName as VehicleDescription, 'Unplanned' AS 'Type', 0 AS PlanId, 'N/A' AS PlanName,        
 --Convert(varchar,ad.ExecutionOn,@DefaultDateFormat) AS 'ExecutionDate',
  convert(varchar(50),Cast(ad.ExecutionOn as date),106) AS 'ExecutionDate',
  Cast(ad.ExecutionOn as date) AS 'ExecutionDateSort', @Distance AS DistanceUnits, 'N/A' AS DelayBy, 0 AS TotalPlannedCost, 'N/A'  AS TotalPlannedCost1,       
 ad.TotalServiceCost AS ActualCost, 'Completed' AS Status, 'N/A' AS ServiceType, '' AS ReadingsOnClose,        
 ad.Comments, NULL AS RescheduledOn, 0 AS NearingPercentage, ad.AdhocServiceId AS ServiceDetailsId,ad.Photo1 as document1,ad.Photo2 as document2,U.UserName as Servicedby,        
 ad.CreatedDateTime AS ModifiedDateTime,
    --'T1=041;T2=036;T3=012;T4=016;' as BeforeT,'P1=0901;P2=0902;P3=0903;P4=0904;' as BeforeP, 'PO1=0901;PO2=0902;' as BeforePO,
    --'T1=041;T2=036;T3=038;T4=033;' as AfterT,'P3=0103;P4=0104;DPs=0;DPp=0801;DPp1=0852;' as AfterP, 'PO1=01;PO2=02;' as AfterPO,
	null  as BeforeService,
	null  as AfterService
 FROM rvlfAdhocServices ad         
  inner join rvlfMAKDevices md on md.VehicleId=ad.VehicleId
 inner join rvlfVehicleType vt on vt.VehicleTypeId=md.SubTypeId   
 INNER JOIN rvlfUser U ON U.UserId = ad.ServicedBy            
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = md.VehicleId        
 WHERE md.OrganizationId = @bigOrganizationID AND (@tiServiceStatus IS NULL OR @tiServiceStatus='' OR 1 = @tiServiceStatus) 
 --AND (CONVERT(DATE, ad.ExecutionOn, 101) BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101))        
 AND cast(ad.ExecutionOn as date) BETWEEN  cast(@dtFromDate as date) AND cast(@dtToDate as date)
 AND (@bigFleetId IS NULL OR @bigFleetId='' OR fv.FleetId = @bigFleetId) AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR md.VehicleId = @bigVehicleId)        
 AND (@bigPlanId IS NULL OR @bigPlanId='' OR 0 = @bigPlanId) AND (@tiServiceType IS NULL OR @tiServiceType='' OR 6 = @tiServiceType)        
         
 ) AS t        
 ORDER BY RefNo        
 --(CASE WHEN t.Status = 'Pending' THEN 'A' WHEN t.Status = 'Completed' THEN 'D' WHEN t.Status = 'Skipped' THEN 'B' WHEN t.Status = 'Dismissed' THEN 'C' END)        
        
SET NOCOUNT OFF        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleServiceHistory_PG]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_GetVehicleServiceHistory_PG]           
 @bigOrganizationID bigint,          
 @bigFleetId bigint = NULL,          
 @bigVehicleId bigint = NULL, 
  @tiServiceStatus tinyint = NULL,    
 @dtFromDate datetime,          
 @dtToDate datetime,          
 @bigQueryingUser bigint = 0          
AS          
/**************************************************************************************/          
-- Name     : rvlf_sp_GetVehicleServiceHistory_PG 6,8,null,null,'5-jul-2016 10:41:00 AM','6-jul-2016 10:41:00 AM',420         
-- Description : To get the vehicle maintenance history details          
-- Author   : N.Ranjith
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--          : 12-Sep-2016  N.Ranjith Created Intial Version          
/**************************************************************************************/          
BEGIN          
SET NOCOUNT ON           
           
 DECLARE @Distance varchar(20)          
 DECLARE @ConversionFactor numeric (10,2) = 1.0        
 DECLARE @DefaultDateFormat INT = 0        
           
    SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,          
     @Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END,        
     @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           
           
 SELECT ROW_NUMBER() OVER (ORDER BY t.ExecutionDate) AS RefNo, t.* FROM           
 (          
 SELECT DISTINCT v.VehicleId, v.VehicleDescription, 'Planned' AS 'Type', mp.PlanId, mp.PlanName, CONVERT(varchar,vm.ExecutedOn,@DefaultDateFormat) AS 'ExecutionDate',vm.ExecutedOn AS 'ExecutionDateSort',              
 @Distance AS DistanceUnits, CASE WHEN vm.Status = 2 THEN 'N/A'           
  ELSE CONVERT(Varchar(6), (CASE WHEN vm.ServiceType = 2 THEN DATEDIFF(DD, vm.DueOnDate, vm.ExecutedOn) ELSE (CASE WHEN vm.OverdueDate IS NOT NULL THEN DATEDIFF(DD, vm.OverdueDate, vm.ExecutedOn) ELSE '0' END) END)) + ' days' END AS DelayBy,           
  mp.TotalPlannedCost,case when mp.TotalPlannedCost =0.00 then 'N/A' else cast(mp.TotalPlannedCost as varchar(10)) end as TotalPlannedCost1    
     
 , ISNULL(vm.ServiceCost, 0) AS ActualCost,          
 CASE WHEN vm.Status = 0 THEN 'Pending' WHEN vm.Status = 1 THEN 'Completed'           
   WHEN vm.Status = 2 THEN 'Skipped' WHEN vm.Status = 3 THEN 'Dismissed' END AS Status,          
    CASE WHEN vm.ServiceType = 0 THEN 'Engine Hours'       
    WHEN vm.ServiceType = 1 THEN 'Odometer'      
    WHEN vm.ServiceType = 2 THEN 'Time Based'          
    ELSE 'Concrete Mix Hours' END AS ServiceType,          
    CONVERT(Varchar(10), ISNULL(vm.EngineHrsOnClose, 0)) + ' hrs; ' +           
    CONVERT(Varchar(7), CONVERT(INT, ROUND((ISNULL(vm.OdometerReadingOnClose, 0) * @ConversionFactor), 0, 0)))          
    + ' ' + @Distance AS ReadingsOnClose,          
    vm.Comments, vm.RescheduledOn, vm.NearingPercentage, vm.ServiceDetailsId, vm.ModifiedDateTime          
 FROM rvlfVehicleMaintenanceService vm          
 INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId          
 INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId           
 INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId          
 INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId          
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId          
 WHERE mp.OrganizationId = @bigOrganizationID AND vm.Status <> 0 AND (@tiServiceStatus IS NULL OR @tiServiceStatus='' OR vm.Status = @tiServiceStatus) 
 AND (CONVERT(DATE, vm.ExecutedOn, 101) BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101))          
 AND (fv.FleetId = @bigFleetId) AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR vp.VehicleId = @bigVehicleId)           
 AND IsNearing = 1         
 
 UNION          
           
    SELECT DISTINCT v.VehicleId, v.VehicleDescription, 'Unplanned' AS 'Type', 0 AS PlanId, 'N/A' AS PlanName,          
 Convert(varchar,ad.ExecutionOn,@DefaultDateFormat) AS 'ExecutionDate',ad.ExecutionOn AS 'ExecutionDateSort', @Distance AS DistanceUnits, 'N/A' AS DelayBy, 0 AS TotalPlannedCost,'N/A'  AS TotalPlannedCost1,         
 ad.TotalServiceCost AS ActualCost, 'Completed' AS Status, 'N/A' AS ServiceType, '' AS ReadingsOnClose,          
 ad.Comments, NULL AS RescheduledOn, 0 AS NearingPercentage, ad.AdhocServiceId AS ServiceDetailsId,          
 ad.CreatedDateTime AS ModifiedDateTime          
 FROM rvlfAdhocServices ad          
 INNER JOIN rvlfVehicle v ON v.VehicleId = ad.VehicleId          
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId          
 WHERE v.OrganizationId = @bigOrganizationID  --AND (@tiServiceStatus='' OR 1 = 5)               
 AND (CONVERT(DATE, ad.ExecutionOn, 101) BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101))          
 AND (fv.FleetId = @bigFleetId) AND (@bigVehicleId IS NULL OR @bigVehicleId='' OR v.VehicleId = @bigVehicleId)  
 ) AS t          
 ORDER BY RefNo          
 --(CASE WHEN t.Status = 'Pending' THEN 'A' WHEN t.Status = 'Completed' THEN 'D' WHEN t.Status = 'Skipped' THEN 'B' WHEN t.Status = 'Dismissed' THEN 'C' END)          
          
SET NOCOUNT OFF          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehiclesInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehiclesInfo]    Script Date: 11/18/2011 12:36:56 ******/          
CREATE PROCEDURE [dbo].[rvlf_sp_GetVehiclesInfo]           
/*********************************************************************************************          
Stored Procedure Name : rvlf_sp_GetVehiclesInfo null,86,270,null,null        
Purpose     : Retrieve all vehicle information          
Created by    : Uma          
Created date   : 20-Jul-09          
Updated by    :           
Updated date   : 19-Aug-10 LK Changed the Vehicle Display Name to Vehicle Name          
      : 10-Nov-11 TSK Optimized query and removed Count(*)          
      : 15-Nov-11 Get vehiclesInfo by Fleet Based     
      : 11-Sep-13 Include Installed date field
*********************************************************************************************/                  
 @VehicleID int = null,          
 @bigOrganizationId bigint = null,          
 @bigUserId bigint = Null,          
 @bigFleetId bigint = NULL,      
 @bigVehicleID bigint = Null        
AS          
         
BEGIN           
     
  declare @Lang varchar(50)         
  select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigUserId      
         
   DECLARE @varGroupName AS Varchar(30)          
   DECLARE @varUserName AS Varchar(30)          
   DECLARE @bigUserGroupId bigint  
  -- declare @Tempvariable1 table(FleetID int)                   
   SELECT @varGroupName = ug.UserGroupName, @varUserName = u.UserName,@bigUserGroupId=ug.UserGroupId FROM rvlfUser u          
   INNER JOIN rvlfUserGroupAssignment uga ON uga.UserId = u.UserId          
   INNER JOIN rvlfUserGroup ug ON ug.UserGroupId = uga.UserGroupId          
   WHERE u.UserId = @bigUserId         
 -- INSERT INTO @Tempvariable1
	--select ft.FleetId from rvlfFleet ft inner join rvlfFleetUsers fu on ft.FleetId=fu.FleetId where fu.UserId=@bigUserId     
   IF(@varUserName = 'Administrator' OR @varGroupName = 'Angler Admin' OR @bigUserId = 0 OR @bigUserGroupId=35)          
 BEGIN          
          
  SET @bigUserId = NULL          
          
 END          
           
 IF @bigFleetId IS NULL OR @bigFleetId=''          
 SELECT TOP 1 @bigFleetId=fleetId FROM rvlfFleet WHERE OrganizationId=@bigOrganizationId Order By FleetId ASC          
           
   DECLARE @AssignStatus AS BIT = 1          
           
   IF @VehicleID IS NOT NULL AND @VehicleID <> 0          
   BEGIN          
             
    DECLARE @intNoOfGeozones AS INT = 0          
    DECLARE @intMaxGeozones AS INT = 0          
      --geozone not required for ADOR      
    --SELECT @intNoOfGeozones = COUNT(O.GeozoneNo) FROM rvlfOrganizationGeozone O          
    --INNER JOIN rvlfVehicleGeozone G on O.GeozoneNo = G.GeozoneNo          
    --where VehicleId = @VehicleID          
               
    --SELECT @intMaxGeozones = f.MaxGeozones FROM rvlfVehicleAssignment va          
    --INNER JOIN rvlfBoxSettings bs ON bs.BoxId = va.BoxId           
    --INNER JOIN rvlfFirmware f ON f.FwID = bs.FwID            
    --WHERE va.VehicleId = @VehicleID          
              
    IF(@intNoOfGeozones >= @intMaxGeozones)          
    BEGIN          
   SET @AssignStatus = 0          
    END          
             
   END          
   ELSE          
   BEGIN          
             
    DECLARE @tblVehicles TABLE (VehicleId bigint, NoOfGeozonesAssigned int, MaxGeozones int)             
            
   --    INSERT INTO @tblVehicles (VehicleId, NoOfGeozonesAssigned, MaxGeozones)          
   --  SELECT veh.VehicleId,           
   --(SELECT COUNT(OrganizationId) FROM rvlfOrganizationGeozone WHERE           
   --   GeozoneNo IN (SELECT vg.GeozoneNo FROM rvlfVehicleGeozone vg           
   --   WHERE vg.VehicleId = veh.VehicleId)),           
   --(SELECT f.MaxGeozones FROM rvlfVehicleAssignment va          
   --   INNER JOIN rvlfBoxSettings bs ON bs.BoxId = va.BoxId           
   --   INNER JOIN rvlfFirmware f ON f.FwID = bs.FwID            
   --   WHERE va.VehicleId = veh.VehicleId)          
   --  FROM rvlfVehicle veh          
   --  WHERE ((veh.VehicleId = COALESCE(@VehicleID, '') AND          
   --(veh.OrganizationId = COALESCE(@bigOrganizationId,'') AND @bigUserId IS NULL) OR          
   --((veh.VehicleId IN          
   -- (SELECT distinct fv.VehicleId FROM rvlfFleetUsers fu           
   -- INNER JOIN rvlfFleetVehicles fv ON fv.FleetId = fu.FleetId          
   -- WHERE fu.UserId = @bigUserId)))))          
            
   
     IF EXISTS (SELECT * FROM @tblVehicles WHERE NoOfGeozonesAssigned >= MaxGeozones)          
     BEGIN          
               
   SET @AssignStatus = 0          
               
END          
             
   END          
             
  SELECT DISTINCT REPLACE(veh.Email,';','; ') as Emails,          
      case when            
    (case when veh.Notify='true' then (case when @Lang='LanguageArNew' THEN N'??????' when @Lang='LanguageHindi' THEN N'????? ????'  else  'Notify' end) else '' end +                
    case when veh.Warning='true' then (case when @Lang='LanguageArNew' THEN N'?????' when @Lang='LanguageHindi' THEN N'???????'  else  'Warning' end) else '' end +             
    case when veh.Critical='true' then (case when @Lang='LanguageArNew' THEN N'????' when @Lang='LanguageHindi' THEN N'??????????'  else  'Critical' end) else '' end)='' 
    then (case when @Lang='LanguageArNew' THEN N'?? ?????' when @Lang='LanguageHindi' THEN N'??? ??????' else  'No Alarm' end) else            
    (case  when veh.Notify='true' then (case when (veh.Warning='true' or veh.Critical='true') then (case when @Lang='LanguageArNew' THEN N'??????;' when @Lang='LanguageHindi' THEN N'????? ????; 'else  'Notify;' end) else (case when @Lang='LanguageArNew' 



	THEN N'??????' when @Lang='LanguageHindi' THEN N'????? ????'  else  'Notify' end) end ) else '' end +                
    case when veh.Warning='true' then (case when veh.Critical='true' then (case when @Lang='LanguageArNew' THEN N'?????;' when @Lang='LanguageHindi' THEN N'???????;'  else  'Warning;' end) else (case when @Lang='LanguageArNew' THEN N'?????' when @Lang='La

nguageHindi' THEN N'???????'  else  'Warning' end) end ) else '' end +             
    case when veh.Critical='true' then (case when @Lang='LanguageArNew' THEN N'????' when @Lang='LanguageHindi' THEN N'??????????'  else  'Critical' end)  else '' end)            
    end as Severity, ISNULL(dbo.rvlf_fn_GetNotificationsList(4, veh.VehicleID, 1,1,0),'') as EmailList,           
  ISNULL(dbo.rvlf_fn_GetNotificationsList(4, veh.VehicleID, 0,1,0),'') as SMSList,          
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(4, veh.VehicleID, 1,0,1),''),',',', ') as EmailUserNameList,          
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(4, veh.VehicleID, 0,0,1),''),',',', ') as SMSUserNameList,          
 veh.VehicleDescription as VehicleName,@AssignStatus as 'AssignStatus',veh.location, veh.VehicleDescription AS DisplayName,
 case when m.MakeId = 0 THEN null else ISNULL(m.MakeId,null) END As MakeID,case when d.ModelId = 0 THEN null else 
 ISNULL(d.ModelId,null) END As ModelID,*,veh.CapacityUnits as TankCapacityUnits,veh.InstalledDate, veh.CapacityValue,isnull(veh.CapacityUnit,0) as CapacityUnit,
 isnull(veh.VehicleOwnership,1) as VehicleOwnership,veh.LifeSpan, veh.InsuranceExpiryDate, veh.LeaseExpiryDate, veh.IsUnderWarranty, veh.WarrantyExpiryDate, veh.IsDocumentsUploaded,md.NoofShifts,
 isnull(md.VFantype,0) as Fantype,MD.EConsumptionType,veh.VehicleTypeId,isnull(md.isAddParams,0) AS isAddParams,
 VehicleTypeName + case when (md.VFantype=null or md.VFantype=0) then '' else ' & ' +cast(md.VFantype as varchar(2)) +' Fibre Compactor' end  as VehicleTypeNameDet
  FROM rvlfVehicle veh          
  INNER JOIN rvlfFleetVehicles fv ON veh.VehicleId=fv.VehicleId          
  LEFT OUTER JOIN rvlfMake m ON veh.MakeId = m.MakeId          
  LEFT OUTER JOIN rvlfModel d ON veh.ModelId = d.ModelId          
  LEFT OUTER JOIN rvlfVehicleType t On veh.VehicleTypeId  = t.VehicleTypeId          
  INNER JOIN rvlfVehicleAssignment b on veh.VehicleId=b.VehicleId          
  inner join rvlfMAKDevices md on md.BoxId=b.BoxId
  --INNER JOIN rvlfTimeZones tz on veh.TimeZone = tz.TimeZoneID             
 WHERE               
  ((@bigFleetID IS NULL OR @bigFleetID = '' OR (fv.FleetId=@bigFleetId)) AND          
  ((@VehicleID is Null) or (veh.VehicleId = @VehicleID) or (@VehicleID = 0)) AND          
  ((@bigOrganizationId is Null) or (veh.OrganizationId = @bigOrganizationId))) --AND @bigUserId IS NULL) OR          
  --(veh.VehicleId IN          
  --  (SELECT distinct fv.VehicleId FROM rvlfFleetUsers fu           
  --  INNER JOIN rvlfFleetVehicles fv ON fv.FleetId = fu.FleetId          
  --  WHERE fu.UserId = @bigUserId))          
 ORDER BY veh.VehicleDescription                   
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehiclesInfoByUser]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetVehiclesInfoByUser]           
/*********************************************************************************************          
Stored Procedure Name : [rvlf_sp_GetVehiclesInfoByUser] null,1,502,null,null        
Purpose     : Retrieve all vehicle information          
Created by    : Uma          
Created date   : 20-Jul-09          
Updated by    :           
Updated date   : 19-Aug-10 LK Changed the Vehicle Display Name to Vehicle Name          
      : 10-Nov-11 TSK Optimized query and removed Count(*)          
      : 15-Nov-11 Get vehiclesInfo by Fleet Based     
      : 11-Sep-13 Include Installed date field
*********************************************************************************************/                  
 @VehicleID int = null,          
 @bigOrganizationId bigint = null,          
 @bigUserId bigint = Null,          
 @bigFleetId bigint = NULL,      
 @bigVehicleID bigint = Null        
AS          
         
BEGIN                
  declare @Lang varchar(50)         
  select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigUserId      
         
   DECLARE @varGroupName AS Varchar(30)          
   DECLARE @varUserName AS Varchar(30)          
   DECLARE @bigUserGroupId bigint  
   declare @Tempvariable1 table(FleetID int)                   
   SELECT @varGroupName = ug.UserGroupName, @varUserName = u.UserName,@bigUserGroupId=ug.UserGroupId FROM rvlfUser u          
   INNER JOIN rvlfUserGroupAssignment uga ON uga.UserId = u.UserId          
   INNER JOIN rvlfUserGroup ug ON ug.UserGroupId = uga.UserGroupId          
   WHERE u.UserId = @bigUserId  
          
  
   IF(@varUserName = 'Administrator' OR @varGroupName = 'Angler Admin' OR @bigUserId = 0 OR @bigUserGroupId=35)          
 BEGIN                    
  SET @bigUserId = NULL                    
 END             
   
  INSERT INTO @Tempvariable1
  select ft.FleetId from rvlfFleet ft inner join rvlfFleetUsers fu on ft.FleetId=fu.FleetId where (@bigUserId is null or @bigUserId='' or fu.UserId=@bigUserId)      
 --IF @bigFleetId IS NULL OR @bigFleetId=''          
 --SELECT TOP 1 @bigFleetId=fleetId FROM rvlfFleet WHERE OrganizationId=@bigOrganizationId Order By FleetId ASC          
                           
 Select distinct veh.vehicleId,veh.vehicledescription,b.boxid--,fv.fleetid
 FROM rvlfVehicle veh          
  INNER JOIN rvlfFleetVehicles fv ON veh.VehicleId=fv.VehicleId          
 -- LEFT OUTER JOIN rvlfMake m ON veh.MakeId = m.MakeId          
 -- LEFT OUTER JOIN rvlfModel d ON veh.ModelId = d.ModelId          
 -- LEFT OUTER JOIN rvlfVehicleType t On veh.VehicleTypeId  = t.VehicleTypeId          
  INNER JOIN rvlfVehicleAssignment b on veh.VehicleId=b.VehicleId                 
 WHERE               
  fv.FleetId in (select FleetId from @Tempvariable1) AND          
         
  ((@bigOrganizationId is Null) or (veh.OrganizationId = @bigOrganizationId)) --AND @bigUserId IS NULL) OR          
                       
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleStatistics]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetVehicleStatistics]  
 @bigOrganizationID bigint = null
AS  
/******************************************************************************/  
-- Name     : rvlf_sp_GetVehicleStatistics  
-- Description : To insert / update the organization  
-- Author   : S. Jeyanthi.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--          : 15-Nov-2010 SJ Created Intial Version   
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
   -- Checks whether to insert or update by checking the organization ID  
   IF @bigOrganizationID IS NOT NULL  
    BEGIN       
     
     --INCLUDED BY JEYANTHI FOR BULK DEVICE AND VEHICLE CREATION 
     DECLARE @NoOfVehicles bigint=(SELECT NoOfVehicles FROM rvlfOrganization WHERE OrganizationId =  @bigOrganizationID)  
     DECLARE @NoOfVehiclesAvailable bigint=(SELECT Count(VehicleId)  FROM rvlfVehicle WHERE OrganizationId =  @bigOrganizationID)  
     DECLARE @NoOfVehiclesPending bigint=ISNULL(@NoOfVehicles,0)-ISNULL(@NoOfVehiclesAvailable,0)
     
     SELECT @bigOrganizationID  OrganizationID,ISNULL(@NoOfVehicles,0)NoOfVehicles,
     ISNULL(@NoOfVehiclesAvailable,0) NoOfVehiclesAvailable,  ISNULL(@NoOfVehiclesPending,0)NoOfVehiclesPending
     --END
	END
 SET NOCOUNT OFF  
END  




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleSummaryDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
                           
CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicleSummaryDetails]    
@bigFleetID BIGINT = null,                      
@intBoxID VARCHAR(MAX) = null,                      
@dtStartDate DATETIME = null,                      
@dtEndDate DATETIME = null,                      
@bigOrganizationID BIGINT = null,                      
@bigQueryingUser BIGINT = null                      
AS                      
/******************************************************************************************************************/                              
-- [rvlf_sp_GetVehicleSummaryDetails] 337,null,'09/06/2014 08:00:00 AM','10/06/2014 08:00:00 PM',190,502    
-- Description : To get the overall summary details of the vehicles                      
-- Author  : Sakthi                              
-- Company  : Angler Technologies                              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                              
--    : 04-Jul-2013 SS Created Intial Version                             
/******************************************************************************************************************/                      
BEGIN                      
SET NOCOUNT ON                      
                      
 DECLARE @Lang VARCHAR(50)                      
 SELECT @Lang=isnull(Lang,'LanguageEn') FROM dbo.rvlfUserPreferences WHERE UserId = @bigQueryingUser                        
                               
 DECLARE @dtFDate DATETIME =@dtStartDate                            
 DECLARE @dtEDate DATETIME =@dtEndDate                            
 IF @bigFleetID IS NULL                              
 BEGIN                              
  SELECT @bigFleetID=FleetID FROM dbo.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)                            
 DECLARE @DefaultDateFormat INT = 0;                            
 DECLARE @Hours VARCHAR(MAX) = 0                      
 DECLARE @Minutes INT = 0                      
 DECLARE @ToDate DATETIME = NULL                       
 DECLARE @FromDate DATETIME = NULL                      
                      
 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,                      
 @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)                              
 FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz                              
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser                             
                         
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                              
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                        
                      
 DECLARE @tblTripDetailsForTD TABLE(                              
   [TripId] [bigint]IDENTITY(1,1) NOT NULL,                              
   [BoxId] [int] NOT NULL,                              
   [StartDate] [datetime] NOT NULL,                              
   [EndDate] [datetime] NULL,                              
   [OdometerStart] [bigint] NOT NULL,                              
   [OdometerEnd] [bigint] NULL,                              
   [IsTripClosed] [bit] NULL,                              
   [IdlingDuration] [int] NULL,                              
   [StopTime] [int] NULL,                              
   [StartAddress] nvarchar(300) NULL,              
   [EndAddress] nvarchar(300) NULL,                              
   [Speed] int NULL,                              
   [RunningTime] int null,                              
   StartLat numeric(10,6),                              
   StartLong numeric(10,6),                              
   StopLat numeric(10,6),                              
   StopLong numeric(10,6),                      
   ExtremeBraking INT NULL,  HarshAcceleration INT NULL                      
  )                              
                                
  DECLARE @TBLSTART 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 @TBLSTOP TABLE                              
  (                          
   Boxid int,                              
   StopTime datetime,                              
   OdoEnd bigint,                              
   EndAddress varchar(300),                              
   tripId int,                              
   Lat numeric(10,6),                              
   Long numeric(10,6),                              
   IsTripCompleted bit                              
  )                               
                               
  DECLARE @intDuration int                              
  DECLARE @dtOriginDateTime datetime                              
  DECLARE @bigOdoMeterReading int                              
  DECLARE @bitIgnitionStatus bit                              
  DECLARE @vcStreetAddress nvarchar(250)                              
  DECLARE @tiBoxMsgInTypeId tinyint                              
  DECLARE @bigTripID bigint                              
  DECLARE @intIterator int                              
  DECLARE @canShowFuelMessage bit = 0                              
                                
  IF EXISTS (SELECT PackageOrgId  FROM dbo.rvlfPackageOperations r                              
   INNER JOIN dbo.rvlfOrganizationPackage p ON r.PackageId = p.PackageId                              
   INNER JOIN dbo.rvlfOrganization g ON p.OrganizationID = g.OrganizationId                              
   WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)                              
    BEGIN                              
     SET @canShowFuelMessage = 1                              
    END                              
                               
  DECLARE @tblMessageForProcessingTrip TABLE (                              
   [BoxId] [bigint] NOT NULL,                      
   [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 @tblBoxes TABLE (BoxID int)                              
            
  INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM dbo.rvlfVehicleAssignment va                               
    INNER JOIN dbo.rvlfVehicle v ON va.VehicleId = v.VehicleId                              
    INNER JOIN dbo.rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                              
    WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' or                       
    BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID                              
    ORDER BY BoxId                               
                               
  DECLARE @intBoxLooping int                              
                                
  SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes                              
  WHILE @intBoxLooping IS NOT NULL                              
    BEGIN                               
     -- GET THE MSGS FOR THE BOXID                              
     DELETE FROM @tblMessageForProcessingTrip                                   
	INSERT INTO @tblMessageForProcessingTrip(BoxId,OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,OdoMeter,Lat,Long)                              
        SELECT h.BoxId,h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,  
        CASE WHEN @bigOrganizationID IN (0) AND BoxMsgInTypeId=2 AND   
        CustomProp like 'SENSOR_NUM=2;%' THEN 1 ELSE CAST(SUBSTRING(sensormask,6,1) as bit) END,                              
        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 dbo.rvlfMsgInHst H LEFT OUTER JOIN dbo.rvlfLandmark L ON L.LandmarkID=H.LandMarkID                                    
        WHERE h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                                        
        AND h.BoxID = @intBoxLooping ORDER BY h.origindatetime ASC                               
                                      
    -- GET THE IGNITION ON DETAILS                              
    DELETE FROM @TBLSTART                       
    INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                              
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                               
     FROM @tblMessageForProcessingTrip                                     
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                               
      AND BoxMsgInTypeId IN(2)                              
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                               
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                              
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                               
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                                
      AND Ignition=1                              
      AND CustomProp LIKE case when @bigOrganizationID=0 then '%SENSOR_NUM=2%' else '%SENSOR_NUM=3%'end                  
                                     
                                   
    --GET THE IGNITION OFF DETAILS                                 
    DELETE FROM @TBLSTOP                               
    INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)                              
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                                  
     FROM @tblMessageForProcessingTrip                                
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                               
      AND BoxMsgInTypeId IN(3)                              
      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                               
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                              
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                               
       WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                                
      AND CustomProp LIKE case when @bigOrganizationID=0 then '%SENSOR_NUM=2%' else '%SENSOR_NUM=3%'end                  
                                  
    --CHECK THE ONGOING TRIPS                               
    IF ((SELECT TOP 1 BoxMsgInTypeId FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) ORDER BY OriginDateTime DESC)=2)                              
     BEGIN                              
      INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                              
       SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                               
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE case when @bigOrganizationID=0 then '%SENSOR_NUM=2%' else '%SENSOR_NUM=3%'end ORDER BY OriginDateTime DESC                                   
     IF EXISTS(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                              
        AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                              
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE case when @bigOrganizationID=0 then '%SENSOR_NUM=2%' else '%SENSOR_NUM=3%'end ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC)                             
  
   
       
        
         
      BEGIN                                      
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long,IsTripCompleted)                              
        --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,OdoMeter,Address,Lat,Long,0                               
        SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long,0                               
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                              
         AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                              
         FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE case when @bigOrganizationID=0 then '%SENSOR_NUM=2%' else '%SENSOR_NUM=3%'end ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC                             
 
      END                               
     ELSE                              
      BEGIN                              
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)                              
        --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                                       
        SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                                       
      END                                
     END                              
                                       
    --PREPARE THE TRIPS AND DETAILS                                  
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )                               
    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 @TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                                  
                                    
      IF @DTSTOPSTART IS NOT NULL                                       
       UPDATE top(1) @TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART                               
                                    
      SET @DTSTOPSTART=@DTSTART                               
      SET @DTEND=NULL                              
      SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART                               
                                    
      UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART                               
      UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND     
            
                                   
      UPDATE top(1) @TBLSTART SET Speed =(SELECT MAX(SPEED) FROM @tblMessageForProcessingTrip     
      WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),                              
      idling=(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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9                               
        AND CustomProp NOT LIKE '%Idling:0;%'),     
        Running=DATEDIFF(S,@DTSTART,@DTEND)                   
       WHERE tripId=@INC AND StartTime=@DTSTART                          
                    
                            
                                     
      SET @INC =@INC +1                              
                                    
      SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART                              
                                    
     END                               
                                         
    --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME                              
    UPDATE @TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN     
    (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END               
                        
     WHERE Running IS NOT NULL                              
                 
    --INSERT THE DETAILS IN THE MASTER TABLE          
    --rvlf_fn_GetIdlingTime_MFC used for get from trip/ignition start to idling end instead of idling start    
    INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,                              
     OdometerEnd,IdlingDuration,Speed, IsTripClosed,StopTime,RunningTime,StartLat,StartLong,StopLat,StopLong)                               
        
    SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,    
    case when  @bigOrganizationID=0 then dbo.rvlf_fn_GetIdlingTime_MFC(s.BoxId,S.StartTime,ST.StopTime) else S.idling end,    
     S.Speed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,    
     S.StopInterval,    
     case when @bigOrganizationID=0 then      
     CASE WHEN ISNULL(DATEDIFF(S,S.StartTime,ST.StopTime),0)< ISNULL(dbo.rvlf_fn_GetIdlingTime_MFC(s.BoxId,S.StartTime,ST.StopTime),0) THEN     
    (CEILING(CAST((dbo.rvlf_fn_GetIdlingTime_MFC(s.BoxId,S.StartTime,ST.StopTime)/(60*1.00))AS NUMERIC(8,2)))*60) ELSE DATEDIFF(S,S.StartTime,ST.StopTime) END    
      else Running end    
     ,S.Lat,S.Long,ST.Lat,ST.Long                         
      FROM @TBLSTART S                              
       INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId                                        
                      
   UPDATE @tblTripDetailsForTD SET ExtremeBraking=    
   (SELECT COUNT(BoxId) FROM @tblMessageForProcessingTrip as a WHERE BoxMsgInTypeId IN (14,15) and a.BoxId=BoxId and a.OriginDateTime between StartDate and EndDate)     
   WHERE BoxId=@intBoxLooping                      
   UPDATE @tblTripDetailsForTD SET HarshAcceleration=    
   (SELECT COUNT(BoxId) FROM @tblMessageForProcessingTrip as a WHERE BoxMsgInTypeId IN (16,17)and a.BoxId=BoxId and a.OriginDateTime between StartDate and EndDate)      WHERE BoxId=@intBoxLooping                      
                      
   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping                              
                                 
   UPDATE @tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM @tblTripDetailsForTD)           
  
    
   END                             
       
       
       
 SELECT Res.*,CEILING(ROUND(ABS(Res.OdometerEnd - Res.[OdometerStartSt]),0,0)) AS [DistanceTotal],  Distancetripwise as  Distance,                   
 (SELECT TOP 1 ISNULL(StartAddress,'NA') FROM @tblTripDetailsForTD ab WHERE ab.BoxId=Res.BoxId AND StartDate=Res.StartDateSort) AS StartAddress,                      
 (SELECT TOP 1 ISNULL(EndAddress,'NA') FROM @tblTripDetailsForTD ab WHERE ab.BoxId=Res.BoxId AND EndDate=Res.EndDateSort) AS EndAddress                      
 FROM                      
 (SELECT tds.BoxId,v.VehicleId,v.VehicleDescription,   SUM(OdometerEnd-OdometerStart) as Distancetripwise,                   
 StartDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,MIN(StartDate)),EndDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,                  
 @DefaultDateFormat,MAX(EndDate)),                                
 StartDateSort = MIN(StartDate),EndDateSort = MAX(EndDate),                      
 CAST(CAST(ROUND(CAST((ABS(ISNULL(MIN(OdometerStart), 0)) * @ConversionFactor) as varchar(20)),0,0) AS BIGINT) AS VARCHAR)                      
 --CAST(CEILING(ABS(MIN(OdometerStart)* @ConversionFactor)) AS VARCHAR)                      
 +' - '+                      
 CAST(CAST(ROUND(CAST((ABS(ISNULL(MAX(OdometerEnd), 0)) * @ConversionFactor) as varchar(20)),0,0) AS BIGINT) AS VARCHAR) AS [OdometerStart],                      
 --CAST(CEILING(ABS(MAX(OdometerEnd) * @ConversionFactor)) AS VARCHAR) AS [OdometerStart],                      
 (ABS(ISNULL(MIN(OdometerStart), 0)) * @ConversionFactor) [OdometerStartSt],                      
 (ABS(ISNULL(MAX(OdometerEnd), 0)) * @ConversionFactor) [OdometerEnd],                      
 --MIN(OdometerStart) [OdometerStartSt],MAX(OdometerEnd) [OdometerEnd],                     
 dbo.rvlf_fn_GetTimeFromSeconds(SUM(ISNULL(RunningTime,0))) [TotDuration],                      
 dbo.rvlf_fn_GetTimeFromSeconds(SUM(ISNULL(IdlingDuration,0))) [IdlingDuration],                      
 dbo.rvlf_fn_GetTimeFromSeconds(SUM(ISNULL(StopTime,0))) [StopTime],                      
 --(CEILING(MAX(OdometerEnd) * @ConversionFactor)-CEILING(MIN(OdometerStart) * @ConversionFactor)) [Distance],                      
 MAX(Speed) [Speed],                      
 @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,                      
 CAST(ISNULL((SUM(ISNULL(IdlingDuration,0)) *1.00) / CASE WHEN(ISNULL(SUM(ISNULL(RunningTime,0)) ,0)*1.00)=0 THEN 1 ELSE                       
 (ISNULL(SUM(ISNULL(RunningTime,0)) ,0)* 1.00) END *100,0) AS NUMERIC(10,2)) [IdlingPercentage],                      
 sum(ExtremeBraking) [ExtremeBraking],sum(HarshAcceleration) [HarshAcceleration],                      
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) AS PasStartDate,                      
 Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) AS PasEndDate,                      
 dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()) AS PasGeneratedDate                      
 FROM @tblTripDetailsForTD tds INNER JOIN rvlfVehicleAssignment va ON va.BoxId=tds.BoxId AND tds.IsTripClosed=1                       
 INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId GROUP BY tds.BoxId,v.VehicleId,v.VehicleDescription) Res      
     
            
SET NOCOUNT OFF                      
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleSummaryDetails_test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
                       
CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicleSummaryDetails_test]
@bigFleetID BIGINT = null,                  
@intBoxID VARCHAR(MAX) = null,                  
@dtStartDate DATETIME = null,                  
@dtEndDate DATETIME = null,                  
@bigOrganizationID BIGINT = null,                  
@bigQueryingUser BIGINT = null                  
AS                  
/******************************************************************************************************************/                          
-- rvlf_sp_GetVehicleSummaryDetails_test 337,4065,'03/03/2014 08:00:00 AM','03/06/2014 08:00:00 PM',190,502
-- Description : To get the overall summary details of the vehicles                  
-- Author  : Sakthi                          
-- Company  : Angler Technologies                          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                          
--    : 04-Jul-2013 SS Created Intial Version                         
/******************************************************************************************************************/                  
BEGIN                  
SET NOCOUNT ON                  
                  
 DECLARE @Lang VARCHAR(50)                  
 SELECT @Lang=isnull(Lang,'LanguageEn') FROM dbo.rvlfUserPreferences WHERE UserId = @bigQueryingUser                    
                           
 DECLARE @dtFDate DATETIME =@dtStartDate                        
 DECLARE @dtEDate DATETIME =@dtEndDate                        
 IF @bigFleetID IS NULL                          
 BEGIN                          
  SELECT @bigFleetID=FleetID FROM dbo.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)                        
 DECLARE @DefaultDateFormat INT = 0;                        
 DECLARE @Hours VARCHAR(MAX) = 0                  
 DECLARE @Minutes INT = 0                  
 DECLARE @ToDate DATETIME = NULL                   
 DECLARE @FromDate DATETIME = NULL                  
                  
 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,                  
 @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)= 0 then 106 else up.DefaultDateFormat end)                          
 FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz                          
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser                         
                     
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                          
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                    
                  
 DECLARE @tblTripDetailsForTD TABLE(                          
   [TripId] [bigint]IDENTITY(1,1) NOT NULL,                          
   [BoxId] [int] NOT NULL,                          
   [StartDate] [datetime] NOT NULL,                          
   [EndDate] [datetime] NULL,                          
   [OdometerStart] [bigint] NOT NULL,                          
   [OdometerEnd] [bigint] NULL,                          
   [IsTripClosed] [bit] NULL,                          
   [IdlingDuration] [int] NULL,                          
   [StopTime] [int] NULL,                          
   [StartAddress] nvarchar(300) NULL,          
   [EndAddress] nvarchar(300) NULL,                          
   [Speed] int NULL,                          
   [RunningTime] int null,                          
   StartLat numeric(10,6),                          
   StartLong numeric(10,6),                          
   StopLat numeric(10,6),                          
   StopLong numeric(10,6),                  
   ExtremeBraking INT NULL,  HarshAcceleration INT NULL                  
  )                          
                            
  DECLARE @TBLSTART 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 @TBLSTOP TABLE                          
  (                      
   Boxid int,                          
   StopTime datetime,                          
   OdoEnd bigint,                          
   EndAddress varchar(300),                          
   tripId int,                          
   Lat numeric(10,6),                          
   Long numeric(10,6),                          
   IsTripCompleted bit                          
  )                           
                           
  DECLARE @intDuration int                          
  DECLARE @dtOriginDateTime datetime                          
  DECLARE @bigOdoMeterReading int                          
  DECLARE @bitIgnitionStatus bit                          
  DECLARE @vcStreetAddress nvarchar(250)                          
  DECLARE @tiBoxMsgInTypeId tinyint                          
  DECLARE @bigTripID bigint                          
  DECLARE @intIterator int                          
  DECLARE @canShowFuelMessage bit = 0                          
                            
  IF EXISTS (SELECT PackageOrgId  FROM dbo.rvlfPackageOperations r                          
   INNER JOIN dbo.rvlfOrganizationPackage p ON r.PackageId = p.PackageId                          
   INNER JOIN dbo.rvlfOrganization g ON p.OrganizationID = g.OrganizationId                          
   WHERE p.IsActive = 1 AND r.OperationID = 95 AND g.OrganizationId = @bigOrganizationID)                          
    BEGIN                          
     SET @canShowFuelMessage = 1                          
    END                          
                           
  DECLARE @tblMessageForProcessingTrip TABLE (                          
   [BoxId] [bigint] NOT NULL,                  
   [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 @tblBoxes TABLE (BoxID int)                          
                             
  INSERT INTO @tblBoxes (BoxID) SELECT va.BoxID FROM dbo.rvlfVehicleAssignment va                           
    INNER JOIN dbo.rvlfVehicle v ON va.VehicleId = v.VehicleId                          
    INNER JOIN dbo.rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                          
    WHERE fv.FleetId = @bigFleetID AND (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' or                   
    BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))) AND V.OrganizationId=@bigOrganizationID                          
    ORDER BY BoxId                           
                           
  DECLARE @intBoxLooping int                          
                            
  SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes                          
  WHILE @intBoxLooping IS NOT NULL                          
    BEGIN                           
     -- GET THE MSGS FOR THE BOXID                          
     DELETE FROM @tblMessageForProcessingTrip                               
INSERT INTO @tblMessageForProcessingTrip(BoxId,OriginDateTime,CustomProp,Speed,BoxMsgInTypeId,Ignition,Address,OdoMeter,Lat,Long)                          
        SELECT h.BoxId,h.OriginDateTime,h.CustomProp,Speed,H.BoxMsgInTypeId,
          CASE WHEN @bigOrganizationID IN (23,190) AND BoxMsgInTypeId=2 AND CustomProp like 'SENSOR_NUM=2;%' THEN 1 ELSE CAST(SUBSTRING(sensormask,6,1) as bit) END,                          
        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 dbo.rvlfMsgInHst H LEFT OUTER JOIN dbo.rvlfLandmark L ON L.LandmarkID=H.LandMarkID                                
        WHERE h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                                    
        AND h.BoxID = @intBoxLooping ORDER BY h.origindatetime ASC                           
                                  
    -- GET THE IGNITION ON DETAILS                          
    DELETE FROM @TBLSTART                   
    INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                          
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                           
     FROM @tblMessageForProcessingTrip                                 
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                           
      AND BoxMsgInTypeId IN(2)                          
      AND OriginDateTime >=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                           
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                          
      AND OriginDateTime <(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                           
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                            
      AND Ignition=1                          
      AND CustomProp LIKE case when @bigOrganizationID=190 then '%SENSOR_NUM=2%' else '%SENSOR_NUM=3%'end              
                                 
                               
    --GET THE IGNITION OFF DETAILS                             
    DELETE FROM @TBLSTOP                           
    INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long)                          
    SELECT @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                              
     FROM @tblMessageForProcessingTrip                            
     WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate                           
      AND BoxMsgInTypeId IN(3)                          
      AND OriginDateTime >(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                           
       WHERE OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =2 ORDER BY OriginDateTime)                          
      AND OriginDateTime <=(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip                           
       WHERE  OriginDateTime BETWEEN @dtStartDate AND @dtEndDate AND BoxMsgInTypeId =3 ORDER BY OriginDateTime DESC)                            
      AND CustomProp LIKE case when @bigOrganizationID=190 then '%SENSOR_NUM=2%' else '%SENSOR_NUM=3%'end              
                              
    --CHECK THE ONGOING TRIPS                           
    IF ((SELECT TOP 1 BoxMsgInTypeId FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId IN(2,3) ORDER BY OriginDateTime DESC)=2)                          
     BEGIN                          
      INSERT INTO @TBLSTART (Boxid,StartTime,OdoStart,StartAddress,Lat,Long)                          
       SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long                           
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE case when @bigOrganizationID=190 then '%SENSOR_NUM=2%' else '%SENSOR_NUM=3%'end ORDER BY OriginDateTime DESC                               
     IF EXISTS(SELECT TOP 1 OriginDateTime FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                          
        AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                          
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE case when @bigOrganizationID=190 then '%SENSOR_NUM=2%' else '%SENSOR_NUM=3%'end ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC)                            
   
    
     
      BEGIN                                  
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,Lat,Long,IsTripCompleted)                          
        --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,OdoMeter,Address,Lat,Long,0                           
        SELECT TOP 1 @intBoxLooping,OriginDateTime,OdoMeter,Address,Lat,Long,0                           
        FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId NOT IN(19)                          
         AND ORIGINDATETIME>=(SELECT TOP 1 OriginDateTime                          
         FROM @tblMessageForProcessingTrip WHERE BoxMsgInTypeId =2 AND CustomProp LIKE case when @bigOrganizationID=190 then '%SENSOR_NUM=2%' else '%SENSOR_NUM=3%'end ORDER BY OriginDateTime DESC ) ORDER BY OriginDateTime DESC                          
      END                           
     ELSE                          
      BEGIN                          
       INSERT INTO @TBLSTOP (Boxid,StopTime,OdoEnd,EndAddress,IsTripCompleted)                          
        --SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                                   
        SELECT TOP 1 @intBoxLooping,CASE WHEN @dtEndDate>GETUTCDATE() THEN GETUTCDATE() ELSE @dtEndDate END,NULL,'Ongoing',0                                   
      END                            
     END                          
                                   
    --PREPARE THE TRIPS AND DETAILS                              
    DECLARE @LOOP BIGINT =(SELECT MIN(Processid) FROM @TBLSTART )                           
    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 @TBLSTART WHERE Processid >=@LOOP AND (@DTEND IS NULL OR StartTime >@DTEND)                              
                                
      IF @DTSTOPSTART IS NOT NULL                                   
       UPDATE top(1) @TBLSTART SET StopInterval =ISNULL(DATEDIFF(S,@DTEND,@DTSTART),0) WHERE StartTime=@DTSTOPSTART                           
                                
      SET @DTSTOPSTART=@DTSTART                           
      SET @DTEND=NULL                          
      SELECT TOP 1 @DTEND=StopTime   FROM @TBLSTOP WHERE StopTime >@DTSTART                           
                                
      UPDATE top(1) @TBLSTART SET tripId=@INC WHERE StartTime =@DTSTART                           
      UPDATE top(1) @TBLSTOP SET tripId=@INC WHERE StopTime =@DTEND 
        
                               
      UPDATE top(1) @TBLSTART SET Speed =(SELECT MAX(SPEED) FROM @tblMessageForProcessingTrip 
      WHERE OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping),                          
      idling=(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 OriginDateTime BETWEEN @DTSTART AND @DTEND AND Boxid =@intBoxLooping AND BoxMsgInTypeId =9                           
        AND CustomProp NOT LIKE '%Idling:0;%'), 
        Running=DATEDIFF(S,@DTSTART,@DTEND)               
       WHERE tripId=@INC AND StartTime=@DTSTART                      
                
                        
                                 
      SET @INC =@INC +1                          
                                
      SELECT @LOOP =MIN(Processid) FROM @TBLSTART WHERE Processid >@LOOP  AND StartTime >@DTSTART                          
                                
     END                           
                                     
    --CHECK AND UPDATE THE RUNNING TIME GREATER THEN IDLING TIME                          
    UPDATE @TBLSTART SET Running =CASE WHEN ISNULL(Running,0)< ISNULL(idling,0) THEN 
    (CEILING(CAST((idling/(60*1.00))AS NUMERIC(8,2)))*60) ELSE Running END           
                    
     WHERE Running IS NOT NULL                          
             
    --INSERT THE DETAILS IN THE MASTER TABLE      
    --rvlf_fn_GetIdlingTime_MFC used for get from trip/ignition start to idling end instead of idling start
    INSERT INTO @tblTripDetailsForTD(BoxId,StartDate,EndDate,StartAddress,EndAddress,OdometerStart,                          
     OdometerEnd,IdlingDuration,Speed, IsTripClosed,StopTime,RunningTime,StartLat,StartLong,StopLat,StopLong)                           
    
    SELECT S.Boxid,S.StartTime,ST.StopTime,S.StartAddress,ST.EndAddress,S.OdoStart,ST.OdoEnd,
    case when  @bigOrganizationID=190 then dbo.rvlf_fn_GetIdlingTime_MFC(s.BoxId,S.StartTime,ST.StopTime) else S.idling end,
     S.Speed,CASE WHEN ST.IsTripCompleted =0 THEN 0 ELSE 1 END,
     S.StopInterval,
     case when @bigOrganizationID=190 then  
     CASE WHEN ISNULL(DATEDIFF(S,S.StartTime,ST.StopTime),0)< ISNULL(dbo.rvlf_fn_GetIdlingTime_MFC(s.BoxId,S.StartTime,ST.StopTime),0) THEN 
    (CEILING(CAST((dbo.rvlf_fn_GetIdlingTime_MFC(s.BoxId,S.StartTime,ST.StopTime)/(60*1.00))AS NUMERIC(8,2)))*60) ELSE DATEDIFF(S,S.StartTime,ST.StopTime) END
      else Running end
     ,S.Lat,S.Long,ST.Lat,ST.Long                          
      FROM @TBLSTART S                          
       INNER JOIN @TBLSTOP ST ON ST.tripId=S.tripId                                    
                  
   UPDATE @tblTripDetailsForTD SET ExtremeBraking=
   (SELECT COUNT(BoxId) FROM @tblMessageForProcessingTrip as a WHERE BoxMsgInTypeId IN (14,15) and a.BoxId=BoxId and a.OriginDateTime between StartDate and EndDate) 
   WHERE BoxId=@intBoxLooping                  
   UPDATE @tblTripDetailsForTD SET HarshAcceleration=
   (SELECT COUNT(BoxId) FROM @tblMessageForProcessingTrip as a WHERE BoxMsgInTypeId IN (16,17)and a.BoxId=BoxId and a.OriginDateTime between StartDate and EndDate) 
   WHERE BoxId=@intBoxLooping                  
                  
   SELECT @intBoxLooping = MIN(BoxID) from @tblBoxes WHERE BoxID > @intBoxLooping                          
                             
   UPDATE @tblTripDetailsForTD SET StopTime =CASE WHEN IsTripClosed =0 THEN 0 ELSE DATEDIFF(ss, EndDate,CASE WHEN GETUTCDATE()< @dtEndDate THEN  GETUTCDATE() ELSE @dtEndDate END ) END WHERE TripId=(SELECT MAX(TripId) FROM @tblTripDetailsForTD)           
   END                         
   
   
   
 SELECT Res.*,CEILING(ROUND(ABS(Res.OdometerEnd - Res.[OdometerStartSt]),0,0)) AS [DistanceTotal],  Distancetripwise as  Distance,               
 (SELECT TOP 1 ISNULL(StartAddress,'NA') FROM @tblTripDetailsForTD ab WHERE ab.BoxId=Res.BoxId AND StartDate=Res.StartDateSort) AS StartAddress,                  
 (SELECT TOP 1 ISNULL(EndAddress,'NA') FROM @tblTripDetailsForTD ab WHERE ab.BoxId=Res.BoxId AND EndDate=Res.EndDateSort) AS EndAddress                  
 FROM                  
 (SELECT tds.BoxId,v.VehicleId,v.VehicleDescription,   SUM(OdometerEnd-OdometerStart) as Distancetripwise,               
 StartDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,MIN(StartDate)),EndDate = dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,              
 @DefaultDateFormat,MAX(EndDate)),                            
 StartDateSort = MIN(StartDate),EndDateSort = MAX(EndDate),                  
 CAST(CAST(ROUND(CAST((ABS(ISNULL(MIN(OdometerStart), 0)) * @ConversionFactor) as varchar(20)),0,0) AS BIGINT) AS VARCHAR)                  
 --CAST(CEILING(ABS(MIN(OdometerStart)* @ConversionFactor)) AS VARCHAR)                  
 +' - '+                  
 CAST(CAST(ROUND(CAST((ABS(ISNULL(MAX(OdometerEnd), 0)) * @ConversionFactor) as varchar(20)),0,0) AS BIGINT) AS VARCHAR) AS [OdometerStart],                  
 --CAST(CEILING(ABS(MAX(OdometerEnd) * @ConversionFactor)) AS VARCHAR) AS [OdometerStart],                  
 (ABS(ISNULL(MIN(OdometerStart), 0)) * @ConversionFactor) [OdometerStartSt],                  
 (ABS(ISNULL(MAX(OdometerEnd), 0)) * @ConversionFactor) [OdometerEnd],                  
 --MIN(OdometerStart) [OdometerStartSt],MAX(OdometerEnd) [OdometerEnd],                 
 dbo.rvlf_fn_GetTimeFromSeconds(SUM(ISNULL(RunningTime,0))) [TotDuration],                  
 dbo.rvlf_fn_GetTimeFromSeconds(SUM(ISNULL(IdlingDuration,0))) [IdlingDuration],                  
 dbo.rvlf_fn_GetTimeFromSeconds(SUM(ISNULL(StopTime,0))) [StopTime],                  
 --(CEILING(MAX(OdometerEnd) * @ConversionFactor)-CEILING(MIN(OdometerStart) * @ConversionFactor)) [Distance],                  
 MAX(Speed) [Speed],                  
 @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,                  
 CAST(ISNULL((SUM(ISNULL(IdlingDuration,0)) *1.00) / CASE WHEN(ISNULL(SUM(ISNULL(RunningTime,0)) ,0)*1.00)=0 THEN 1 ELSE                   
 (ISNULL(SUM(ISNULL(RunningTime,0)) ,0)* 1.00) END *100,0) AS NUMERIC(10,2)) [Idlingpercentage],                  
 sum(ExtremeBraking) [ExtremeBraking],sum(HarshAcceleration) [HarshAcceleration],                  
 Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) AS PasStartDate,                  
 Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) AS PasEndDate,                  
 dbo.rvlf_fn_DayLightSavings(@dtFDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()) AS PasGenerateddate                  
 FROM @tblTripDetailsForTD tds INNER JOIN rvlfVehicleAssignment va ON va.BoxId=tds.BoxId AND tds.IsTripClosed=1                   
 INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId GROUP BY tds.BoxId,v.VehicleId,v.VehicleDescription) Res  
 
        
SET NOCOUNT OFF                  
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleTemperatureDetails_HDF]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicleTemperatureDetails_HDF]
@OrgId INT = 121
AS
/******************************************************************************/      
-- Name				: rvlf_sp_GetVehicleTemperatureDetails_HDF
-- Description		: To get the vehicles details with temperature values
-- Author				: S Sakthi Gopinath
-- Created Date	: 08-Jul-2014
-- Company			: Angler Technologies      
-- History				: <<Date(dd-MON-yyyy)>> Initial Reason      
/******************************************************************************/    
BEGIN
SET NOCOUNT ON

	--SELECT 
--dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID, h.BoxId, h.MessageInID, h.OriginDateTime) as MessageDetails,
--b.* FROM rvlfBoxId b 
--INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId
--INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId
--INNER JOIN rvlfMsgInHst h ON h.MessageInID=b.MessageInId
--INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=v.VehicleId
--INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId
--WHERE v.OrganizationId=121 AND f.FleetId=413

	SELECT HDP.*,REPLACE(REPLACE(REPLACE(HDP.T1,'0 degree Celsius','NA'),' degree Celsius',''),'Disconnected','NA') AS T1_Value,
	REPLACE(REPLACE(REPLACE(HDP.T2,'0 degree Celsius','NA'),' degree Celsius',''),'Disconnected','NA') AS T2_Value,'°C' AS Units
	FROM (SELECT b.BoxId,v.VehicleId,v.VehicleDescription, 
	DATEADD(HOUR,5, DATEADD(MINUTE,30,b.LastStatusDateTime)) AS LastStatusDateTime,
	b.LastLatitude,b.LastLongitude,ISNULL(b.LastStreetAddress,'N/A') AS StreetAddress,
	dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID, h.BoxId, h.MessageInID, h.OriginDateTime) as MessageDetails,
	CASE WHEN B.LastValidDateTime = B.LastStatusDateTime THEN 1 ELSE 0 END as IsCurrent,b.LastSpeed,h.CustomProp,
	CASE WHEN CHARINDEX('Temperature Sensor-1 Value',h.CustomProp,0) <> 0 THEN
	SUBSTRING(h.CustomProp,CHARINDEX('Temperature Sensor-1 Value',h.CustomProp,0)+27,
	(CHARINDEX(';',h.CustomProp,CHARINDEX('Temperature Sensor-1 Value',h.CustomProp,0))  - 
	(CHARINDEX('Temperature Sensor-1 Value',h.CustomProp,0)+27))) ELSE '0' END AS T1,
	CASE WHEN CHARINDEX('Temperature Sensor-2 Value',h.CustomProp,0) <> 0 THEN
	SUBSTRING(h.CustomProp,CHARINDEX('Temperature Sensor-2 Value',h.CustomProp,0)+27,
	(CHARINDEX(';',h.CustomProp,CHARINDEX('Temperature Sensor-2 Value',h.CustomProp,0))  - 
	(CHARINDEX('Temperature Sensor-2 Value',h.CustomProp,0)+27))) 
	ELSE '0' END AS T2
	--CASE WHEN CHARINDEX('Temperature Sensor-1 Value',h.CustomProp,0) <> 0 THEN
	--SUBSTRING(h.CustomProp,CHARINDEX('Temperature Sensor-1 Value',h.CustomProp,0)+27,
	--(CHARINDEX(';',REPLACE(h.CustomProp,' degree Celsius',''),CHARINDEX('Temperature Sensor-1 Value',h.CustomProp,0))  - 
	--(CHARINDEX('Temperature Sensor-1 Value',h.CustomProp,0)+27)))
	-- ELSE 'NA' END AS T1,
	--CASE WHEN CHARINDEX('Temperature Sensor-2 Value',h.CustomProp) <> 0 THEN
	--SUBSTRING(h.CustomProp,CHARINDEX('Temperature Sensor-2 Value',h.CustomProp,0)+27,
	--(CHARINDEX(';',REPLACE(h.CustomProp,' degree Celsius',''),CHARINDEX('Temperature Sensor-2 Value',h.CustomProp,0))  - 
	--(CHARINDEX('Temperature Sensor-2 Value',h.CustomProp,0)+27)))
	-- ELSE 'NA' END AS T2 
	FROM rvlfVehicle v 
	INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId
	INNER JOIN rvlfBoxId b ON b.BoxId=va.BoxId
	INNER JOIN rvlfMsgInHst h ON h.MessageInID=b.MessageInId
	INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=v.VehicleId
	INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId
	WHERE v.OrganizationId=121 AND f.FleetId=413) HDP WHERE HDP.LastSpeed > 0

SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleType]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicleType]           
/******************************************************          
Stored Procedure Name : rvlf_sp_GetVehicleType          
Purpose     : Retrieve all Vehicle Types          
Created by    : Gopal  
Created date   : 18-Dec-14          
Updated by    :           
Updated date   :           
*******************************************************/                  
AS                  
BEGIN                
 SELECT VehicleTypeId,VehicleTypeName from rvlfVehicleType      
          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleViolations]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicleViolations]  
 @bigFleetID bigint = NULL,                      
 @intBoxID varchar(max) = null,                      
 @dtStartDate datetime = Null,                      
 @dtEndDate datetime = NULL,                      
 @tiBoxMsgInType tinyint = null,                      
 @bigOrganizationID bigint = NULL,                      
 @bigQueryingUser bigint = NULL,                      
 @vcBoxMsgTypeIDs varchar(25) = Null--'4, 14 , 15 , 16 , 17'                      
AS                      
/******************************************************************************/                      
-- Name  : [rvlf_sp_GetVehicleViolations] @intBoxID = NULL, @bigOrganizationID=23, @dtStartDate='01/08/2013 08:00:00 AM', @dtEndDate='01/09/2013 08:00:00 PM', @bigQueryingUser = 303,@vcBoxMsgTypeIDs='4,14,15,16,17'  
-- EXEC [rvlf_sp_GetVehicleViolations_KAS] @intBoxID = '2091', @bigOrganizationID=138, @dtStartDate='12/30/2012 08:00:00 AM', @dtEndDate='12/30/2012 08:00:00 PM', @bigQueryingUser = 19,@vcBoxMsgTypeIDs='4,14,15,16,17'  
-- Description : To get the driver behaviour                      
-- Author  : S.Jeyanthi.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>>  Initial Reason  
--    : 15-Oct-2010 SJ Created Intial Version  
--    : 09-Aug-2011 Ranjith Date format Included  
/******************************************************************************/  
BEGIN                      
 Declare @dtFDate datetime = @dtStartDate                  
 Declare @dtEDate datetime = @dtEndDate                  
 DECLARE @Lang varchar(50),  @LangSetting varchar(20)                                               
                  
 ------- Included to get the user prefernces---------------------                      
 DECLARE @HoursToBeAdded INT = 0                      
 DECLARE @MinsToBeAdded INT = 0                      
 DECLARE @DistanceCaptionPrefix varchar(15)                      
 DECLARE @SpeedCaptionPrefix varchar(15)                      
 DECLARE @ConversionFactor numeric (10,2) = 1.0                      
 DECLARE @DefaultDateFormat INT = 0  
                          
   
 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 '(in Miles)' ELSE '(in Kms)' END,                      
     @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(in MPH)' ELSE '(in KMPH)' END,                  
     @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)=0 then 107 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                      
                      
    SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                      
  
                       
 IF @bigFleetID is null  OR @bigFleetID=''                    
  BEGIN                      
   SELECT @bigFleetID = FleetID FROM rvlfFleet where IsDefault= 1 and OrganizationId = @bigOrganizationID                      
  END                      
                      
 DECLARE @tblViolation table (VehicleID bigint,VehDisplayName varchar(20), BoxId int,                      
   SpeedCount int, HarshBrakingCount int,ExtremeBrakingCount int,  HarshAccelerationCount int, ExtremeAccelerationCount int,                      
   AccidentCount int)                      
                      
 DECLARE @tblMessages table(                      
  [MessageInID] [uniqueidentifier] NOT NULL,                      
  [BoxId] [int] NOT NULL,                      
  [OriginDateTime] [datetime] NULL,                      
  [DateTimeReceived] [datetime] NULL,                      
  [BoxMsgInTypeDesc] [varchar](50) NOT NULL,                      
  [BoxMsgInTypeId] [tinyint] NOT NULL,                        
  [Speed] [int] NULL,                      
  [Heading] [smallint] NULL,       
  [SensorMask] varchar(35) NULL,                      
  [StreetAddress] [nvarchar](250) NOT NULL,                        
  [Vin] [varchar](20) NULL,                      
  [LicensePlate] [varchar](20) NULL,                        
  [VehicleID] [bigint],                      
  [VehicleDescription] [varchar](50) NULL,                      
  [VehDisplayName] [varchar](20) NULL,                      
  [OrganizationId] [bigint] NULL,                        
  [Duration] [varchar](max) NULL,                      
  [FleetName] [varchar](100) NOT NULL,                      
  [OrganizationName] [varchar](200) NOT NULL,                      
  [DistanceCaption] [varchar](10) NOT NULL,                      
  [SpeedCaption] [varchar](10) NOT NULL,                      
  [MessageDetails] [nvarchar](max) NULL,          
  [DriverName] [NVARCHAR](MAX) NULL,  
  [RoadSpeed] INT                
 )                 
                      
  INSERT INTO @tblViolation (VehicleID, VehDisplayName, BoxId,SpeedCount,HarshBrakingCount,                       
   ExtremeBrakingCount, HarshAccelerationCount, ExtremeAccelerationCount)                      
   SELECT  DISTINCT v.VehicleId, v.VehicleDescription AS DisplayName, va.BoxId,0,0,0,0,0                                              
    from rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId                                              
    INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=v.VehicleId    
    INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId    
    where v.OrganizationId = @bigOrganizationID AND     
    (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID)    
    AND (@intBoxID is null OR @intBoxID='0' OR @intBoxID='' OR BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))    
            
  DECLARE @intIterator int;                   
  DECLARE @intSpeedCount int  
  DECLARE @intHarshBrakingCount int  
  DECLARE @intExtremeBrakingCount int  
  DECLARE @intHarshAccelerationCount int  
  DECLARE @intExtremeAccelerationCount int  
                        
  SELECT @intIterator = MAX(VehicleID) FROM @tblViolation                      
                        
  WHILE @intIterator IS NOT NULL                      
   BEGIN                      
    SELECT @intBoxID = BoxId from @tblViolation WHERE VehicleID  = @intIterator                      
    SET @intSpeedCount  = 0;SET @intHarshBrakingCount = 0;SET @intExtremeBrakingCount = 0;                       
    SET @intHarshAccelerationCount = 0; SET @intExtremeAccelerationCount = 0;                      
                  
                  
 DECLARE @ISRoadSpeedenabled BIT = 0   
 SELECT @ISRoadSpeedenabled = ISNULL(ISRoadSpeedEnabled,0) FROM rvlfOrganization WHERE OrganizationId = @bigOrganizationID  
                          
    SELECT                       
     @intSpeedCount = SUM(CASE WHEN (@vcBoxMsgTypeIDs LIKE '4%' AND h.Speed <> 0 AND h.Speed > h.RoadSpeedLimit AND   
     --@bigOrganizationID = 23  
     --@bigOrganizationID IN (SELECT OrganizationId FROM rvlfOrganization WHERE ISRoadSpeedEnabled = 1)  
     @ISRoadSpeedenabled = 1)  
      OR h.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END),  
     @intHarshBrakingCount = SUM(CASE WHEN  h.BoxMsgInTypeId = 14 THEN 1 ELSE 0 END),                           
     @intExtremeBrakingCount = SUM(CASE WHEN h.BoxMsgInTypeId = 15  THEN 1 ELSE 0 END),                           
     @intHarshAccelerationCount = SUM(CASE WHEN h.BoxMsgInTypeId = 16 THEN 1 ELSE 0 END),                      
     @intExtremeAccelerationCount = SUM(CASE WHEN h.BoxMsgInTypeId = 17 THEN 1 ELSE 0 END)  
    FROM rvlfMsgInHst h  
     INNER JOIN rvlfBoxId B on B.BoxId = H.BoxId  
     INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
    WHERE  
     B.OrganizationId = @bigOrganizationID and  
     (@intBoxID IS NULL OR @intBoxID='' OR h.BoxId = @intBoxID) AND  
    (h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)  
     AND (h.BoxMsgInTypeId IN (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxMsgTypeIDs,',')) OR  (h.Speed <> 0 AND h.Speed > h.RoadSpeedLimit))  
    Group By h.BoxId  
      
    INSERT INTO @tblMessages                       
     SELECT                       
      h.MessageInID, h.BoxId,                      
      DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime))OriginDateTime,  
      DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.DateTimeReceived))DateTimeReceived,  
        
        
      CASE WHEN @vcBoxMsgTypeIDs LIKE '4%' AND   
      --@bigOrganizationID=23   
      @ISRoadSpeedenabled = 1  
      AND h.Speed <> 0 AND h.Speed > h.RoadSpeedLimit THEN 'Road Speed (Limit - '               
      + CAST (CAST(CAST(h.RoadSpeedLimit AS numeric(10,2)) * @ConversionFactor  AS INT)as VARCHAR(5))+' '           
      + REPLACE(REPLACE(@SpeedCaptionPrefix,'(',''),')','') + ')'          
      ELSE            
      (case when @Lang ='LanguageArNew' then ISNULL(m.BoxMsgInTypeDesc_Ar,m.BoxMsgInTypeDesc) else m.BoxMsgInTypeDesc end)  
      END as BoxMsgInTypeDesc, m.BoxMsgInTypeId,  
      CAST (CAST(h.Speed AS numeric(10)) * @ConversionFactor  as int) as Speed,  
       h.Heading,  
         
       CASE WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3  
       OR h.BoxMsgInTypeId = 13 THEN  
        dbo.rvlf_fn_GetAlarmDetails_New(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime,@Lang)         
       WHEN (@vcBoxMsgTypeIDs LIKE '4%' AND   
       --@bigOrganizationID=23   
       @ISRoadSpeedenabled = 1   
       AND h.Speed <> 0 AND H.Speed > H.RoadSpeedLimit) THEN '' ELSE ' ' END as SensorMask,  
         
       --ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,  
         (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)as StreetAddress,         
      v.Vin, v.LicensePlate,v.VehicleId,v.VehicleDescription, v.VehicleDescription AS DisplayName,  
      v.OrganizationId,  
        
       (CASE WHEN (@vcBoxMsgTypeIDs LIKE '4%' AND   
       --@bigOrganizationID=23   
       @ISRoadSpeedenabled = 1   
       AND h.Speed <> 0 AND h.Speed > h.RoadSpeedLimit AND h.Speed > 0) THEN ' - '  
        WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3 OR h.BoxMsgInTypeId = 13  
       THEN dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID ,h.BoxId, h.MessageInID, h.OriginDateTime)  
         WHEN h.BoxMsgInTypeId = 4 THEN  
          (SELECT TOP 1 dbo.rvlf_fn_GetTimeFromSeconds(SUBSTRING(CustomProp,CHARINDEX('Speed with Duration:',MH.CustomProp)+20,CAST (CHARINDEX(';',MH.CustomProp) AS INT ) - CAST (CHARINDEX('Speed with Duration:',MH.CustomProp)+20  AS INT)))  
         FROM rvlfmsginhst MH WHERE MH.BoxMsgInTypeId = 51 AND MH.OriginDateTime BETWEEN h.OriginDateTime AND @dtEDate AND mh.BoxId = @intBoxID AND MH.CustomProp LIKE '%Speed with Duration:%')  
         WHEN m.BoxMsgInTypeDesc<>'Sensor'  
       THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN  
       dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1) END)  
       ELSE '' END) as Duration,         
         
      f.FleetName, g.OrganizationName, @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,  
      CASE WHEN h.BoxMsgInTypeId = 28  THEN m.BoxMsgInTypeDesc  
         WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +  
         CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +  
        dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'  
        WHEN @vcBoxMsgTypeIDs LIKE '4%' AND   
        --@bigOrganizationID IN(23,183)   
        @ISRoadSpeedenabled = 1   
        AND h.Speed <> 0 AND h.Speed > H.RoadSpeedLimit THEN 'Road Speed Violation'   
       ELSE  
       dbo.rvlf_fn_GetAlarmDetails_New(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime,@Lang)END  as MessageDetails,  
        (CASE WHEN @Lang='LanguageArNew' then ISNULL(dm.DisplayName,ISNULL(dm.DisplayName,'-'))else ISNULL(dm.DisplayName,'-') end),CAST((h.RoadSpeedLimit * @ConversionFactor)AS INT)  
     FROM rvlfMsgInHst h  
      INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
      INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
      INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
      INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
      INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
      INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
      LEFT OUTER JOIN rvlfDriverMaster dm on dm.DriverId in(select Top 1 dg.DriverId from rvlfDriverAssignment dg where  dg.BoxId = va.BoxId)  
      WHERE  
(@bigFleetID IS NULL  OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND  
 ((@vcBoxMsgTypeIDs LIKE '4%' AND   
 --@bigOrganizationID=23   
 @ISRoadSpeedenabled = 1   
 AND h.Speed <> 0 AND h.Speed > h.RoadSpeedLimit) OR h.BoxMsgInTypeId IN (SELECT * from  
   dbo.rvlf_fn_ConvertArrayToTable(@vcBoxMsgTypeIDs,','))) AND  
  (@intBoxID IS NULL OR @intBoxID='' OR h.BoxId = @intBoxID) AND  
  ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
    h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND  
  (@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='' OR h.BoxMsgInTypeId = @tiBoxMsgInType)  
  AND  
  m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity  
   WHERE ModuleId = 26 and UserGroupId IN  
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))  
  AND  m.VisibleWeb = 1   
    
    
    
                           
    Update @tblViolation SET SpeedCount = @intSpeedCount,                      
      HarshBrakingCount = @intHarshBrakingCount,                      
      ExtremeBrakingCount = @intExtremeBrakingCount,                      
      HarshAccelerationCount = @intHarshAccelerationCount,                      
      ExtremeAccelerationCount = @intExtremeAccelerationCount                           
    WHERE VehicleID  = @intIterator                      
                          
    SELECT @intIterator = MAX(VehicleID) FROM @tblViolation WHERE VehicleID < @intIterator                      
   END                      
     
   --SELECT * FROM @tblMessages  
                               
  SELECT MessageInID,m.BoxId,Convert(varchar,OriginDateTime,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(OriginDateTime as time),22) as OriginDateTime ,OriginDateTime AS OriginDateTimeSort, DateTimeReceived,m.BoxMsgInTypeDesc AS 'BoxMsgInTypeName',    
  
m.BoxMsgInTypeId,  
 CASE WHEN (M.Speed >= RoadSpeed OR BoxMsgInTypeId = 4)  
             THEN M.Speed ELSE '-' END AS Speed, M.Speed,RoadSpeed,  
             SensorMask,StreetAddress,  
    m.VehicleID, m.VehicleDescription, m.VehDisplayName,  
     Vin, LicensePlate, Duration, FleetName,  
   OrganizationName, DistanceCaption, SpeedCaption, MessageDetails,b.SC, b.HBC,  b.EBC,  
    b.HAC, b.EAC,b.TotalViolations,  
    Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,m.DriverName                     
    FROM  
   (SELECT *, SC+HBC+EBC+HAC+EAC   as TotalViolations FROM  
      (SELECT VehicleID,  SUM(SpeedCount) as SC,  
        SUM(HarshBrakingCount) as HBC,  
        SUM(ExtremeBrakingCount) EBC,  SUM(HarshAccelerationCount) as HAC,  
        SUM(ExtremeAccelerationCount) as EAC  
    FROM @tblViolation  
          GROUP BY VehicleID  
        ) as a  
    ) as b  
  INNER JOIN @tblMessages as m ON m.VehicleID = b.VehicleID                        
 SET NOCOUNT OFF                      
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVehicleViolations_MasterDB]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_GetVehicleViolations_MasterDB]    
 @bigFleetID bigint = NULL,                        
 @intBoxID varchar(max) = null,                        
 @dtStartDate datetime = Null,                        
 @dtEndDate datetime = NULL,                        
 @tiBoxMsgInType tinyint = null,                        
 @bigOrganizationID bigint = NULL,                        
 @bigQueryingUser bigint = NULL,                        
 @vcBoxMsgTypeIDs varchar(25) = Null--'4, 14 , 15 , 16 , 17'                        
AS                        
/******************************************************************************/                        
-- Name  : [rvlf_sp_GetVehicleViolations] @intBoxID = NULL, @bigOrganizationID=23, @dtStartDate='2/1/2013 8:00:00 AM', @dtEndDate='{2/28/2013 8:00:00 PM}', @bigQueryingUser = 303,@vcBoxMsgTypeIDs='4,14,15,16,17'    
-- EXEC [rvlf_sp_GetVehicleViolations_KAS] @intBoxID = '2091', @bigOrganizationID=138, @dtStartDate='12/30/2012 08:00:00 AM', @dtEndDate='12/30/2012 08:00:00 PM', @bigQueryingUser = 19,@vcBoxMsgTypeIDs='4,14,15,16,17'    
-- Description : To get the driver behaviour                        
-- Author  : S.Jeyanthi.    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>>  Initial Reason    
--    : 15-Oct-2010 SJ Created Intial Version    
--    : 09-Aug-2011 Ranjith Date format Included    
/******************************************************************************/    
BEGIN                        
-- Declare @dtFDate datetime = @dtStartDate                    
-- Declare @dtEDate datetime = @dtEndDate                    
-- DECLARE @Lang varchar(50),  @LangSetting varchar(20)                                                 
                    
-- ------- Included to get the user prefernces---------------------                        
-- DECLARE @HoursToBeAdded INT = 0                        
-- DECLARE @MinsToBeAdded INT = 0                        
-- DECLARE @DistanceCaptionPrefix varchar(15)                        
-- DECLARE @SpeedCaptionPrefix varchar(15)                        
-- DECLARE @ConversionFactor numeric (10,2) = 1.0                        
-- DECLARE @DefaultDateFormat INT = 0    
                            
     
-- 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 '(in Miles)' ELSE '(in Kms)' END,                        
--     @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(in MPH)' ELSE '(in KMPH)' END,                    
--     @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)=0 then 107 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                        
                        
--    SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                        
    
                         
-- IF @bigFleetID is null  OR @bigFleetID=''                      
--  BEGIN                        
--   SELECT @bigFleetID = FleetID FROM rvlfFleet where IsDefault= 1 and OrganizationId = @bigOrganizationID                        
--  END                        
                        
-- DECLARE @tblViolation table (VehicleID bigint,VehDisplayName varchar(20), BoxId int,                        
--   SpeedCount int, HarshBrakingCount int,ExtremeBrakingCount int,  HarshAccelerationCount int, ExtremeAccelerationCount int,                        
--   AccidentCount int)                    
                        
-- DECLARE @tblMessages table(                        
--  [MessageInID] [uniqueidentifier] NOT NULL,                        
--  [BoxId] [int] NOT NULL,                        
--  [OriginDateTime] [datetime] NULL,                        
--  [DateTimeReceived] [datetime] NULL,                        
--  [BoxMsgInTypeDesc] [varchar](50) NOT NULL,                        
--  [BoxMsgInTypeId] [tinyint] NOT NULL,                          
--  [Speed] [int] NULL,                        
--  [Heading] [smallint] NULL,         
--  [SensorMask] varchar(35) NULL,                        
--  [StreetAddress] [nvarchar](250) NOT NULL,                          
--  [Vin] [varchar](20) NULL,                        
--  [LicensePlate] [varchar](20) NULL,                          
--  [VehicleID] [bigint],                        
--  [VehicleDescription] [varchar](50) NULL,                        
--  [VehDisplayName] [varchar](20) NULL,                        
--  [OrganizationId] [bigint] NULL,                          
--  [Duration] [varchar](max) NULL,                        
--  [FleetName] [varchar](100) NOT NULL,                        
--  [OrganizationName] [varchar](200) NOT NULL,                        
--  [DistanceCaption] [varchar](10) NOT NULL,                        
--  [SpeedCaption] [varchar](10) NOT NULL,                        
--  [MessageDetails] [nvarchar](max) NULL,            
--  [DriverName] [NVARCHAR](MAX) NULL,    
--  [RoadSpeed] INT                  
-- )                   
                        
--  INSERT INTO @tblViolation (VehicleID, VehDisplayName, BoxId,SpeedCount,HarshBrakingCount,                         
--   ExtremeBrakingCount, HarshAccelerationCount, ExtremeAccelerationCount)                        
--   SELECT  DISTINCT v.VehicleId, v.VehicleDescription AS DisplayName, va.BoxId,0,0,0,0,0                                                
--    from rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON v.VehicleId = va.VehicleId                                                
--    INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=v.VehicleId      
--    INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId      
--    where v.OrganizationId = @bigOrganizationID AND       
--    (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID)      
--    AND (@intBoxID is null OR @intBoxID='0' OR @intBoxID='' OR BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))      
              
--  DECLARE @intIterator int;                     
--  DECLARE @intSpeedCount int    
--  DECLARE @intHarshBrakingCount int    
--  DECLARE @intExtremeBrakingCount int    
--  DECLARE @intHarshAccelerationCount int    
--  DECLARE @intExtremeAccelerationCount int    
                          
--  SELECT @intIterator = MAX(VehicleID) FROM @tblViolation                        
                          
--  WHILE @intIterator IS NOT NULL                        
--   BEGIN                        
--    SELECT @intBoxID = BoxId from @tblViolation WHERE VehicleID  = @intIterator                        
--    SET @intSpeedCount  = 0;SET @intHarshBrakingCount = 0;SET @intExtremeBrakingCount = 0;                         
--    SET @intHarshAccelerationCount = 0; SET @intExtremeAccelerationCount = 0;                        
                    
                    
-- DECLARE @ISRoadSpeedenabled BIT = 0     
-- SELECT @ISRoadSpeedenabled = ISNULL(ISRoadSpeedEnabled,0) FROM rvlfOrganization WHERE OrganizationId = @bigOrganizationID    
                            
--    SELECT                         
--     @intSpeedCount = SUM(CASE WHEN (@vcBoxMsgTypeIDs LIKE '4%' AND h.Speed <> 0 AND      
--     --@bigOrganizationID = 23    
--     --@bigOrganizationID IN (SELECT OrganizationId FROM rvlfOrganization WHERE ISRoadSpeedEnabled = 1)    
--     @ISRoadSpeedenabled = 1)    
--      OR h.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END),    
--     @intHarshBrakingCount = SUM(CASE WHEN  h.BoxMsgInTypeId = 14 THEN 1 ELSE 0 END),                        
--     @intExtremeBrakingCount = SUM(CASE WHEN h.BoxMsgInTypeId = 15  THEN 1 ELSE 0 END),                             
--     @intHarshAccelerationCount = SUM(CASE WHEN h.BoxMsgInTypeId = 16 THEN 1 ELSE 0 END),             
--     @intExtremeAccelerationCount = SUM(CASE WHEN h.BoxMsgInTypeId = 17 THEN 1 ELSE 0 END)    
--    FROM FMS_ARCHIVE.dbo.rvlfMsgInHst h    
--     INNER JOIN rvlfBoxId B on B.BoxId = H.BoxId    
--     INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId    
--    WHERE    
--     B.OrganizationId = @bigOrganizationID and    
--     (@intBoxID IS NULL OR @intBoxID='' OR h.BoxId = @intBoxID) AND    
--    (h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)    
--     AND (h.BoxMsgInTypeId IN (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxMsgTypeIDs,',')) OR  (h.Speed <> 0 ))    
--    Group By h.BoxId    
        
--    INSERT INTO @tblMessages                         
--     SELECT                         
--      h.MessageInID, h.BoxId,                        
--      DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime))OriginDateTime,    
--      DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.DateTimeReceived))DateTimeReceived,    
          
          
--      CASE WHEN @vcBoxMsgTypeIDs LIKE '4%' AND     
--      --@bigOrganizationID=23     
--      @ISRoadSpeedenabled = 1    
--      AND h.Speed <> 0  THEN 'Road Speed (Limit - '                 
--      + CAST (CAST(CAST(h.speed AS numeric(10,2)) * @ConversionFactor  AS INT)as VARCHAR(5))+' '             
--      + REPLACE(REPLACE(@SpeedCaptionPrefix,'(',''),')','') + ')'            
--      ELSE              
--      (case when @Lang ='LanguageArNew' then ISNULL(m.BoxMsgInTypeDesc_Ar,m.BoxMsgInTypeDesc) else m.BoxMsgInTypeDesc end)    
--      END as BoxMsgInTypeDesc, m.BoxMsgInTypeId,    
--      CAST (CAST(h.Speed AS numeric(10)) * @ConversionFactor  as int) as Speed,    
--       h.Heading,    
           
--       CASE WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3    
--       OR h.BoxMsgInTypeId = 13 THEN    
--        dbo.rvlf_fn_GetAlarmDetails_New(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime,@Lang)           
--       WHEN (@vcBoxMsgTypeIDs LIKE '4%' AND     
--       --@bigOrganizationID=23     
--       @ISRoadSpeedenabled = 1     
--       AND h.Speed <> 0 ) THEN '' ELSE ' ' END as SensorMask,    
           
--       --ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,    
--         (Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN H.StreetAddress     
--    When @Lang='LanguageHindi' and @LangSetting like '%3%' THEN H.StreetAddress     
--    ELSE H.StreetAddress END)as StreetAddress,           
--      v.Vin, v.LicensePlate,v.VehicleId,v.VehicleDescription, v.VehicleDescription AS DisplayName,    
--      v.OrganizationId,    
          
--       (CASE WHEN (@vcBoxMsgTypeIDs LIKE '4%' AND     
--       --@bigOrganizationID=23     
--       @ISRoadSpeedenabled = 1     
--       AND h.Speed <> 0 AND h.Speed > 0) THEN ' - '    
--        WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3 OR h.BoxMsgInTypeId = 13    
--       THEN dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID ,h.BoxId, h.MessageInID, h.OriginDateTime)    
--         WHEN h.BoxMsgInTypeId = 4 THEN    
--          (SELECT TOP 1 dbo.rvlf_fn_GetTimeFromSeconds(SUBSTRING(CustomProp,CHARINDEX('Speed with Duration:',MH.CustomProp)+20,CAST (CHARINDEX(';',MH.CustomProp) AS INT ) - CAST (CHARINDEX('Speed with Duration:',MH.CustomProp)+20  AS INT)))    
--         FROM FMS_ARCHIVE.dbo.rvlfmsginhst MH WHERE MH.BoxMsgInTypeId = 51 AND MH.OriginDateTime BETWEEN h.OriginDateTime AND @dtEDate AND mh.BoxId = @intBoxID AND MH.CustomProp LIKE '%Speed with Duration:%')    
--         WHEN m.BoxMsgInTypeDesc<>'Sensor'    
--       THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN    
--       dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1) END)    
--       ELSE '' END) as Duration,           
           
--      f.FleetName, g.OrganizationName, @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,    
--      CASE WHEN h.BoxMsgInTypeId = 28  THEN m.BoxMsgInTypeDesc    
--         WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +    
--         CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +    
--        dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'    
--        WHEN @vcBoxMsgTypeIDs LIKE '4%' AND     
--        --@bigOrganizationID IN(23,183)     
--        @ISRoadSpeedenabled = 1     
--        AND h.Speed <> 0  THEN 'Road Speed Violation'     
--       ELSE    
--       dbo.rvlf_fn_GetAlarmDetails_New(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime,@Lang)END  as MessageDetails,    
--        (CASE WHEN @Lang='LanguageArNew' then ISNULL(dm.DisplayName,ISNULL(dm.DisplayName,'-'))else ISNULL(dm.DisplayName,'-') end),CAST((h.speed * @ConversionFactor)AS INT)    
--     FROM FMS_ARCHIVE.dbo.rvlfMsgInHst h    
--      INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId    
--      INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId    
--      INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId    
--      INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId    
--      INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId    
--      INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId    
--      LEFT OUTER JOIN rvlfDriverMaster dm on dm.DriverId in(select Top 1 dg.DriverId from rvlfDriverAssignment dg where  dg.BoxId = va.BoxId)    
--      WHERE    
--(@bigFleetID IS NULL  OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND    
-- ((@vcBoxMsgTypeIDs LIKE '4%' AND     
-- --@bigOrganizationID=23     
-- @ISRoadSpeedenabled = 1     
-- AND h.Speed <> 0 ) OR h.BoxMsgInTypeId IN (SELECT * from    
--   dbo.rvlf_fn_ConvertArrayToTable(@vcBoxMsgTypeIDs,','))) AND    
--  (@intBoxID IS NULL OR @intBoxID='' OR h.BoxId = @intBoxID) AND    
--  ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR    
--    h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND    
--  (@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='' OR h.BoxMsgInTypeId = @tiBoxMsgInType)    
--  AND    
--  m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity    
--   WHERE ModuleId = 26 and UserGroupId IN    
--   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))    
--  AND  m.VisibleWeb = 1     
      
      
      
                             
--    Update @tblViolation SET SpeedCount = @intSpeedCount,                        
--      HarshBrakingCount = @intHarshBrakingCount,                        
--      ExtremeBrakingCount = @intExtremeBrakingCount,                        
--      HarshAccelerationCount = @intHarshAccelerationCount,                        
--      ExtremeAccelerationCount = @intExtremeAccelerationCount                             
--    WHERE VehicleID  = @intIterator                        
                            
--    SELECT @intIterator = MAX(VehicleID) FROM @tblViolation WHERE VehicleID < @intIterator                        
--   END                        
       
--   --SELECT * FROM @tblMessages    
                                 
--  SELECT MessageInID,m.BoxId,Convert(varchar,OriginDateTime,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(OriginDateTime as time),22) as OriginDateTime ,OriginDateTime AS OriginDateTimeSort, DateTimeReceived,m.BoxMsgInTypeDesc AS 'BoxMsgInTypeName',   

   
    
--m.BoxMsgInTypeId,    
-- CASE WHEN (M.Speed >= RoadSpeed OR BoxMsgInTypeId = 4)    
--             THEN M.Speed ELSE '-' END AS Speed, M.Speed,RoadSpeed,    
--             SensorMask,StreetAddress,    
--    m.VehicleID, m.VehicleDescription, m.VehDisplayName,    
--     Vin, LicensePlate, Duration, FleetName,    
--   OrganizationName, DistanceCaption, SpeedCaption, MessageDetails,b.SC, b.HBC,  b.EBC,    
--    b.HAC, b.EAC,b.TotalViolations,    
--    Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,Convert(varchar,dateadd(hour,@
--HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,m.DriverName                       
--    FROM    
--   (SELECT *, SC+HBC+EBC+HAC+EAC   as TotalViolations FROM    
--      (SELECT VehicleID,  SUM(SpeedCount) as SC,    
--        SUM(HarshBrakingCount) as HBC,    
--        SUM(ExtremeBrakingCount) EBC,  SUM(HarshAccelerationCount) as HAC,    
--        SUM(ExtremeAccelerationCount) as EAC    
--    FROM @tblViolation    
--          GROUP BY VehicleID    
--        ) as a    
--    ) as b    
--  INNER JOIN @tblMessages as m ON m.VehicleID = b.VehicleID                          
-- SET NOCOUNT OFF     
select 1                   
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVendorDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
            
CREATE PROCEDURE [dbo].[rvlf_sp_GetVendorDetails]             
@VendorID int = Null,                          
@bigOrganizationId bigint = Null,                          
@bigUserId bigint = Null                       
            
AS            
-- =============================================            
-- Name   : rvlf_sp_GetVendorDetails            
-- Author  : Gopal.R            
-- Create date : 21-Oct-2013            
-- Description : Get Vendor Details            
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
-- =============================================            
BEGIN            
 -- SET NOCOUNT ON added to prevent extra result sets from            
 -- interfering with SELECT statements.            
 SET NOCOUNT ON;            
            
    -- Insert statements for procedure here            
 select VendorId,VendorName,WorkOrder,replace(convert(varchar(20),ContractFrom,106 ),' ','-')as ContractFrom,ContractFrom as ContractFromSort,replace(convert(varchar(20),ContractTo,106 ),' ','-') as ContractTo,ContractTo as ContractToSort,FxCostPerMonth,
 FxKMPerMonth,DutyHourType,FuelCostPerLit,LiterPerKm,      
 ExCostPerKm,ExCostPerHr,CreatedBy,CreateDate,ModifiedBy,ModifiedDate,IsDelete,OrganizationId,replace(convert(varchar(20),ContractFrom,106 ),' ','-') + ' to ' + replace(convert(varchar(20),ContractTo,106 ),' ','-') as ContractPeriod           
 from rvlfVendors           
 where IsDelete=0 and (OrganizationId=@bigOrganizationId or @bigOrganizationId is null) and (VendorId=@VendorID or @VendorID is null )        
 order by VendorId      
     
 select * from rvlfVendorMDays where VendorId=@VendorID    
     
 set Nocount off;          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVendorNames]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetVendorNames]        
@Prefix varchar(20)=null,            
@bigOrganizationId bigint = Null  ,      
@VendorType char(3)      
AS        
/******************************************************************************/        
-- Name    : rvlf_sp_GetVendorNames 'T',6,'I'        
-- Description   : To get all the ContainerNames         
-- Author    : Kapil        
-- Created Date  : 19-Feb-2014        
--  Modified Date :         
/******************************************************************************/        
BEGIN        
 SET NOCOUNT ON         
        
 SELECT  VendorId,VendorName FROM rvlfTyreVendorMaster where IsDelete =0 and OrganizationId= @bigOrganizationId        
         and VendorType=@VendorType      
       --SELECT distinct B.BrandID,BrandName,M.Remarks from rvlfTyreMake B        
       --inner JOIN rvlfTyreModel M on M.BrandID = B.BrandID               
       --where OrganizationId= @bigOrganizationId            
               
 SELECT B.BrandID,BrandName from rvlfTyreMake B        
  where OrganizationId=@bigOrganizationId and BrandID in(select BrandID from rvlfTyreModel)            
               
 SELECT ModelID,ModelName,M.BrandID,Remarks from rvlfTyreModel  TM left join rvlfTyreMake M on M.BrandID = Tm.BrandID        
       where OrganizationId= @bigOrganizationId    
          
 SELECT  VendorId,VendorName FROM rvlfTyreVendorMaster where IsDelete =0 and OrganizationId= @bigOrganizationId        
         and VendorType=@VendorType  and VendorName like @Prefix + '%'           
                
 SET NOCOUNT OFF        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVendorNamesMapping]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetVendorNamesMapping]
@bigOrganizationId bigint = Null
AS
/******************************************************************************/
--	Name		  : rvlf_sp_GetVendorNamesMapping 1
--	Description	  :	To get all the VendorNames for Vehicle Mapping which has quantity 
--	Author		  :	Kapil
--	Created Date  : 12-Mar-2014
--  Modified Date : 
/******************************************************************************/
BEGIN
	SET NOCOUNT ON

       SELECT distinct TM.VendorId,VendorName FROM rvlfTyreVendorMaster VM
	   inner join rvlfTyreMaster TM on TM.VendorId = VM.VendorId 
	   inner join rvlfTyreStock S on S.VendorId = TM.VendorId 
		-- INNER JOIN rvlfTyreMake B on B.BrandID = TM.BrandID  	 B.BrandID,B.BrandName,M.ModelID,M.ModelName  
		-- INNER JOIN rvlfTyreModel M on M.BrandID = B.BrandID
	   where Tm.IsDelete =0 and Tm.IsActive =1 and TM.OrganizationId= @bigOrganizationId
	   and S.Available >0
	  order by TM.VendorId
	  	  
              
       SELECT B.BrandID,BrandName,M.Remarks from rvlfTyreMake B
       inner JOIN rvlfTyreModel M on M.BrandID = B.BrandID       
       where OrganizationId= @bigOrganizationId       
       
       SELECT ModelID,ModelName,M.BrandID from rvlfTyreModel  TM
       left join rvlfTyreMake M on M.BrandID = Tm.BrandID
       where OrganizationId= @bigOrganizationId
       
       SELECT  VendorId,VendorName FROM rvlfTyreVendorMaster where IsDelete =0 and OrganizationId= @bigOrganizationId
      		
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVendorVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetVendorVehicles]            
	@bigVendorID		bigint	=	null,            
	@bigOrganizationID	bigint	=	null,            
	@bitIsAssigned		bit		=	0,            
	@VehDescPrefix		nVarchar(50) = null,        
	@bigQueryingUser	bigint	=	null              
AS           
/******************************************************************************/            
-- Name  :	rvlf_sp_GetVendorVehicles 116,6,0,null,219
--			rvlf_sp_GetVendorVehicles 54,6,1,null,219
-- Description : To get assinged and unassinged vehicles            
-- Author  : R.Gopal    
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--    : 23-oct-2013 MJJC Created Intial Version             
/******************************************************************************/            
BEGIN            
 SET NOCOUNT ON             
  declare @Lang varchar(50)             
  select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser          
             
 IF @bitIsAssigned = 0             
 BEGIN

	SELECT	v.VehicleId, (case when @Lang='LanguageArNew' then isnull(v.VehicleDescription, v.VehicleDescription) else v.VehicleDescription end) as VehicleDescription,
			m.ModelName, k.MakeName, v.Color,v.ModelYear, t.VehicleTypeName, v.Vin, v.ModelId, v.MakeId, v.VehicleTypeId, v.VehicleDescription as VehicleName, 
			v.Location, v.DisplayName             
	FROM	rvlfVehicle v             
	--INNER JOIN rvlfVendorVehicles fv ON v.VehicleId = fv.VehicleId
	--INNER JOIN rvlfVendors f ON fv.VendorId = f.VendorId            
	LEFT	OUTER JOIN rvlfModel m ON v.ModelId = m.ModelId            
	LEFT	OUTER JOIN rvlfMake k ON v.MakeId = k.MakeId            
	LEFT	OUTER JOIN rvlfVehicleType t ON v.VehicleTypeId = t.VehicleTypeId            
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)            
	AND		(@VehDescPrefix IS NULL OR @VehDescPrefix='' OR v.VehicleDescription LIKE @VehDescPrefix + '%')            
	AND		v.VehicleId NOT IN	(SELECT rfv.VehicleId FROM rvlfVendorVehicles rfv 
								WHERE /*VendorId = @bigVendorID AND*/ -- If a vehicle assigned for one vendor then it can't be assigned to another.
								rfv.IsActive = 1)
	AND		v.VehicleOwnership = 2 
	ORDER	BY v.VehicleDescription asc           
              
 END                   
 ELSE            
 BEGIN            
	
	-- SELECT the vehicles assinged to the Vendor            
	SELECT	ROW_NUMBER () over (order by v.vehicledescription asc) as SlNo, v.VehicleId,va.BoxId, 
			(case when @Lang='LanguageArNew' then isnull(v.VehicleDescription, v.VehicleDescription) else v.VehicleDescription end) as VehicleDescription,            
			m.ModelName, k.MakeName, v.Color,v.ModelYear, t.VehicleTypeName, v.Vin, v.ModelId, v.MakeId, v.VehicleTypeId, v.VehicleDescription as VehicleName,
			v.Location, v.DisplayName,vvs.TokenId,vvs.Email,convert(varchar(50),vvs.ContractTo,106)as ContractTo                   
	FROM	rvlfVehicle v             
	LEFT	OUTER JOIN rvlfVendorVehicles fv ON v.VehicleId = fv.VehicleId AND fv.IsActive = 1
	--INNER	JOIN rvlfVendors f ON fv.VendorId = f.VendorId
	INNER	JOIN rvlfTyreVendorMaster tvm ON fv.VendorId = tvm.VendorId
	INNER	JOIN rvlfVehicleAssignment va on v.VehicleId=va.VehicleId  
	INNER	JOIN rvlfVendorVehicleSettings vvs on vvs.vendorvehicleassignid =fv.vendorvehicleassignid                          
	LEFT	OUTER JOIN rvlfModel m ON v.ModelId = m.ModelId            
	LEFT	OUTER JOIN rvlfMake k ON v.MakeId = k.MakeId            
	LEFT	OUTER JOIN rvlfVehicleType t ON v.VehicleTypeId = t.VehicleTypeId            
	WHERE	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR tvm.OrganizationId = @bigOrganizationID)            
	AND		(@VehDescPrefix IS NULL OR @VehDescPrefix='' OR v.VehicleDescription LIKE @VehDescPrefix + '%')            
	AND		(@bigVendorID IS NULL OR @bigVendorID='' OR tvm.VendorId = @bigVendorID)	
	ORDER	BY v.VehicleDescription asc            

 END            
             
 SET NOCOUNT OFF            
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVICurve]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_GetVICurve]
as begin
 select 69 as MA,0 as Va,0 as Vp    ,0 as Vt union
 select 138 as MA,3 as Va,5 as Vp   ,6 as Vt union
 select 207 as MA,7 as Va,10 as Vp  ,12 as Vt union
 select 276 as MA,11 as Va,15 as Vp ,17 as Vt union
 select 345 as MA,14 as Va,19 as Vp ,21 as Vt union
 select 414 as MA,17 as Va,23 as Vp ,25 as Vt union
 select 483 as MA,20 as Va,27 as Vp ,29 as Vt union
 select 552 as MA,23 as Va,31 as Vp ,32 as Vt union
 select 621 as MA,26 as Va,35 as Vp ,35 as Vt union
 select 690 as MA,28 as Va,38 as Vp ,39 as Vt
 end
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetViolations]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_GetViolations]  
 @bigFleetID bigint = null,  
 @intBoxID int = null,  
 @dtStartDate datetime = null,  
 @dtEndDate datetime = null,  
 @bigAcceptedBy bigint = null,  
 @bigClosedBy bigint = null,  
 @tiBoxMsgInType tinyint = null,  
 @bigOrganizationID bigint = null,  
 @bigQueryingUser bigint = 0,  
 @vcBoxMsgTypeIDs varchar(25) = null --'4, 14 , 15 , 16 , 17'  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_GetViolations @vcBoxMsgTypeIDs ='4, 14 , 15 , 16 , 17'  
-- Description : To get the violations messages  
--    :   Pass the valu 0 (Zero) to @bigQueryingUser if the user is angler admin  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>>  Initial Reason  
--    : 28-May-2009 MJJC    Created Intial Version   
--    : 11-Dec-2009 MJJC    Commented ranking for future and included message restrictions  
--    : 29-Jan-2010 MJJC    Handled null values in street address  
--              :   06-Mar-2010 Kumuthini  Included the date conversion in Start Date & End Date  
--    : 26-Apr-2010 MJJC Done the related change for shoing speed with violation  
--    : 29-Jun-2010 MJJC Vehicle Display Nmae as Vehicle Description  
--    : 03-Feb-2011 TSK  Displayed Landmark Name instead of Street Address  
/******************************************************************************/  
BEGIN  
 SET NOCOUNT ON   
   
 ------- Included to get the user prefernces---------------------  
   
 DECLARE @HoursToBeAdded INT = 0  
 DECLARE @MinsToBeAdded INT = 0  
 DECLARE @DistanceCaptionPrefix varchar(15)  
 DECLARE @SpeedCaptionPrefix varchar(15)  
 DECLARE @ConversionFactor numeric (10,2) = 1.0  
 DECLARE @DefaultDateFormat INT = 0;  
 
    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 '(in Miles)' ELSE '(in Kms)' END,  
     @SpeedCaptionPrefix = CASE WHEN up.Distance = 0 THEN '(in MPH)' ELSE '(in KMPH)' 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 = @bigQueryingUser  
  
    SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))  
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))  
   
 SELECT   
  h.MessageInID, h.BoxId,  
   OriginDateTime =dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,h.OriginDateTime),
 DateTimeReceived= dbo.rvlf_fn_DayLightSavings_Date(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,h.DateTimeReceived),
  --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.OriginDateTime))OriginDateTime,   
  --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,h.DateTimeReceived))DateTimeReceived,   
  m.BoxMsgInTypeName, m.BoxMsgInTypeId,  
  h.CommInfo1, h.CommInfo2, h.Latitude, h.Longitude,   
  CASE WHEN h.BoxMsgInTypeId=51 THEN 0 ELSE CAST (CAST(h.Speed AS numeric(10,2)) * @ConversionFactor  as int) END as Speed,  
   h.Heading,   
  CASE WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3  
  OR h.BoxMsgInTypeId = 13 THEN   
   dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID, h.BoxId, h.MessageInID, h.OriginDateTime)  
   ELSE ' ' END as SensorMask,  
  h.CustomProp,   
  --ISNULL(h.StreetAddress, 'Address is not resolved') as StreetAddress,   
  CASE WHEN (H.LandMarkID IS NULL OR H.LandMarkID = 0) THEN   
       Replace(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''') ELSE L.LandmarkName END AS StreetAddress,  
  h.IsArmed, h.NearestLandmark,  
  h.Priority, v.Vin, v.LicensePlate, v.Email, v.SMS,v.VehicleDescription,   
  v.OrganizationId, CASE WHEN v.Notify=1 THEN 'Notify'   
  WHEN v.Warning=1 THEN 'Warning' WHEN v.Critical =1 THEN 'Critical'   
  ELSE 'No Notification is set' END as NotificationType,   
  (CASE WHEN h.BoxMsgInTypeID = 11 OR h.BoxMsgInTypeId = 2 OR h.BoxMsgInTypeId = 3 OR h.BoxMsgInTypeId = 13    
   THEN dbo.rvlf_fn_GetAlarmDetails(h.customprop,h.BoxMsgInTypeID ,h.BoxId, h.MessageInID, h.OriginDateTime)  
     WHEN h.BoxMsgInTypeId = 4 THEN ''  
     WHEN m.BoxMsgInTypeName<>'Sensor'  
   THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeName,CustomProp,1) = 1 THEN   
   dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,1) END)  
   ELSE '' END) as Duration,  
  f.FleetName, g.OrganizationName, @DistanceCaptionPrefix as DistanceCaption, @SpeedCaptionPrefix as SpeedCaption,  
  CASE WHEN h.BoxMsgInTypeId = 28  THEN m.BoxMsgInTypeDesc   
     WHEN h.BoxMsgInTypeId = 51 THEN 'Violated ' +  
     CAST(CAST(h.Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @DistanceCaptionPrefix +' (' +  
    dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'  
   ELSE  
  dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId,h.MessageInID,h.OriginDateTime)END  as MessageDetails  
 FROM rvlfMsgInHst h   
  INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
  INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
  INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
  LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
  INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
  INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
  INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId  
  INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId  
  LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID  
 WHERE  
  ( @bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId = @bigFleetID) AND   
  h.BoxMsgInTypeId IN (SELECT * from   
   dbo.rvlf_fn_ConvertArrayToTable(@vcBoxMsgTypeIDs,',')) AND  
  (@intBoxID IS NULL OR @intBoxID='' OR h.BoxId = @intBoxID) AND  
  ((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR  
    h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate) AND  
  (@tiBoxMsgInType IS NULL OR @tiBoxMsgInType='' OR h.BoxMsgInTypeId = @tiBoxMsgInType)AND  
  m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity  
   WHERE ModuleId = 26 and UserGroupId IN   
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))  
  AND  
  m.VisibleWeb=1  
 SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetVORReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[rvlf_sp_GetVORReport]                          
@bigFleetID bigint = NULL,              
@intBoxID varchar(max) = NULL,              
@dtStartDate datetime = NULL,              
@dtEndDate datetime =NULL,              
@bigOrganizationID bigint = NULL,              
@bigQueryingUser bigint = NULL                          
AS                          
/*******************************************************************************************************/                                            
-- Name  : rvlf_sp_GetVORReport 8,null,'2015-06-01 10:27:01.000','2015-07-17 11:23:00.000',6,94              
-- Description : To get the VOR Details as a report              
-- Created date : 17-Jun-2015              
-- Created by : Gopalakrishnan.R              
/*******************************************************************************************************/                            
BEGIN                          
SET NOCOUNT ON                          
                         
 DECLARE @dtFDate datetime =@dtStartDate                            
 DECLARE @dtEDate datetime =@dtEndDate                            
 DECLARE @HoursToBeAdded INT = 0                            
 DECLARE @MinsToBeAdded INT = 0                             
 DECLARE @DefaultDateFormat INT = 0                          
                            
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                          
 @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(@bigQueryingUser IS NULL OR @bigQueryingUser='' OR up.UserId = @bigQueryingUser)                            
          
select VD.FleetId,VD.VehicleId,V.VehicleDescription,V.Vin,V.LicensePlate,    
CONVERT (varchar(11),vd.DateFrom,106) as DateFrom,              
  CONVERT (varchar(11),vd.DateTo,106) as DateTo,              
DATEDIFF(DAY,VD.DateFrom,VD.DateTo) as TotOffRoadDays,VD.RefDoc,VD.AdditionalInfo,VD.Reason,              
case when VDP.sts >GETDATE() then 'Vehicle Off Road' else 'Vehicle On Road' end as CrntSts,          
case when VD.dateto >GETDATE() then 'In-Progress' else 'Expired' end as Statuss,              
Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,                        
Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,                        
Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate            
  
    
     
 from  rvlfVORDetails VD               
 inner join rvlfVehicle V on VD.VehicleId=V.VehicleId              
 inner join rvlfVehicleAssignment VA on V.VehicleId=VA.VehicleId      
 inner join rvlfFleetVehicles FV on V.VehicleId=FV.VehicleId              
 inner join rvlfFleet F on FV.FleetId=f.FleetId              
 left join (select VehicleID,MAX(DateTo) as sts from rvlfVORDetails group by VehicleId) as VDP on VD.vehicleID=VDP.vehicleID          
 WHERE                      
 (@bigFleetID IS NULL OR @bigFleetID='' OR f.FleetId=@bigFleetID) AND      
 (@intBoxID IS NULL OR @intBoxID='' OR @intBoxID='0' OR  VA.BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))              
 --AND (@dtStartDate BETWEEN DateFrom AND DateTo  or @dtEndDate BETWEEN DateFrom AND DateTo)  and               
 AND (DateFrom BETWEEN @dtStartDate AND @dtEndDate  or DateTo BETWEEN @dtStartDate AND @dtEndDate)  and               
 (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR VD.OrganizationId=@bigOrganizationID)               
order by DateFrom          
SET NOCOUNT OFF                          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetWidgets]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_GetWidgets]  
@UserId int,  
@GetCount int,  
@GetTitles varchar(1500)  
AS  
BEGIN  
SET NOCOUNT ON  
 Declare @qry varchar(max) = ' Declare @Count int '+  
        ' SELECT @Count=COUNT(*) FROM rvlfWidgets WHERE UserId='+Cast(@UserId as varchar)+ ' AND Title in ('+@GetTitles+') '+  
        ' IF '+Cast(@GetCount as varchar)+'> @Count OR '+Cast(@GetCount as varchar)+'< @Count '+  
        ' BEGIN '+  
        ' DELETE rvlfWidgets WHERE UserId='+Cast(@UserId as varchar)+' '+  
        ' END'  
 Exec(@qry)  
	SELECT UserId,ColumnId,SortNo,Collapsed,Title,Status FROM rvlfWidgets WHERE UserId=@UserId and ColumnId=1 Order by SortNo asc   
    SELECT UserId,ColumnId,SortNo,Collapsed,Title,Status FROM rvlfWidgets WHERE UserId=@UserId and ColumnId=2 Order by SortNo asc   
    SELECT UserId,ColumnId,SortNo,Collapsed,Title,Status FROM rvlfWidgets WHERE UserId=1 and ColumnId=1 and [Status]='D' Order by SortNo asc  
    SELECT UserId,ColumnId,SortNo,Collapsed,Title,Status FROM rvlfWidgets WHERE UserId=1 and ColumnId=2 and [Status]='D' Order by SortNo asc  
SET NOCOUNT OFF  
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GetWriteParam]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_GetWriteParam]
@bigVehicleID tinyint
 as begin
 select ParamID,ParamName from rvlfWriteParams where EquipmentType=@bigVehicleID
 end
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_GPRSBGProcess]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_GPRSBGProcess]    
@MessageInID uniqueidentifier=null,    
@latitude decimal(10,6)=0,    
@longitute decimal(10,6)=0    
as    
begin    
if @latitude=0 and @MessageInID IS NULL    
begin    
select top 1 MessageInID,BoxId,    
OriginDateTime,BoxMsgInTypeId,CustomProp from rvlfMsgInHst  
where ValidGps=-1 and BoxMsgInTypeId=154 and OriginDateTime >  '2014-03-28 00:00:00.000' 
end    
else    
begin    
update rvlfMsgInHst set Latitude=@latitude, Longitude=@longitute,ValidGps=0,IsProcessed=1 where MessageInID=@MessageInID    
select 1    
end    
    
end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ImportContainerFuelDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
            
CREATE PROCEDURE [dbo].[rvlf_sp_ImportContainerFuelDetails]             
 -- Add the parameters for the stored procedure here             
 @TableXML XML = NULL ,            
 @OrgID INT = NULL,           
 @UserID BIGINT = NULL         
     
AS  
-- =============================================            
-- Author:  kapil            
-- Create date: 07-May-2014    
-- Description: Import ContainerFuel entry into the DB.            
-- =============================================          
BEGIN            
 -- SET NOCOUNT ON added to prevent extra result sets from            
 -- interfering with SELECT statements.            
 SET NOCOUNT ON;      
 SET ANSI_WARNINGS OFF;  
    DECLARE @TblCotainerImport TABLE                        
 (         
 ContainerName varchar(50),    
 MeterReading BIGINT,    
 FuelQuantity FLOAT,    
 Value FLOAT,    
 Date DATETIME            
 )    
    DECLARE @Error INT       
    DECLARE @Total INT          
    DECLARE @Error1 INT          
    DECLARE  @Proceed  INT    
    DECLARE @tblName varchar(30) = '/NewDataSet/Table'                
    DECLARE @Index AS INT;            
    SET @Index = 0;                                                
    EXEC Sp_xml_preparedocument  @Index OUTPUT,@TableXML                    
    BEGIN TRY            
    INSERT INTO @TblCotainerImport (ContainerName,MeterReading,FuelQuantity,Value,Date) 
    SELECT ContainerName,MeterReading,FuelQuantity,Value,CONVERT(DATETIME,[Date],103) 
    FROM   OPENXML (@Index, @tblName) 
          WITH (ContainerName     VARCHAR(30) 'RefrigeratorName',          
                MeterReading      VARCHAR(30) 'MeterReading',    
                FuelQuantity VARCHAR(50) 'FuelQuantity',    
                Value varchar(100) 'Value',                   
                Date VARCHAR(10) 'Date'             
                )SA      
    END TRY   
     BEGIN CATCH  
  RAISERROR('Import Failed! Incorrect Data format',15,0) 
 return  
 end catch              
   delete from @TblCotainerImport where ContainerName not in (select RefgName from rvlfRefrigeration where IsDelete =0) AND ContainerName is not null     
        
   --select * from @TblCotainerImport 
    Declare @TemptblFuelDetails table    
    (    
  RefID INT,     
 AVGFUEL FLOAT,    
 MeterReading BIGINT,    
 FuelQty FLOAT,    
 Value FLOAT,    
 [CreatedDate] DateTime  
    )   
INSERT INTO @TemptblFuelDetails  
select R.RefgId,R.AvgFuel,T.MeterReading,T.FuelQuantity,T.Value,T.[Date] from @TblCotainerImport T   
INNER JOIN rvlfRefrigeration R on T.ContainerName = R.RefgName    
--INNER join rvlfVehicles V ON R.RefgId = V.RefgId AND R.IsDelete =0    
   inner join rvlfRefrigeratorAssignmt RA on R.RefgId=RA.RefgId and UnAssignDate is null  
 select * from @TemptblFuelDetails  
 SET @Total =(SELECT ISNULL(COUNT(*),0) from @TblCotainerImport)  
 SET @Error =(select ISNULL(COUNT(*),0) from @TemptblFuelDetails where RefID in (select RefgId from rvlfFuelContainer) AND MeterReading in (select f.Odometer from rvlfFuelContainer F))    
 SET @Error1 = (select COUNT(*) from @TemptblFuelDetails)    
 SET @Proceed = (select COUNT(*) from @TemptblFuelDetails) 
--print @Error    
--print @Error1    
--print @Proceed    
--print @Total    
 IF(@Proceed=0)    
  BEGIN    
       RAISERROR('Import Failed! No Refrigeration Matched with vehicle,Kindly check and try Again',15,0)  
   --  RAISERROR('Fuel Details for Vehicles Imported Successfully',15,0)   
    RETURN         
  END  
 DECLARE @RefID INT,@AvgCons FLOAT,@Odometer varchar(10), @FuelQty FLOAT,@Value FLOAT,@Date DateTIME   
 DECLARE cursorName CURSOR -- Declare cursor    
--LOCAL SCROLL STATIC     
   FOR   
    Select RefID,AVGFUEL,MeterReading,FuelQty,Value,CreatedDate FROM @TemptblFuelDetails     
    OPEN cursorName -- open the cursor        
    FETCH NEXT FROM cursorName         
    INTO @RefID,@AvgCons,@Odometer,@FuelQty,@Value,@Date  
     WHILE @@FETCH_STATUS = 0   
        BEGIN             
        declare @CURRCONSUMPTION FLOAT,@ExsLessQty FLOAT,@Variance VARCHAR(10),@Price VARCHAR(10),@Mileage VARCHAR(20)    
     DEclare @Maxodometer bigint          
         
     SET @Maxodometer = (select ISNULL(MAX(odometer),0) from rvlfFuelContainer where RefgId = @RefID AND IsDelete =0)    
                      
        SET @CURRCONSUMPTION = CONVERT(DECIMAL(10,2),((@FuelQty)/(@Odometer-@Maxodometer)))    
            
     IF NOT EXISTS(select RefgId from rvlfFuelContainer where RefgId = @RefID and Odometer=@Odometer and IsDelete =0)              
         
        INSERT INTO  rvlfFuelContainer (RefgId,Odometer,Date,FuelQty,Value,AvgConsumption,CurrConsumption,ExsLessQty,Variance,CreatedBy,CreatedDate,IsDelete,Price,Mileage)     
            
        VALUES (@RefID,@Odometer,@Date,@FuelQty,@Value,@AvgCons,    
        @CURRCONSUMPTION,             
         ((@AvgCons)- (@CURRCONSUMPTION)),    
        ((@AvgCons -@CURRCONSUMPTION)/(@AvgCons))*100,    
        @UserID,GETUTCDATE(),0,    
        ((@Value)/(@FuelQty)),  
        ((@CURRCONSUMPTION)/(@Odometer-@Maxodometer)))  
        FETCH NEXT FROM cursorName  
        INTO @RefID,@AvgCons,@Odometer,@FuelQty,@Value,@Date  
        END  
   CLOSE cursorName -- close the cursor  
DEALLOCATE cursorName -- Dealloc  
END  
 --print 'ccc' 
IF(@Error1=0)  
BEGIN    
 --print 'Err1'    
    RAISERROR('Refrigeration Fuel Details Imported Successfully',15,0)  
RETURN   
END   
 ELSE IF(@Error1<>@Total)  
  BEGIN    
 -- print 'Err2'    
   RAISERROR('Some of Duplicate Found! Remaining Imported Successfully',15,0)   
 RETURN   
 END   
 ELSE IF(@Error=@Total)    
 --print 'Err3'    
  BEGIN    
  RAISERROR('Duplicate Found Remaining Imported!',15,0)  
 RETURN    
 END       
    
    
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ImportFuelEntry]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================          
-- Author:  Vijay N          
-- Create date: 23-Nov-2012          
-- Description: Import Fuel entry into the DB.          
-- =============================================          
CREATE PROCEDURE [dbo].[rvlf_sp_ImportFuelEntry]           
 -- Add the parameters for the stored procedure here           
 @TableXML XML = NULL ,          
 @OrgID INT = NULL,          
 @UserID BIGINT = NULL          
AS          
BEGIN          
 -- SET NOCOUNT ON added to prevent extra result sets from          
 -- interfering with SELECT statements.          
 SET NOCOUNT ON;          
          
    -- Insert statements for procedure here        
        
    -- SET @TableXML = REPLACE(@TableXML,'FuelCost(Per Ltr)','FuelCost');    
          
DECLARE @HoursToBeAdded INT = 0              
DECLARE @MinsToBeAdded INT = 0              
DECLARE @ConversionFactor decimal(18,2) = 1.0  
                               
SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,  
@ConversionFactor = CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 END                             
FROM [DBO].[rvlfUserPreferences] up INNER JOIN [DBO].[rvlfTimeZones] tz                            
ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @UserID    
          
      
              
    DECLARE @TemptblFuel TABLE                      
 (          
  VehicleName        Varchar(250),          
  VehicleID          BIGINT NULL,          
  FuelFilledDateTime DATETIME,          
  FuelFilled         DECIMAL(18,2),          
  FuelCost           DECIMAL(18,2),          
  FuelStation        VARCHAR(250) ,          
  Comments           VARCHAR(250),          
  OrgID      INT,          
  UserID      BIGINT           
 )          
              
              
    DECLARE @tblName varchar(30) = '/NewDataSet/Table'              
    DECLARE @Index AS INT;          
    SET @Index = 0;                                              
    EXEC Sp_xml_preparedocument  @Index OUTPUT,@TableXML           
              
              
    INSERT INTO @TemptblFuel (VehicleName,FuelFilledDateTime,FuelFilled,FuelCost,    
    FuelStation,Comments,OrgID,UserID)              
    SELECT VehicleName,FuelFilledDateTime,FuelFilled,FuelCost,FuelStation,Comments,@OrgID,@UserID          
    FROM   OPENXML (@Index, @tblName)          
          WITH (VehicleName            VARCHAR(250) 'VehicleName',    
                FuelFilledDateTime     DATETIME 'FuelFilledDateTime',    
                FuelFilled             DECIMAL(18,2) 'FuelFilled',    
                FuelCost               DECIMAL(18,2) 'FuelCost',    
                FuelStation            VARCHAR(250) 'FuelStation',    
                Comments               VARCHAR(250)  'Comments') SA    
                          
          
          
 UPDATE F SET F.VehicleID = V.VehicleId,      
 FuelFilledDateTime = FuelFilledDateTime,
 --DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,FuelFilledDateTime)),  
 Fuelcost = (FuelCost / @ConversionFactor),FuelFilled = (FuelFilled * @ConversionFactor)  
 FROM @TemptblFuel F           
 INNER JOIN rvlfVehicle V ON F.VehicleName = V.VehicleDescription           
 WHERE OrganizationId = @OrgID          
           
 INSERT INTO rvlfFuelEntry(VehicleID,FuelFilledDateTime,FuelFilled,FuelCost,FuelStation,Comments,CreatedBy,CreatedDateTime)          
 SELECT VehicleID,FuelFilledDateTime,FuelFilled,FuelCost,FuelStation,Comments,@UserID,GETUTCDATE() FROM @TemptblFuel          
           
END   
  
--select * from rvlfFuelEntry  
  
--SELECT tz.HoursToBeAdded,tz.MinToBeAdded, CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 END                             
--FROM [DBO].[rvlfUserPreferences] up INNER JOIN [DBO].[rvlfTimeZones] tz                            
--ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = 303

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ImportGeozones]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_ImportGeozones]    
 @TableXML XML = NULL ,              
 @OrgID INT = NULL,              
 @UserID BIGINT = NULL,    
 @GeozoneType bigint = null               
AS              
/**********************************************************************    
-- Procedure Name : rvlf_sp_ImportGeozones    
-- Created By   :  Sakthi Gopinath S    
-- Create Date   : 20-Mar-2014    
-- Description   : Import Geozone details into the DB.              
***********************************************************************/    
BEGIN              
 SET NOCOUNT ON;              
    
 DECLARE @Latitude decimal(10,6)='17.298182';    
 DECLARE @Longitude decimal(10,6)='78.491297';    
 DECLARE @radiusOfEarth int = 6378137;    
 DECLARE @PI DECIMAL(10,6) = 3.14159;    
 DECLARE @meters DECIMAL(10,6) = 100.00;    
 DECLARE @degree DECIMAL(10,6) = 180.00;    
 DECLARE @dLat DECIMAL(10,6);    
 DECLARE @dLon DECIMAL(10,6);    
 DECLARE @tblName varchar(30) = '/NewDataSet/Table';    
 DECLARE @Index AS INT;     
 DECLARE @TotalGeozone AS INT = 0    
 DECLARE @CreatedGeozone AS INT = 0    
 DECLARE @AvailableGeozone AS INT = 0    
 DECLARE @AlertMessage VARCHAR(150) = '';    
 DECLARE @LimitReachedMsg VARCHAR(75)='';    
 declare @DefaultGeozoneid int =0  
 set @DefaultGeozoneid=(select top 1 CategoryId from rvlfCategory where OrganizationId=@OrgID)             
 DECLARE @TemptblGeozones TABLE                          
 (              
  id bigint identity(1,1),    
  GeozoneName Varchar(250),    
  GeozoneCategory Varchar(10),    
  Latitude DECIMAL(10,6),              
  Longitude DECIMAL(10,6),              
  OrgID INT,              
  UserID BIGINT,    
  Radius bigint null               
 ) 
 
   If @GeozoneType = 2     
    Begin                    
  SET @Index = 0;                                                      
  EXEC Sp_xml_preparedocument  @Index OUTPUT,@TableXML                   
                       
  INSERT INTO @TemptblGeozones (GeozoneName,GeozoneCategory,Latitude,Longitude,OrgID,UserID)                      
  SELECT GeozoneName,GeozoneCategory,Latitude,Longitude,@OrgID,@UserID            
  FROM OPENXML (@Index, @tblName)                  
  WITH (GeozoneName VARCHAR(250) 'GeozoneName',            
  GeozoneCategory VARCHAR(250) 'Category',            
  Latitude DECIMAL(10,6) 'Latitude',            
  Longitude DECIMAL(10,6) 'Longitude') SA            
    End    
    Else    
    Begin    
  SET @Index = 0;                                                      
  EXEC Sp_xml_preparedocument  @Index OUTPUT,@TableXML                   
                       
  INSERT INTO @TemptblGeozones (GeozoneName,GeozoneCategory,Latitude,Longitude,OrgID,UserID,Radius)                      
  SELECT GeozoneName,GeozoneCategory,Latitude,Longitude,@OrgID,@UserID,Radius            
  FROM OPENXML (@Index, @tblName)                  
  WITH (GeozoneName VARCHAR(250) 'GeozoneName',            
  GeozoneCategory VARCHAR(250) 'Category',            
  Latitude DECIMAL(10,6) 'Latitude',            
  Longitude DECIMAL(10,6) 'Longitude',    
  Radius DECIMAL(10,6) 'Radius') SA        
    End    
          
    DELETE @TemptblGeozones WHERE GeozoneName IS NULL        
    DELETE FROM @TemptblGeozones WHERE id NOT IN (SELECT min(id) FROM @TemptblGeozones GROUP BY GeozoneName)         
    DELETE FROM @TemptblGeozones WHERE GeozoneName IN        
    (SELECT GeozoneName FROM rvlfOrganizationGeozone WHERE OrganizationId=@OrgID)        
            
    SELECT @TotalGeozone = ISNULL(NoOfGeozones,0) FROM rvlfOrganization WHERE OrganizationId=@OrgID        
    SET @dLat = @meters/@radiusOfEarth        
        
    DECLARE @Count int = 0        
    SELECT @Count = MAX(Id) FROM @TemptblGeozones        
            
    IF ISNULL(@Count,0) = 0        
    BEGIN        
 SET @AlertMessage = 'Imported Geozone(s) are already created.'        
 SET @LimitReachedMsg = 'Already Created'        
    END        
      
    --select * from @TemptblGeozones  
    --Select GeozoneCategory FROM @TemptblGeozones WHERE GeozoneCategory not in  
    --(SELECT CategoryName FROM rvlfCategory WHERE OrganizationId = @OrgID)  
      
     IF Exists(Select GeozoneCategory FROM @TemptblGeozones WHERE GeozoneCategory not in  
    (SELECT CategoryName FROM rvlfCategory WHERE OrganizationId = @OrgID))  
     BEGIN        
  RAISERROR('Import Failed! Invalid Geozone Category Name',15,0)     
  RETURN     
    END      
      
        
   DECLARE @MaxId int = 0        
   DECLARE @i int = 1        
   WHILE @i <= ISNULL(@Count,0) AND @TotalGeozone > 0        
   BEGIN        
   SELECT @CreatedGeozone = COUNT(GeozoneNo) FROM rvlfOrganizationGeozone WHERE OrganizationId=@OrgID        
   SET @AvailableGeozone = @TotalGeozone - @CreatedGeozone        
           
   PRINT CAST(@i AS VARCHAR)+ '  Iteration'        
   PRINT CAST(@CreatedGeozone AS VARCHAR)        
   PRINT CAST(@AvailableGeozone AS VARCHAR)        
           
   IF @AvailableGeozone  BETWEEN 1 AND @TotalGeozone        
   BEGIN        
     SELECT @MaxId = MAX(GeozoneId)+1 FROM rvlfOrganizationGeozone WHERE OrganizationId=@OrgID        
                  
     INSERT INTO rvlfOrganizationGeozone(OrganizationId,GeozoneId,GeozoneName,GeozoneType,Direction,        
     Notify,Email,SMS,DayLightSaving,Warning,Critical,AutoAdjustDayLightSaving,        
     [Description],CreatedBy,CreatedDateTime,CategoryId,SeverityId,TimeZone,Radius)        
     SELECT @OrgID,@MaxId,GeozoneName,(Case when @GeozoneType = null then 1 else 3 end),3,0,'','',0,0,0,0,        
     GeozoneName,@UserID,GETUTCDATE(),        
     (SELECT ISNULL(CategoryId,@DefaultGeozoneid) FROM rvlfCategory WHERE OrganizationId=@OrgID AND         
     CategoryName=GeozoneCategory),1,3,Radius FROM @TemptblGeozones WHERE id=@i AND         
     Latitude IS NOT NULL AND Longitude IS NOT NULL        
             
     DECLARE @GeozoneNo int = 0        
     SELECT @GeozoneNo = @@IDENTITY        
             
     INSERT INTO rvlfGeozoneSet(GeozoneNo,SequenceNo,Latitude,Longitude)        
     SELECT @GeozoneNo, 0, (Latitude - @dLat * @degree / @PI) AS LeftLatitude,        
     (Longitude + (@meters/(@radiusOfEarth*COS(@PI*Latitude/@degree))) * @degree / @PI)  AS LeftLongitude        
     FROM @TemptblGeozones WHERE id=@i UNION ALL        
     SELECT @GeozoneNo, 1, (Latitude + @dLat * @degree / @PI) AS RightLatitude,        
     (Longitude - (@meters/(@radiusOfEarth*COS(@PI*Latitude/@degree))) * @degree / @PI)  AS RightLongitude        
     FROM @TemptblGeozones WHERE id=@i AND Latitude IS NOT NULL AND Longitude IS NOT NULL        
     SET @AlertMessage = 'Details of Geozone(s) imported successfully';        
   END        
   ELSE        
   BEGIN        
     SET @LimitReachedMsg = ' and Geozone Limit is reached. Kindly contact administrator'        
     SET @AlertMessage = @AlertMessage + @LimitReachedMsg        
   END        
   SET @i = @i + 1;        
    END        
            
    IF LEN(@AlertMessage) > 1 AND LEN(@LimitReachedMsg) > 1        
    BEGIN        
  RAISERROR(@AlertMessage,15,0)        
    END        
SET NOCOUNT OFF        
END                     
                 
--    SET @Index = 0;                                                  
--    EXEC Sp_xml_preparedocument  @Index OUTPUT,@TableXML               
                  
--    INSERT INTO @TemptblGeozones (GeozoneName,GeozoneCategory,Latitude,Longitude,OrgID,UserID)                  
--    SELECT GeozoneName,GeozoneCategory,Latitude,Longitude,@OrgID,@UserID              
--    FROM OPENXML (@Index, @tblName)              
-- WITH (GeozoneName VARCHAR(250) 'GeozoneName',        
-- GeozoneCategory VARCHAR(250) 'Category',        
--    Latitude DECIMAL(10,6) 'Latitude',        
--    Longitude DECIMAL(10,6) 'Longitude') SA        
      
--    DELETE @TemptblGeozones WHERE GeozoneName IS NULL  OR GeozoneCategory IS NULL OR   
--    Latitude IS NULL OR Longitude IS NULL  
--    DELETE FROM @TemptblGeozones WHERE id NOT IN (SELECT min(id) FROM @TemptblGeozones GROUP BY GeozoneName)     
--    DELETE FROM @TemptblGeozones WHERE GeozoneName IN    
--    (SELECT GeozoneName FROM rvlfOrganizationGeozone WHERE OrganizationId=@OrgID)    
        
--    SELECT @TotalGeozone = ISNULL(NoOfGeozones,0) FROM rvlfOrganization WHERE OrganizationId=@OrgID    
-- SET @dLat = @meters/@radiusOfEarth    
    
--    DECLARE @Count int = 0    
--    SELECT @Count = MAX(Id) FROM @TemptblGeozones    
        
--    IF ISNULL(@Count,0) = 0    
--    BEGIN    
--  SET @AlertMessage = 'Some of the duplicate Geozone(s) found remaining imported successfully.'    
--  SET @LimitReachedMsg = 'Already Created'    
--    END    
     
-- DECLARE @MaxId int = 0    
-- DECLARE @i int = 1    
-- WHILE @i <= ISNULL(@Count,0) AND @TotalGeozone > 0    
-- BEGIN    
--   SELECT @CreatedGeozone = COUNT(GeozoneNo) FROM rvlfOrganizationGeozone WHERE OrganizationId=@OrgID    
--   SET @AvailableGeozone = @TotalGeozone - @CreatedGeozone    
       
--   PRINT CAST(@i AS VARCHAR)+ '  Iteration'    
--   PRINT CAST(@CreatedGeozone AS VARCHAR)    
--   PRINT CAST(@AvailableGeozone AS VARCHAR)    
       
--   IF @AvailableGeozone  BETWEEN 1 AND @TotalGeozone    
--   BEGIN    
--     SELECT @MaxId = MAX(GeozoneId)+1 FROM rvlfOrganizationGeozone WHERE OrganizationId=@OrgID    
         
--     INSERT INTO rvlfOrganizationGeozone(OrganizationId,GeozoneId,GeozoneName,GeozoneType,Direction,    
--     Notify,Email,SMS,DayLightSaving,Warning,Critical,AutoAdjustDayLightSaving,    
--     [Description],CreatedBy,CreatedDateTime,CategoryId,SeverityId,TimeZone)    
--     SELECT @OrgID,@MaxId,GeozoneName,1,3,0,'','',0,0,0,0,    
--     GeozoneName,@UserID,GETUTCDATE(),    
--     (SELECT ISNULL(CategoryId,@DefaultGeozoneid) FROM rvlfCategory WHERE OrganizationId=@OrgID AND     
--     CategoryName=GeozoneCategory),1,3 FROM @TemptblGeozones WHERE id=@i AND     
--     Latitude IS NOT NULL AND Longitude IS NOT NULL    
         
--     DECLARE @GeozoneNo int = 0    
--     SELECT @GeozoneNo = @@IDENTITY    
         
--     INSERT INTO rvlfGeozoneSet(GeozoneNo,SequenceNo,Latitude,Longitude)    
--     SELECT @GeozoneNo, 0, (Latitude - @dLat * @degree / @PI) AS LeftLatitude,    
--     (Longitude + (@meters/(@radiusOfEarth*COS(@PI*Latitude/@degree))) * @degree / @PI)  AS LeftLongitude    
--     FROM @TemptblGeozones WHERE id=@i UNION ALL    
--     SELECT @GeozoneNo, 1, (Latitude + @dLat * @degree / @PI) AS RightLatitude,    
--     (Longitude - (@meters/(@radiusOfEarth*COS(@PI*Latitude/@degree))) * @degree / @PI)  AS RightLongitude    
--     FROM @TemptblGeozones WHERE id=@i AND Latitude IS NOT NULL AND Longitude IS NOT NULL    
--     SET @AlertMessage = 'Details of Geozone(s) imported successfully';    
--   END    
--   ELSE    
--   BEGIN    
--     SET @LimitReachedMsg = ' and Geozone Limit is reached. Kindly contact administrator'    
--     SET @AlertMessage = @AlertMessage + @LimitReachedMsg    
--   END    
--   SET @i = @i + 1;    
--    END    
        
--    IF LEN(@AlertMessage) > 1 AND LEN(@LimitReachedMsg) > 1    
--    BEGIN    
--  RAISERROR(@AlertMessage,15,0)    
--    END    
--SET NOCOUNT OFF    
--END     
    
--EXEC rvlf_sp_ImportGeozones N'<NewDataSet>    
--  <Table>    
--    <GeozoneName>RS PURAM</GeozoneName>    
--    <Category>CBE</Category>    
--    <Latitude>11.011297</Latitude>    
--    <Longitude>76.949995</Longitude>    
--  </Table>    
--  <Table>    
--    <GeozoneName>Sakthi Tirupur</GeozoneName>    
--    <Category>CBE</Category>    
--    <Latitude>11.106214</Latitude>    
--    <Longitude>77.341502</Longitude>    
--  </Table>    
--  <Table>    
--    <GeozoneName>Sakthi Kangeyam</GeozoneName>    
--    <Category>CBE</Category>    
--    <Latitude>11.007825</Latitude>    
--    <Longitude>77.560542</Longitude>    
--  </Table>    
--  <Table>    
--    <GeozoneName>Sakthi UAE</GeozoneName>    
--    <Category>CBE</Category>    
--    <Latitude>24.05311</Latitude>    
--    <Longitude>55.842975</Longitude>    
--  </Table>    
--</NewDataSet>',1,94

GO
/****** Object:  StoredProcedure [dbo].[rvlf_SP_ImportItemMaster]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_SP_ImportItemMaster]
 @TableXML XML =NULL,          
 @OrgID INT = NULL,          
 @UserID BIGINT = NULL 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @TempItemDet table
	(
		id bigint identity(1,1),
		ItemCode varchar(150),
		ItemName varchar(150),
		ItemDescription varchar(250),
		ItemCategory int,
		UnitofMeasure int,
		SerialNo varchar(20)
	)
		DECLARE @Index INT 
		set @Index= 0
		declare @Error nvarchar(Max)
		EXEC sp_xml_preparedocument @Index OUTPUT, @TableXML

		INSERT INTO @TempItemDet (ItemCode,ItemName,ItemDescription,ItemCategory,UnitofMeasure,SerialNo)              
		select * from OPENXML(@Index, '/NewDataSet/TheData')
	WITH(
			ItemCode nvarchar(150) 'ItemCode',
			ItemName  nvarchar(150) 'ItemName',
			ItemDescription nvarchar(250) 'ItemDescription',
			ItemCategory nvarchar(10) 'ItemCategory',
			UnitofMeasure nvarchar(10) 'UnitofMeasure',
			SerialNo nvarchar(10) 'SerialNo'
		   ) AS OT 

		declare @Count as int=0
		Declare @Start int=1
		select @Count=COUNT(*) from @TempItemDet
		declare @ItemcodeFrm varchar(50)=null,@ItemNameFrm varchar(150)=null,@ItemDescFrm varchar(300)=null,@ItemCatIDFrm int=null,@UoMFrm varchar(15)=null,@ItemImageFrm nvarchar(MAX)=null, @ItemSerialNo varchar(20)=null
		while @Start<=@Count
		BEGIN
			select @ItemcodeFrm=ItemCode,@ItemNameFrm=ItemName,@ItemDescFrm=ItemDescription,@ItemCatIDFrm=ItemCategory,@UoMFrm=UnitofMeasure,@ItemSerialNo=SerialNo from @TempItemDet where id=@Start
			exec rvlf_sp_GetSetItemDetails @ItemSNo =null,@Itemcode=@ItemcodeFrm,@ItemName=@ItemNameFrm,@ItemDesc=@ItemDescFrm,@AvailQty=0,@ReorderQty =0,@OpenQty=0,@UnitPrice=0.00,@bigOrganizationId = @OrgID,@bigUserId = @UserID,@ItemCatID=@ItemCatIDFrm ,@UoM =@UoMFrm,@SerialNo=@ItemSerialNo,@tblNotificationsList = null,@Operation ='I'
			set @Start=@Start+1
		end
		
    -- Insert statements for procedure here
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ImportLandmarks]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_ImportLandmarks]           
 @TableXML XML = NULL ,          
 @OrgID INT = NULL,          
 @UserID BIGINT = NULL          
AS          
/**********************************************************************
-- Procedure Name	: rvlf_sp_ImportLandmarks
-- Created By		:  Sakthi Gopinath S
-- Create Date		: 22-Oct-2013
-- Description		: Import Landmark details into the DB.          
***********************************************************************/
BEGIN          
 SET NOCOUNT ON;          
          
	DECLARE @TemptblLandmarks TABLE                      
	(         
		id bigint identity(1,1), 
		LandmarkName Varchar(250),          
		Latitude DECIMAL(10,6),          
		Longitude DECIMAL(10,6),          
		Radius int,          
		OrgID INT,          
		UserID BIGINT           
	)          
    Declare @Alert int = 0  
    declare @AlertMessage varchar(250)       
    DECLARE @tblName varchar(30) = '/NewDataSet/Table'              
    DECLARE @Index AS INT;          
    SET @Index = 0;                                              
    EXEC Sp_xml_preparedocument  @Index OUTPUT,@TableXML           
              
              
    INSERT INTO @TemptblLandmarks (LandmarkName,Latitude,Longitude,Radius,OrgID,UserID)              
    SELECT LandmarkName,Latitude,Longitude,Radius,@OrgID,@UserID          
    FROM OPENXML (@Index, @tblName)          
	WITH (LandmarkName VARCHAR(250) 'LocationName',    
    Latitude DECIMAL(10,6) 'Latitude',    
    Longitude DECIMAL(10,6) 'Longitude',    
    Radius int 'Radius') SA    
    
    DELETE @TemptblLandmarks WHERE LandmarkName IS NULL
    DELETE from @TemptblLandmarks where id not in (select min(id) from @TemptblLandmarks group by LandmarkName)                                                           
    delete from @TemptblLandmarks WHERE LandmarkName in(select LandmarkName from rvlfLandmark)
    
	INSERT INTO rvlfLandmark(LandmarkName,Description,Latitude,Longitude,Radius,CreatedBy,CreatedDateTime,OrganizationId,Notify,Warning,Critical,
	Email,SMS,TimeZone,LandmarkCategoryID,LandmarkType)
		
	SELECT LandmarkName,'',Latitude,Longitude,Radius,@UserID,GETUTCDATE(),@OrgID,0,0,0,'','',0,0,0 FROM @TemptblLandmarks	
    set @Alert = (select COUNT(*) from @TemptblLandmarks)    
	IF(ISNULL(@Alert,0) = 0)	
	  BEGIN  
	   SET @AlertMessage = 'Some of the duplicate Landmark(s) imported Failed. Kindly check and try again !'  
	  	RAISERROR(@AlertMessage,15,0)  
     END  		
--	SET @Alert = 'Lanmark(s) details imported successfully';  		
	

	
SET NOCOUNT OFF       
END   



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ImportOrganizationContactDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================          
-- Author:  Kapil K          
-- Create date: 23-Nov-2013          
-- Description: Import Other Contact Details entry into the Organization DB.          
-- =============================================          
create PROCEDURE [dbo].[rvlf_sp_ImportOrganizationContactDetails]           
 -- Add the parameters for the stored procedure here           
 @TableXML XML = NULL ,          
 @OrgID INT = NULL,          
 @UserID BIGINT = NULL          
AS          
BEGIN          
 -- SET NOCOUNT ON added to prevent extra result sets from          
 -- interfering with SELECT statements.          
 SET NOCOUNT ON;          
          
    -- Insert statements for procedure here        
                     
  DECLARE @TemptblContacts TABLE                      
 (          
  ContactPerson2        Varchar(100),
  ContactPerson3        Varchar(100),          
  ContactPerson4        Varchar(100),          
  ContactPerson5        Varchar(100),          
  ContactPerson6        Varchar(100), 
  ContactEmailID2       Varchar(150),          
  ContactEmailID3       Varchar(150),          
  ContactEmailID4       Varchar(150),          
  ContactEmailID5       Varchar(150),          
  ContactEmailID6       Varchar(150),                   
  OrganizationId		BIGINT NULL                  
        
 )     
              
              
    DECLARE @tblName varchar(30) = '/NewDataSet/Table'              
    DECLARE @Index AS INT;          
    SET @Index = 0;                                              
    EXEC Sp_xml_preparedocument  @Index OUTPUT,@TableXML           
   
     BEGIN TRY           
              
    INSERT INTO @TemptblContacts (OrganizationId,ContactPerson2,ContactPerson3,ContactPerson4,ContactPerson5,ContactPerson6,
    ContactEmailID2,ContactEmailID3,ContactEmailID4,ContactEmailID5,ContactEmailID6)   
    
                
    SELECT OrganizationId,ContactPerson2,ContactPerson3,ContactPerson4,ContactPerson5,ContactPerson6,
    ContactEmailID2,ContactEmailID3,ContactEmailID4,ContactEmailID5,ContactEmailID6        
    FROM   OPENXML (@Index, @tblName)          
          WITH (
				OrganizationId			BIGINT 'OrganizationId',
				ContactPerson2         VARCHAR(100) 'ContactPerson2',    
                ContactPerson3         VARCHAR(100) 'ContactPerson3', 
                ContactPerson4         VARCHAR(100) 'ContactPerson4', 
                ContactPerson5         VARCHAR(100) 'ContactPerson5',
                ContactPerson6         VARCHAR(100) 'ContactPerson6', 
                ContactEmailID2        VARCHAR(150) 'ContactEmailID2', 
                ContactEmailID3        VARCHAR(150) 'ContactEmailID3',               
                ContactEmailID4        VARCHAR(150) 'ContactEmailID4',                
                ContactEmailID5        VARCHAR(150) 'ContactEmailID5', 
                ContactEmailID6        VARCHAR(150) 'ContactEmailID6'                
                ) SA    
                          
    END TRY
   
   BEGIN CATCH

   RAISERROR('Import Failed! Incorrect Data format',15,0)
	
   RETURN 

   END CATCH	
   select * from @TemptblContacts
   
   DELETE FROM @TemptblContacts where OrganizationId IS NULL or OrganizationId =''
   DELETE FROM @TemptblContacts where OrganizationId NOT IN (select OrganizationId from rvlfOrganization)
   
   update @TemptblContacts set ContactEmailID2= CASE WHEN ContactEmailID2 NOT LIKE '%_@__%.__%' THEN NULL ELSE ContactEmailID2 END,
   ContactEmailID3= CASE WHEN ContactEmailID3 NOT LIKE '%_@__%.__%' THEN NULL ELSE ContactEmailID3 END,   
   ContactEmailID4= CASE WHEN ContactEmailID4 NOT LIKE '%_@__%.__%' THEN NULL ELSE ContactEmailID4 END,   
   ContactEmailID5= CASE WHEN ContactEmailID5 NOT LIKE '%_@__%.__%' THEN NULL ELSE ContactEmailID5 END,
   ContactEmailID6 = CASE WHEN ContactEmailID6 NOT LIKE '%_@__%.__%' THEN NULL ELSE ContactEmailID6 END
   
   WHERE  ContactEmailID2 <> ''
   OR ContactEmailID3 <> ''
   OR ContactEmailID4 <> ''
   OR ContactEmailID5 <> ''
   OR ContactEmailID6 <> ''
   
 --INSERT INTO rvlfOrganization(ContactPerson2,ContactPerson3,ContactPerson4,ContactPerson5,ContactPerson6,
 -- ContactEmailID2,ContactEmailID3,ContactEmailID4,ContactEmailID5,ContactEmailID6,ModifiedBy,ModifiedDateTime)  

UPDATE ORG SET ContactEmailID2 = CASE WHEN T.ContactEmailID2 = '' THEN NULL ELSE T.ContactEmailID2 END,
 ContactEmailID3 = CASE WHEN T.ContactEmailID3 ='' THEN NULL ELSE T.ContactEmailID3 END,
 ContactEmailID4 = CASE WHEN T.ContactEmailID4 ='' THEN NULL ELSE T.ContactEmailID4 END,
 ContactEmailID5 = CASE WHEN T.ContactEmailID5 ='' THEN NULL ELSE T.ContactEmailID5 END,
 ContactEmailID6 = CASE WHEN T.ContactEmailID6 ='' THEN NULL ELSE T.ContactEmailID6 END,
 ContactPerson2 =  CASE WHEN T.ContactPerson2 = '' THEN NULL ELSE T.ContactPerson2  END ,
 ContactPerson3 =  CASE WHEN T.ContactPerson3 = '' THEN NULL ELSE T.ContactPerson3  END,
 ContactPerson4 =  CASE WHEN T.ContactPerson4 = '' THEN NULL ELSE T.ContactPerson4  END,
 ContactPerson5 =  CASE WHEN T.ContactPerson5 = '' THEN NULL ELSE T.ContactPerson5  END,  
 ContactPerson6 =  CASE WHEN T.ContactPerson6 = '' THEN NULL ELSE T.ContactPerson6  END
,ModifiedBy = @UserID,ModifiedDateTime = GETUTCDATE()
 from rvlfOrganization ORG INNER JOIN @TemptblContacts T ON ORG.OrganizationId = T.OrganizationId
 
 --RAISERROR('Imported Successfully!',15,0)     
      
          
--SELECT ContactPerson2,ContactPerson3,ContactPerson4,ContactPerson5,ContactPerson6,
--CASE WHEN ContactEmailID2 = '' THEN NULL ELSE ContactEmailID2 END as ContactEmailID2,ContactEmailID3,ContactEmailID4,ContactEmailID5,ContactEmailID6,@UserID,GETUTCDATE() FROM @TemptblContacts          
           
END   


--[rvlf_sp_ImportOrganizationContactDetails]'<NewDataSet>
--  <Table>
--    <OrganizationId>6</OrganizationId>
--    <ContactPerson2></ContactPerson2>
--    <ContactEmailID2>kapil@g,a.com</ContactEmailID2>
--    <ContactPerson3>ContactPerson3</ContactPerson3>
--    <ContactEmailID3>ContactEmailID3gmailcom</ContactEmailID3>
--    <ContactPerson4>ContactPerson4</ContactPerson4>
--    <ContactEmailID4>ContactEmailID4@gmailcom</ContactEmailID4>
--    <ContactPerson5>ContactPerson5</ContactPerson5>
--    <ContactEmailID5>ContactEmailID5@gmail.</ContactEmailID5>
--    <ContactPerson6>ContactPerson6</ContactPerson6>
--    <ContactEmailID6>ContactEmailID6@gmail.com</ContactEmailID6>
--  </Table>
--  <Table>
--    <OrganizationId>1</OrganizationId>
--    <ContactPerson5>ContactPerson5</ContactPerson5>
--    <ContactEmailID5>ContactEmailID5@gmail.com</ContactEmailID5>
--    <ContactPerson6>ContactPerson6</ContactPerson6>
--    <ContactEmailID6>ContactEmailID6@gmail.com</ContactEmailID6>
--  </Table>  
--</NewDataSet>',6,18

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_InsertCategory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_InsertCategory]
	-- Add the parameters for the stored procedure here	
	@categoryId int,
	@categoryName nvarchar(50), 
	@CategoryDescription varchar(500), 
	@organizationId bigint
AS
DECLARE @count as int 
SET @count = 0
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
    IF(@categoryId=0)
		BEGIN
				SET @count = (SELECT COUNT(*) FROM rvlfCategory WHERE CategoryName = @categoryName AND OrganizationId = @organizationId)
				IF(@count=0)
					BEGIN
						INSERT INTO rvlfCategory
							(CategoryName, CategoryDescription, OrganizationId) 
								VALUES
							(@categoryName, @CategoryDescription, @organizationId)
						SELECT @@identity AS CategoryCount
					END
				ELSE
					BEGIN
						SET @count = 0
						SELECT @count AS CategoryCount
					END	
		END
	ELSE
		BEGIN
			SET @count = (SELECT COUNT(*) FROM rvlfCategory WHERE CategoryId <> @categoryId AND OrganizationId = @organizationId AND CategoryName = @categoryName)
			IF(@count=0)
				BEGIN
					UPDATE rvlfCategory SET 
						CategoryName = @categoryName, 
						CategoryDescription = @CategoryDescription, 
						OrganizationId = @organizationId 
						WHERE CategoryId = @categoryId AND OrganizationId = @organizationId
						
					SELECT @categoryId AS CategoryCount
				END
			ELSE
				BEGIN
					SET @count = 0
					SELECT @count AS CategoryCount
				END
			
		END
		
	
	SELECT CategoryId, CategoryName, CategoryDescription,
	CASE WHEN EXISTS(SELECT OG.CategoryId FROM rvlfOrganizationGeozone OG WHERE OG.CategoryId = rvlfCategory.CategoryId) 
		THEN 1 ELSE 0 END AS AssignedStatus  
	FROM rvlfCategory where OrganizationId = @organizationId
	
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_InsertLandmarkCategory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================    
-- Author:  <>    
-- Create date: <>  
-- Description: <Description,,>  
-- rvlf_sp_InsertLandmarkCategory 1,null,'-Select Category-','My Category One','~/images/Org_1/Landmarks' 
-- =============================================    
CREATE PROCEDURE [dbo].[rvlf_sp_InsertLandmarkCategory]    
 @OrganizationId bigint,   
 @CategoryId bigint = NULL,   
 @CategoryName varchar(255),    
 @Description varchar(500),  
 @ImagePath varchar(500)  
   
AS    
DECLARE @count as int   
SET @count = 0  
  
BEGIN    
 SET NOCOUNT ON;    
    
    DECLARE @IsDuplicate AS BIT = 1
    
    --SET @count = (SELECT COUNT(*) FROM rvlfLandmarkCategory WHERE CategoryName = @categoryName AND OrganizationId = @organizationId)  
    IF(@CategoryId > 0)  
     BEGIN  
        
        IF NOT EXISTS(SELECT CategoryName FROM rvlfLandmarkCategory WHERE CategoryName = @CategoryName AND LandmarkCategoryID <> @CategoryId AND OrganizationId = @OrganizationId)
        BEGIN
        
			Update rvlfLandmarkCategory  set  
			CategoryName = @categoryName,  
			[Description] = @Description,
			ImagePath=@ImagePath    
			where LandmarkCategoryID = @CategoryId  
			
			SET @IsDuplicate = 0
		
		END
               
     END  
    ELSE  
     BEGIN  
      
      IF NOT EXISTS(SELECT CategoryName FROM rvlfLandmarkCategory WHERE CategoryName = @CategoryName AND OrganizationId = @OrganizationId)
        BEGIN
        
		  Insert into rvlfLandmarkCategory     
		   (OrganizationId,CategoryName,[Description],ImagePath)    
			values    
		   (@OrganizationId,@CategoryName,@Description,@ImagePath)  
		 
		  SET @IsDuplicate = 0
		 
		END
	       
     END   
     
     SELECT @IsDuplicate AS IsDuplicate
  
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_InsertSelectTemplate]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_InsertSelectTemplate]     
/*************************************************************************************    
Stored Procedure Name : [rvlf_sp_InsertSelectTemplate]    
Purpose               : Select and Insert Template
Created by            : Ranjith   
Created date          : 25-Aug-11    
**************************************************************************************/    
@IntReleaseTemplateId numeric=null,
@vcTemplateName varchar(200)=null,
@vcTemplate varchar(max)=null,
@IntFlag int=null
AS  
begin
--Inserting New Template Details
if @IntFlag =1
   begin
       insert into rvlfReleaseTemplate(TemplateName,Template)values
         (@vcTemplateName,@vcTemplate)   
    end
--Getting All Template
else if @IntFlag =2
     begin       
        select * from rvlfReleaseTemplate order by TemplateName        
     end
--Getting Particular Template
else if @IntFlag =3
     begin       
        select * from rvlfReleaseTemplate where ReleaseTemplateId =@IntReleaseTemplateId
     end
--Updating Template
else if @IntFlag =4
     begin       
        Update rvlfReleaseTemplate set TemplateName = @vcTemplateName, Template = @vcTemplate  where ReleaseTemplateId =@IntReleaseTemplateId
     end
--Checking duplicate Template Name Entry  
else if @IntFlag =5  
     begin  
      select * from rvlfReleaseTemplate   
         where lower(replace(TemplateName,' ',''))=lower(replace(@vcTemplateName,' ',''))       
     end  
--Deleting Existing Template 
else if @IntFlag =6  
     begin  
      delete from rvlfReleaseTemplate   
         where ReleaseTemplateId =@IntReleaseTemplateId
     end  
end




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_InsertUpdateSelectAPNSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_InsertUpdateSelectAPNSettings]     
/*************************************************************************************    
Stored Procedure Name : rvlf_sp_InsertUpdateSelectAPNSettings    
Purpose               : Select,Insert and Modify APN Settings
Created by            : Ranjith   
Created date          : 10-June-11    
Updated by            : Sakthi Gopinath S set provider name for commModeName   
Updated date          : 17-Jun-11
Updated by            : Ranjith for display Provider name in Grid
Updated date          : 08-Jul-11
			          : Sakthi - 27-06-2012, Include CommModeAddresstype for New APN
**************************************************************************************/    
@BigIntCommModeId int=null,    
@vcProviderName varchar(50)=null,
@vcDisplayName varchar(50)=null,
@vcDesc varchar(250)=null,
@vcAPNName varchar(50)=null,
@vcAPNHex nvarchar(400)=null,
@vcUser varchar(20)=null,
@vcUserHex nvarchar(400)=null,
@vcPwd varchar(20)=null,
@vcPwdHex nvarchar(400)=null,
@vcSystemInstalled varchar(50)=null,
@vcTotalChunks nvarchar(800)=null,
@IntFlag int=null
AS  
begin
--Inserting New APN Details
if @IntFlag =1
   begin
	   DECLARE @commModeId int
	   ---Communication Info table
       insert into rvlfCommMode(CommModeId,CommModeName,CommModeDesc)values
         ((select isnull(MAX(CommModeId),0)+1  as CommModeId from rvlfCommMode),@vcProviderName,@vcDesc)
	   SELECT @commModeId = MAX(CommModeId) from rvlfCommMode
       ---Communication Services table
       insert into rvlfServices(ServiceID,CommModeId,ServiceName,DisplayName,Description,SystemInstalled)values
         ((select isnull(MAX(ServiceID),0)+1 as ServiceID  from rvlfServices),@commModeId,@vcProviderName,@vcDisplayName,@vcDesc,@vcSystemInstalled)
	   ---Communication Channels table
       insert into rvlfChannels(ChName,BoxProtocolTypeId,CommModeId)values
         (@vcAPNName,1,@commModeId)
       ---Communication address type table
       INSERT INTO rvlfCommModeAddressType(CommModeId,CommAddressTypeId) VALUES(@commModeId,1)
	   ---APN Settings table
       insert into rvlfapnsettings(CommModeId,APNName,APNHex,APNUser,APNUserHex,APNPwd,APNPwdHex,TotalChunk)values
          (@commModeId,@vcAPNName,@vcAPNHex,@vcUser,@vcUserHex,@vcPwd,@vcPwdHex,@vcTotalChunks)
    end
--Updating Existing APN Details
else if @IntFlag =2
    begin
       update rvlfCommMode set CommModeName=@vcProviderName,CommModeDesc=@vcDesc where CommModeId=@BigIntCommModeId
       update rvlfServices set ServiceName=@vcProviderName,DisplayName=@vcDisplayName,Description=@vcDesc,SystemInstalled=@vcSystemInstalled  where CommModeId=@BigIntCommModeId
       update rvlfChannels set ChName=@vcAPNName where CommModeId=@BigIntCommModeId
       update rvlfapnsettings set APNName=@vcAPNName,APNHex=@vcAPNHex,APNUser=@vcUser,APNUserHex=@vcUserHex,APNPwd=@vcPwd,APNPwdHex=@vcPwdHex,TotalChunk=@vcTotalChunks where CommModeId=@BigIntCommModeId
    end
--Selecting Particular APN
else if @IntFlag =3
     begin       
        select rvlfapnsettings.CommModeId,rvlfapnsettings.APNName,rvlfapnsettings.APNUser,rvlfapnsettings.APNPwd, rvlfCommMode.CommModeDesc,rvlfServices.DisplayName,rvlfServices.ServiceName 
         from rvlfapnsettings 
        inner join rvlfCommMode on rvlfCommMode.CommModeId=rvlfapnsettings.CommModeId
        inner join rvlfServices on rvlfServices.CommModeId=rvlfCommMode.CommModeId
        where rvlfapnsettings.CommModeId=@BigIntCommModeId     
     end
--Getting All APN Details
else if @IntFlag =4
     begin
       --select  * from rvlfapnsettings order by APNName
       select a.CommModeId,a.APNName,a.APNUser,a.APNPwd,c.CommModeName  from rvlfapnsettings a
           inner join rvlfCommMode c
             on c.CommModeId=a.CommModeId
     end
--Checking duplicate Provider Entry
else if @IntFlag =5
     begin
       select  * from rvlfServices where ServiceName=@vcProviderName
     end

end




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_InsertUpdateSelectIbuttonSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_InsertUpdateSelectIbuttonSettings]         
/*************************************************************************************        
Stored Procedure Name : rvlf_sp_InsertUpdateSelectIbuttonSettings        
Purpose               : Select,Insert,Modify and Delete Ibutton Settings    
Created by            : Ranjith       
Created date          : 07-July-11        
Updated by            :      
Updated date          :      
**************************************************************************************/        
@BigIntIbuttonId int=null,       
@vcIButtonKey varchar(50)=null,    
@vcIButtonName varchar(50)=null,    
@vcOrgId int=null,    
@IntFlag int=null,  
@IntKeyType int=null,  
@drvName varchar(50) = NULL  
AS      
begin    
--Inserting New Ibutton Details    
if @IntFlag =1    
   begin    
       insert into rvlfIButtonMapping(IButtonKey,IButtonKeyName,OrganizationId,KeyType)values    
         (@vcIButtonKey,@vcIButtonName,@vcOrgId,@IntKeyType)         
    end    
--Updating Existing IButton Details    
else if @IntFlag =2    
    begin    
       update rvlfIButtonMapping set IButtonKey=@vcIButtonKey,IButtonKeyName=@vcIButtonName,    
       OrganizationId=@vcOrgId,KeyType=@IntKeyType     
       where IButtonId=@BigIntIbuttonId         
    end    
--Selecting Particular Ibutton    
else if @IntFlag =3    
     begin           
        select IButtonKey,IButtonKeyName,KeyType,UserName from rvlfIButtonMapping             
        where IButtonId=@BigIntIbuttonId         
     end    
--Deleting Existing IButton Details    
else if @IntFlag =4    
    begin    
       Delete from rvlfIButtonMapping      
       where IButtonId=@BigIntIbuttonId         
    end    
    
--Getting All IButton Details    
else if @IntFlag =5    
     begin    
       --select  * from rvlfIButtonMapping where OrganizationId=@vcOrgId order by IButtonKeyName    
       select i.IButtonId,i.IButtonKey,i.IButtonKeyName,i.IButtonKeyName,(case when @IntKeyType =1 then d.DriverName else i.UserName end) as Keyuser from rvlfIButtonMapping i    
         left join rvlfDriverMaster d on d.DriverId=i.DriverId    
          where i.OrganizationId=@vcOrgId and KeyType=@IntKeyType  order by i.IButtonKeyName    
     end    
--Checking duplicate IbuttonKey Entry    
else if @IntFlag =6    
     begin    
     select * from rvlfIButtonMapping     
          where lower(replace(IButtonKey,' ',''))=lower(replace(@vcIButtonKey,' ',''))    
       and (@BigIntIbuttonId IS NULL OR @BigIntIbuttonId='' Or  IButtonId <> @BigIntIbuttonId)     
       --select * from rvlfIButtonMapping     
       --where lower(replace(IButtonKey,' ',''))=lower(replace(@vcIButtonKey,' ',''))    
     end    
--Checking duplicate Ibutton Name Entry    
else if @IntFlag =7    
     begin    
      select * from rvlfIButtonMapping     
         where lower(replace(IButtonKeyName,' ',''))=lower(replace(@vcIButtonName,' ',''))     
           and OrganizationId=@vcOrgId    
        and (@BigIntIbuttonId IS NULL OR @BigIntIbuttonId='' Or  IButtonId <> @BigIntIbuttonId)    
       --select * from rvlfIButtonMapping     
       --where lower(replace(IButtonKeyName,' ',''))=lower(replace(@vcIButtonName,' ','')) and OrganizationId=@vcOrgId    
     end
     
--Checking RFID already exists for any Students  
 else if @IntFlag = 8   
 begin          
    SELECT * FROM rvlfStudentMaster  
    WHERE ((@vcIButtonKey IS NULL OR @vcIButtonKey='') OR RFID = @vcIButtonKey)  
 end  
end  
  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_InsertUpdateTyreDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
              
CREATE PROCEDURE [dbo].[rvlf_sp_InsertUpdateTyreDetails]              
@Vendorid int=null,     
@TyreID int = NULL,        
@bigOrganizationId bigint = Null,                            
@bigUserId bigint = Null ,   
@BrandName varchar(25), 
@BillNo varchar(25),
@Warranty varchar(25),
@PurchaseDate date,
@cost money,
@LifeTime varchar(15),
@Modal varchar(25),              
@Qty BIGINT,              
@Size varchar(25),                            
@Width varchar(25),              
@TotalAmount Money  
AS              
-- =============================================              
-- Name   : rvlf_sp_InsertUpdateTyreDetails              
-- Author  : Kapil              
-- Create date : 19-Feb-2014              
-- Description : Insert & update Tyre Vendor Details              
-- Company  : TRINETRA
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
-- =============================================              
BEGIN              
 -- SET NOCOUNT ON added to prevent extra result sets from              
 -- interfering with SELECT statements.              
 SET NOCOUNT ON;              
 
 declare @ErrorMessage varchar(max)=null      
         
 if(@TyreID is null) 
 begin        
  --if Not exists (select * from rvlfTyreMaster where VendorName = @VendorName and IsDelete=0)       
  --begin           
   Insert into rvlfTyreMaster (VendorId,BrandID,DateOfPurchase,TyreBillNo,Quantity,TyreCost,TotalAmount,TyreWidth,TyreSize,ModelID,TyreLifetime,Warranty,
   CreatedBy,CreatedDateTime,ModifiedBy,ModifiedDateTime,IsDelete,IsActive,OrganizationId)
                  
   values (@Vendorid,@BrandName,@PurchaseDate,@BillNo,@Qty,@cost,@TotalAmount,@Width,@Size,@Modal,@LifeTime,@Warranty,
   @bigUserId,GETUTCDATE(),null,null,0,1,@bigOrganizationId)
   
   update rvlfTyreMaster set TyreCode = 'TR'+ CAST(TyreId as varchar)   
   
   
   SET @TyreID = @@IDENTITY     
   
   IF NOT EXISTS(select * from rvlfTyreStock where vendorID = @Vendorid  and 
   OrganizationID = @bigOrganizationId   and BrandID = @BrandName and ModelID = @Modal)
   
		   BEGIN    
		      
			   insert into rvlfTyreStock (TyreID,VendorID,TotalQuantity,CreatedDateTime,BrandID,ModelID,OrganizationID) values (@TyreID,@Vendorid,@Qty,GETUTCDATE(),@BrandName,@Modal,@bigOrganizationId)
			   --select * from rvlfTyreStock
		   END 
   
   ELSE
   
		   BEGIN       
			
			declare @Total bigint
			
			set @Total=    (select TotalQuantity  from rvlfTyreStock  where OrganizationId=@bigOrganizationId 
			   and VendorID = @Vendorid and BrandID = @BrandName and ModelID = @Modal)			
				
			   update rvlfTyreStock set TotalQuantity = ISNULL(@Total,0) + ISNULL(@Qty,0)
			   where OrganizationId=@bigOrganizationId 
			   and VendorID = @Vendorid and BrandID = @BrandName and ModelID = @Modal
		   END             
		   
   select 1
  --end      
  --else      
  -- select 0          
 end        
        
 else   --Update vendors       
  
 begin       
   
  update rvlfTyreMaster set 
  VendorId = @Vendorid
 ,BrandID = @BrandName
 ,DateOfPurchase = @PurchaseDate 
 ,TyreBillNo=  @BillNo
 ,Quantity = @Qty
 ,TyreCost = @cost
 ,TotalAmount = @TotalAmount
 ,TyreWidth= @Width
 ,TyreSize= @Size
 ,ModelID = @Modal
 ,TyreLifetime=@LifeTime  
 ,Warranty = @Warranty
 ,ModifiedBy=@bigUserId,ModifiedDateTime=GETUTCDATE()          
  where TyreId=@TyreID and OrganizationId=@bigOrganizationId 
        
   update rvlfTyreStock set TotalQuantity = @Qty
   where TyreId=@TyreID and 
   OrganizationId=@bigOrganizationId 
   and VendorID = @Vendorid
  
  
  select 1      
  
 end  
  
update rvlfTyreStock set Available = (TotalQuantity-ISNULL(UsedQuantity,0)),UsedQuantity = ISNULL(UsedQuantity,0)  
              
 SET NOCOUNT OFF;              
END 




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_InsertUpdateVendorTyreDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
                    
CREATE PROCEDURE [dbo].[rvlf_sp_InsertUpdateVendorTyreDetails]                    
@Vendorid int=null,                   
@bigOrganizationId bigint = Null,                                  
@bigUserId bigint = Null ,                    
@VendorName varchar(50),                    
@Address varchar(200),                    
@ContactNo varchar(15),          
@MobileNo varchar(12),                      
@EmailId varchar(50),                                  
@EmailId1 varchar(50),              
@EmailId2 varchar(50),              
@State varchar(25),                    
@Zipcode varchar(25),                    
@City varchar(25),    
@VendorDesc Varchar(500)=null,
@VendorType char(3)=null    
AS                    
-- =============================================                    
-- Name   : rvlf_sp_InsertUpdateVendorTyreDetails                    
-- Author  : Kapil                    
-- Create date : 17-Feb-2014                    
-- Description : Insert & update Tyre Vendor Details                    
-- Company  : TRINETRA      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                    
-- =============================================                    
BEGIN                    
 -- SET NOCOUNT ON added to prevent extra result sets from                    
 -- interfering with SELECT statements.                    
 SET NOCOUNT ON;                    
       
 declare @ErrorMessage varchar(max)=null        
               
 if(@Vendorid is null)                
 begin              
  if Not exists (select * from rvlfTyreVendorMaster where VendorName = @VendorName and IsDelete=0 and OrganizationId = @bigOrganizationId  
   and VendorType=@VendorType)             
  begin               
   Insert into rvlfTyreVendorMaster (VendorName,VendorAddress,ContactNo,MobileNo,Email,Email1,Email2,VendorCity,VendorState,ZipCode,CreatedBy,CreatedDateTime,ModifiedBy,ModifiedDateTime,IsDelete,IsActive,OrganizationId,VendorDesc,VendorType)              
  
      
   values (@VendorName,@Address,@ContactNo,@MobileNo,@EmailId,@EmailId1,@EmailId2,@City,@State,@Zipcode,@bigUserId,GETUTCDATE(),null,null,0,1,@bigOrganizationId,@VendorDesc,@VendorType)                     
       
   select 1            
  end            
  else            
   select 0                
 end              
              
 else   --Update vendors             
 begin             
 if not exists (select * from rvlfTyreVendorMaster where VendorName = @VendorName and VendorId <> @Vendorid and IsDelete=0 and OrganizationId = @bigOrganizationId and VendorType=@VendorType)            
 begin               
  update rvlfTyreVendorMaster set VendorName=@VendorName,VendorAddress=@Address,      
  ContactNo= @ContactNo,Email=@EmailId,VendorCity=@City,VendorState = @State, ZipCode =@Zipcode,        
  MobileNo = @MobileNo, Email1=@EmailId1,Email2=@EmailId2,      
  ModifiedBy=@bigUserId,ModifiedDateTime=GETUTCDATE(),VendorDesc= @VendorDesc              
  where VendorId=@Vendorid and OrganizationId=@bigOrganizationId         
  select 1          
  end      
  else            
  select 0           
 end        
                      
 SET NOCOUNT OFF;                    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_InsertVendorDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
                  
CREATE PROCEDURE [dbo].[rvlf_sp_InsertVendorDetails]                  
@Vendorid int=null,                 
@bigOrganizationId bigint = Null,                                
@bigUserId bigint = Null ,                  
@VendorName varchar(25),                  
@WorkOrder varchar(50),                  
@ContractFrom datetime,                  
@ContractTo datetime,                  
@FxCostPerMonth decimal(8,2),                  
@FxKMPerMonth int,                  
@DutyHourType tinyint,                  
@FuelCostPerLit decimal(8,2),                  
@LiterPerKm int,                  
@ExCostPerKm decimal(8,2),                  
@ExCostPerHr decimal(8,2) ,                
@selectedate xml = null              
AS                  
-- =============================================                  
-- Name   : rvlf_sp_InsertVendorDetails                  
-- Author  : Gopal.R                  
-- Create date : 21-Oct-2013                  
-- Description : Insert & update Vendor Details                  
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
-- =============================================                  
BEGIN                  
 -- SET NOCOUNT ON added to prevent extra result sets from                  
 -- interfering with SELECT statements.                  
 SET NOCOUNT ON;                  
 declare @ErrorMessage varchar(max)=null              
 if(@Vendorid is null)              
 begin            
  if Not exists (select * from rvlfVendors where VendorName = @VendorName and IsDelete=0)           
  begin             
   Insert into rvlfVendors ( VendorName,WorkOrder,ContractFrom,ContractTo,FxCostPerMonth,FxKMPerMonth,DutyHourType,FuelCostPerLit,LiterPerKm,                  
   ExCostPerKm,ExCostPerHr,CreatedBy,CreateDate,ModifiedBy,ModifiedDate,IsDelete,OrganizationId )                  
   values ( @VendorName,@WorkOrder,@ContractFrom,@ContractTo,@FxCostPerMonth,@FxKMPerMonth,@DutyHourType,@FuelCostPerLit,@LiterPerKm,@ExCostPerKm,                  
   @ExCostPerHr,@bigUserId,GETDATE(),null,GETDATE(),0,@bigOrganizationId)                  
            declare @RecentVendorid int                  
            set @RecentVendorid=( select IDENT_CURRENT('rvlfVendors'))      
                            
   Insert into rvlfVendorMDays                 
   --select @RecentVendorid,*,'M' from rvlf_fn_ConvertArrayToTable(@selectedate,',')            
   SELECT @RecentVendorid,x.d.value('Dates[1]','date') AS Dates,'M' FROM @selectedate.nodes('/DocumentElement/Seleteddate') x(d)    
   select 1          
  end          
  else          
   select 0              
 end              
            
 else   --Update vendors           
 begin           
 if not exists (select * from rvlfVendors where VendorName = @VendorName and VendorId <> @Vendorid and IsDelete=0)          
 begin             
  update rvlfVendors set VendorName=@VendorName,WorkOrder=@WorkOrder,ContractFrom=@ContractFrom,ContractTo=@ContractTo,FxCostPerMonth=@FxCostPerMonth,              
  FxKMPerMonth=@FxKMPerMonth,DutyHourType=@DutyHourType,FuelCostPerLit=@FuelCostPerLit,LiterPerKm=@LiterPerKm,ExCostPerKm=@ExCostPerKm,ExCostPerHr=@ExCostPerHr,              
  ModifiedBy=@bigUserId,ModifiedDate=GETDATE()              
  where VendorId=@Vendorid and OrganizationId=@bigOrganizationId              
  if(@selectedate is not null and @selectedate.exist('/DocumentElement')=1)          
  begin              
   BEGIN TRAN DeleteMaintenanceDays                  
   BEGIN TRY                  
    delete from rvlfVendorMDays where VendorId=@Vendorid and datepart(MONTH,[Date]) in (SELECT DATEPART(MONTH,x.w.value('Dates[1]','dateTime')) AS Dates    
                      FROM @selectedate.nodes('/DocumentElement/Seleteddate') as x(w))                 
    Insert into rvlfVendorMDays     
      SELECT @Vendorid,x.d.value('Dates[1]','date') AS Dates,'M' FROM @selectedate.nodes('/DocumentElement/Seleteddate') x(d)              
    --select @Vendorid,*,'M' from rvlf_fn_ConvertArrayToTable(@selectedate,',')  where cast(FieldValue as datetime) > '1-1-1970'             
   COMMIT TRAN          
   END TRY                  
   BEGIN CATCH                  
    ROLLBACK TRAN               
    SET @ErrorMessage = 'An Error occured during assigning vehicles to the fleet : ' +ERROR_MESSAGE()                  
    RAISERROR( @ErrorMessage,16,1)                  
   END CATCH                
  end           
  select 1           
 end            
 else          
  select 0             
end                    
 SET NOCOUNT OFF;                  
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_SP_Instrument_Rpt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_SP_Instrument_Rpt]
	@intBoxId Varchar(1000) = NULL,
	@dtStartDate Datetime = NULL,
	@dtEndDate Datetime =NULL,
	@bigOrganizationID bigint = NULL,
	@bigQueryingUser bigint =NULL,
	@ParamId Varchar(500) =NULL,
	@bigFleetId Bigint =NULL,
	@vechileTypeId Tinyint =NULL
AS
--Declare
--	@intBoxId Varchar(1000) = NULL,
--	@dtStartDate Datetime = '7/11/2021 8:33:00 AM',
--	@dtEndDate Datetime ='7/12/2021 12:33:00 PM',
--	@bigOrganizationID bigint = NULL,
--	@bigQueryingUser bigint =453,
--	@ParamId Varchar(500) ='1,2,4,5,6,7',
--	@bigFleetId Bigint =NULL
--AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	declare @Lang varchar(50),  @LangSetting varchar(20)  
	declare @param varchar(100);  
	DECLARE @sqlX NVARCHAR(Max); 
	DECLARE @DisplayName nvarchar(30) 

	DECLARE @HoursToBeAdded INT = 0     
	DECLARE @MinsToBeAdded INT = 0                  
	--DECLARE @Distance varchar(20)                 
	                  
	DECLARE @DefaultDateFormat INT = 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)  ,
			@Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings,
			@DisplayName = U.UserName                
    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    
	inner join rvlfOrganization o on u.OrganizationId = o.OrganizationId  



	SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                  
	SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate)) 
	
	DECLARE @TabParam TABLE(id INT IDENTITY(1,1), Paramname VARCHAR(500))

    INSERT INTO @TabParam (Paramname)
    SELECT ParamName FROM rvlf_Rpt_ParamMst  WHERE ParamId IN(select FieldValue FROM rvlf_fn_ConvertArrayToTable(@ParamId,','))

   select
    @param = STUFF((SELECT ', ' + CAST(Paramname AS VARCHAR(50)) [text()]
         FROM @TabParam         
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') FROM @TabParam    
   IF(@vechileTypeId='1')
   BEGIN
    SELECT 
    cast(dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,T.OriginDateTime) as datetime) as     [Date],md.BoxId,md.EquipmentName As Devicename, md.SubTypeId,md.VehicleId,  
    ISNULL(T.Gen_Freq,'0')AS Gen_Freq,
	ISNULL(T.Gen_LNVolt,'0')AS Gen_LNVolt,
	ISNULL(T.Gen_LLVolt,'0')AS Gen_LLVolt ,
    ISNULL(T.Tot_Watts,'0')AS Tot_Watts,ISNULL(T.Tot_VA,'0')AS Tot_VA,ISNULL(T.Tot_VAr,'0')AS Tot_VAr,
	ISNULL(T.Gen_KWh,'0')AS Gen_KWh,ISNULL(T.Gen_KVArh,'0')AS Gen_KVArh,ISNULL(T.Gen_KVAh,'0')AS Gen_KVAh,
	ISNULL(T.Gen_L1_PF,'0') AS Gen_L1_PF,
    ISNULL(T.Gen_L1_VAr,'0') AS Gen_L1_VAr,
    ISNULL(T.Gen_L1_VA,'0') AS Gen_L1_VA,
    ISNULL(T.Gen_L1_Watts,'0') AS Gen_L1_Watts,
    ISNULL(T.Gen_L1_Current,'0') AS Gen_L1_Current,
    ISNULL(T.Gen_L2_PF,'0') AS Gen_L2_PF,
    ISNULL(T.Gen_L2_VAr,'0') AS Gen_L2_VAr,
    ISNULL(T.Gen_L2_VA,'0') AS Gen_L2_VA,
    ISNULL(T.Gen_L2_Watts,'0') AS Gen_L2_Watts,
    ISNULL(T.Gen_L2_Current,'0') AS Gen_L2_Current,
    ISNULL(T.Gen_L3_PF,'0') AS Gen_L3_PF,
    ISNULL(T.Gen_L3_VAr,'0') AS Gen_L3_VAr,
    ISNULL(T.Gen_L3_VA,'0') AS Gen_L3_VA,
    ISNULL(T.Gen_L3_Watts,'0') AS Gen_L3_Watts,
    ISNULL(T.Gen_L3_Current,'0') AS Gen_L3_Current,		
	ISNULL(T.Batt_Volt,'0') AS Batt_Volt,ISNULL(T.Chrg_Alternator,'0') AS Chrg_Alternator,ISNULL(T.Coolant_Temp,'0') AS Coolant_Temp,
	ISNULL(T.EngineSpeed,'0') AS EngineSpeed,ISNULL(T.Oil_Temp,'0') AS Oil_Temp,ISNULL(T.Oil_Pressure,'0') AS Oil_Pressure,
	ISNULL(T.FuelLevel,'0') AS FuelLevel, 	
	--CONVERT(time(0), DATEADD(SECOND, Engine_RunTime, 0)) AS Engine_RunTime,		
    ISNULL(GEN_L1_N_VOLT,'0') AS GEN_L1_N_VOLT, 
    ISNULL(GEN_L2_N_VOLT,'0') AS GEN_L2_N_VOLT, 
    ISNULL(GEN_L3_N_VOLT,'0') AS GEN_L3_N_VOLT, 
    ISNULL(GEN_L1_L2_VOLT,'0') AS GEN_L1_L2_VOLT, 
    ISNULL(GEN_L2_L3_VOLT,'0') AS GEN_L2_L3_VOLT, 
    ISNULL(GEN_L1_L3_VOLT,'0') AS GEN_L1_L3_VOLT, 
    ISNULL(GENCURRENT_L1,'0') AS GENCURRENT_L1, 
    ISNULL(GENCURRENT_L2,'0') AS GENCURRENT_L2, 
    ISNULL(GENCURRENT_L3,'0') AS GENCURRENT_L3, 
    ISNULL(BatteryCharger_OP_Cur,'0') AS BatteryCharger_OP_Cur,	
	isnull(Gen_Rating,'-') as Gen_Rating,
	ISNULL(Gen_AvgPF,'0') AS Gen_AvgPF,
	 Convert(varchar,@dtStartDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtStartDate as time),22) as PasStartDate,Convert(varchar,@dtEndDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEndDate as Time),22) as PasEndDate, 
  --PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()),
  @DisplayName + ' - ' + CONVERT(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ 
	' '+ CONVERT(VARCHAR,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) AS TIME),22) AS PasGeneratedDate  
  INTO #Temptbl_7410 FROM
    rvlfMAKDevices MD 
	INNER JOIN rvlfVehicle V on md.VehicleId=v.VehicleId    
	INNER JOIN rvlfFleetVehicles RFV ON MD.VehicleId = RFV.vehicleId
	INNER JOIN rvlfBoxID B ON B.BoxID = MD.BoxId   
	LEFT OUTER JOIN rvlfMsgInHst_Techno T ON T.BoxId = B.BoxId
	--LEFT OUTER JOIN rvlfMsgInHst_Techno_355 T3 ON T3.BoxId = B.BoxId
  WHERE
    (@bigFleetId IS NULL OR @bigFleetId='' OR RFV.FleetId=@bigFleetId)                   
    AND (@intBoxId IS NULL OR @intBoxId='' OR @intBoxId='0' OR T.BoxID in (select * from rvlf_fn_ConvertArrayToTable(@intBoxId,',')))  
	AND  T.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate and MD.SubTypeId=@vechileTypeId and T.BoxMsgInTypeId<>11
 ORDER BY OriginDateTime DESC   

 SET @sqlX = ' SELECT '+'Devicename,VehicleId,[Date],'+ @param + ',PasStartDate,PasEndDate,PasGeneratedDate FROM #Temptbl_7410 order by [Date] desc';

 EXEC sp_executesql @sqlX

 DROP TABLE #Temptbl_7410
 END
 ELSE
 BEGIN
  SELECT 
    cast(dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,T3.OriginDateTime) as datetime) as     [Date],md.BoxId,md.EquipmentName As Devicename, md.SubTypeId,md.VehicleId,  
	ISNULL(T3.S1_Tot_Watts,'0') AS S1_Tot_Watts,
    ISNULL(S1_Tot_VA,'0')AS S1_Tot_VA,
    ISNULL(S1_Tot_VAr,'0') AS S1_Tot_VAr,
    ISNULL(S1_KWh,'0') AS S1_KWh,
    ISNULL(S1_KVAh,'0') AS S1_KVAh,
    ISNULL(S1_KVArh,'0') AS S1_KVArh,
    ISNULL(S1_Freq,'0') AS S1_Freq,
	ISNULL(S1_LN_Volt,'0')AS S1_LN_Volt,
    ISNULL(S1_LL_Volt,'0') AS S1_LL_Volt,
    ISNULL(S1_AvgPF,'0') AS S1_AvgPF,
    ISNULL(S1_L1_PF,'0') AS S1_L1_PF,
    ISNULL(S1_L1_VAr,'0') AS S1_L1_VAr,
    ISNULL(S1_L1_VA,'0') AS S1_L1_VA,
    ISNULL(S1_L1_Watts,'0') AS S1_L1_Watts,
    ISNULL(S1_L1_Current,'0') AS S1_L1_Current,
    ISNULL(S1_L2_PF,'0') AS S1_L2_PF,
    ISNULL(S1_L2_VAr,'0') AS S1_L2_VAr,
    ISNULL(S1_L2_VA,'0') AS S1_L2_VA,
    ISNULL(S1_L2_Watts,'0') AS S1_L2_Watts,
    ISNULL(S1_L2_Current,'0') AS S1_L2_Current,
    ISNULL(S1_L3_PF,'0') AS S1_L3_PF,
    ISNULL(S1_L3_VAr,'0') AS S1_L3_VAr,
    ISNULL(S1_L3_VA,'0') AS S1_L3_VA,
    ISNULL(S1_L3_Watts,'0') AS S1_L3_Watts,
    ISNULL(S1_L3_Current,'0') AS S1_L3_Current,
    ISNULL(S2_Tot_Watts,'0') AS S2_Tot_Watts,
    ISNULL(S2_Tot_VA,'0') AS S2_Tot_VA,
    ISNULL(S2_Tot_VAr,'0') AS S2_Tot_VAr,
    ISNULL(S2_KWh,'0') AS S2_KWh,
    ISNULL(S2_KVAh,'0') AS S2_KVAh,
    ISNULL(S2_KVArh,'0') AS S2_KVArh,
    ISNULL(S2_Freq,'0') AS S2_Freq,	
    ISNULL(S2_LN_Volt,'0') As S2_LN_Volt,
    ISNULL(S2_LL_Volt,'0') AS S2_LL_Volt,
    ISNULL(S2_AvgPF,'0') AS S2_AvgPF,
    ISNULL(S2_L1_PF,'0') AS S2_L1_PF,
    ISNULL(S2_L1_VAr,'0') AS S2_L1_VAr,
    ISNULL(S2_L1_VA,'0') AS S2_L1_VA,
    ISNULL(S2_L1_Watts,'0') AS S2_L1_Watts,
    ---ISNULL(S2_L1_Current,'0') AS S2_L1_Current,
    ISNULL(S2_L2_PF,'0') AS S2_L2_PF,
    ISNULL(S2_L2_VAr,'0') AS S2_L2_VAr,
    ISNULL(S2_L2_VA,'0') AS S2_L2_VA,
    ISNULL(S2_L2_Watts,'0') AS S2_L2_Watts,
    --ISNULL(S2_L2_Current,'0') AS S2_L2_Current,
    ISNULL(S2_L3_PF,'0') AS S2_L3_PF,
    ISNULL(S2_L3_VAr,'0') AS S2_L3_VAr,
    ISNULL(S2_L3_VA,'0') AS S2_L3_VA,
    ISNULL(S2_L3_Watts,'0') AS S2_L3_Watts,
	CASE WHEN S2_L1_L2_Voltage IS NOT NULL OR S2_L1_L2_Voltage <> '0' THEN ISNULL(S1_L1_Current,'0') ELSE '0' END AS S2_L1_Current,
	CASE WHEN S2_L2_L3_Voltage IS NOT NULL OR S2_L2_L3_Voltage <> '0' THEN ISNULL(S1_L2_Current,'0') ELSE '0' END AS S2_L2_Current,
	CASE WHEN S2_L3_L1_Voltage IS NOT NULL OR S2_L3_L1_Voltage <> '0'THEN ISNULL(S1_L3_Current,'0') ELSE '0' END AS S2_L3_Current,
    --ISNULL(S2_L3_Current,'0') AS S2_L3_Current,
    ISNULL(Main_Gen_LNVolt,'0') AS Main_Gen_LNVolt,
	ISNULL(T3.Gen_LLVolt,'0') AS S1_S2LLVolt,
    ISNULL(S1_L1_N_Voltage,'0') AS S1_L1_N_Voltage,
    ISNULL(S1_L2_N_Voltage,'0') AS S1_L2_N_Voltage,
    ISNULL(S1_L3_N_Voltage,'0') AS S1_L3_N_Voltage,
    ISNULL(S1_L1_L2_Voltage,'0') AS S1_L1_L2_Voltage,
    ISNULL(S1_L2_L3_Voltage,'0') AS S1_L2_L3_Voltage,
    ISNULL(S1_L3_L1_Voltage,'0') AS S1_L3_L1_Voltage,
    ISNULL(S2_L1_N_Voltage,'0') AS S2_L1_N_Voltage,
    ISNULL(S2_L2_N_Voltage,'0') AS S2_L2_N_Voltage,
    ISNULL(S2_L3_N_Voltage,'0') AS S2_L3_N_Voltage,
    ISNULL(S2_L1_L2_Voltage,'0') AS S2_L1_L2_Voltage,
    ISNULL(S2_L2_L3_Voltage,'0') AS S2_L2_L3_Voltage,
    ISNULL(S2_L3_L1_Voltage,'0') AS S2_L3_L1_Voltage,
	 Convert(varchar,@dtStartDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtStartDate as time),22) as PasStartDate,Convert(varchar,@dtEndDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEndDate as Time),22) as PasEndDate, 
  --PasGenerateddate = dbo.rvlf_fn_DayLightSavings(@dtStartDate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()),
  @DisplayName + ' - ' + CONVERT(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ 
	' '+ CONVERT(VARCHAR,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) AS TIME),22) AS PasGeneratedDate  
  INTO #Temptbl_335 FROM
    rvlfMAKDevices MD 
	INNER JOIN rvlfVehicle V on md.VehicleId=v.VehicleId    
	INNER JOIN rvlfFleetVehicles RFV ON MD.VehicleId = RFV.vehicleId
	INNER JOIN rvlfBoxID B ON B.BoxID = MD.BoxId   
	--LEFT OUTER JOIN rvlfMsgInHst_Techno T ON T.BoxId = B.BoxId
	LEFT OUTER JOIN rvlfMsgInHst_Techno_355 T3 ON T3.BoxId = B.BoxId
  WHERE
    (@bigFleetId IS NULL OR @bigFleetId='' OR RFV.FleetId=@bigFleetId)                   
    AND (@intBoxId IS NULL OR @intBoxId='' OR @intBoxId='0' OR T3.BoxID in (select * from rvlf_fn_ConvertArrayToTable(@intBoxId,',')))  
	AND  T3.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate and MD.SubTypeId=@vechileTypeId and T3.BoxMsgInTypeId<>11
 ORDER BY B.LastStatusDateTime DESC

 SET @sqlX = ' SELECT '+'Devicename,VehicleId,[Date],'+ @param + ',PasStartDate,PasEndDate,PasGeneratedDate FROM #Temptbl_335 order by [Date] desc';

 EXEC sp_executesql @sqlX

 DROP TABLE #Temptbl_335
 END


 
   
 

-- 

 --

    
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_KPIDbd_GenerateSelectedKPIs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasu.e
-- Create date: 26-11-2015
-- Description:	Generates the Selected KPIs from the pre-defined Templates availalble
--				rvlf_sp_KPIDbd_GenerateSelectedKPIs '1988,2027',66,6
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_KPIDbd_GenerateSelectedKPIs]
	-- Add the parameters for the stored procedure here
	--@nvASSIGNMENTIDs	AS KPIAssignmentIDs READONLY,
	@nvASSIGNMENTIDs	Varchar(1000) = NULL,
	@bigUserID			bigint = NULL,
	@bigOrganizationId	bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
	SET NOCOUNT ON;
    
	-- Insert statements for procedure here	
	SELECT	GENERATEDKPI, REPLACE(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),
			RIGHT(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),2),'') AS KPISTATUS
	FROM(
		SELECT	--ASSIGNMENTID,KM.KPIID,KUA.DISPTYPEID,FLEETID,BOXID,REFRESHFREQUENCY,MINRANGE,MAXRANGE,DURATION,@bigUserID,@bigOrganizationId,
				CASE KUA.ISREVERSED 
				WHEN 0 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplate(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),TILETEMPLATE,TITLECLRCODE,ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KUA.TEMPERATURETYPE,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId)
				WHEN 1 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplateReversed(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),TILETEMPLATE,TITLECLRCODE,ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KUA.TEMPERATURETYPE,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId)
				END  AS GENERATEDKPI
		FROM	RVLFKPIUSERASSIGNMENT KUA
		INNER	JOIN RVLFKPIMASTER KM ON KUA.KPIID = KM.KPIID
		INNER	JOIN RVLFKPIDISPLAY KD ON KUA.DISPTYPEID = KD.DISPLAYID
		INNER	JOIN rvlfUser Usr ON KUA.USERID = Usr.UserId
		INNER   JOIN rvlfOrganization Org ON Usr.OrganizationId = Org.OrganizationId 
		INNER	JOIN rvlfScreenRefreshFrequency scref ON REFRESHFREQUENCY = scref.FrequencyId
		WHERE	KUA.USERID = @bigUserID AND Org.OrganizationId = @bigOrganizationId
		AND		ASSIGNMENTID IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@nvASSIGNMENTIDs,','))
													--(SELECT * FROM @nvASSIGNMENTIDs) 
	) KPITEMPLATE
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_KPIDbd_GenerateSelectedKPIs_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[rvlf_sp_KPIDbd_GenerateSelectedKPIs_PhoneGap]
	-- Add the parameters for the stored procedure here
	--@nvASSIGNMENTIDs	AS KPIAssignmentIDs READONLY,
	@nvASSIGNMENTIDs	Varchar(1000) = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22',
	@bigUserID			bigint = NULL,
	@bigOrganizationId	bigint = NULL
AS
-- =============================================
-- Author:		Ranjith.N
-- Create date: 11-Apr-2016
-- Description:	Generates the Selected KPIs from the pre-defined Templates availalble for Mobile
--				[rvlf_sp_KPIDbd_GenerateSelectedKPIs_PhoneGap] '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22',423,40
-- =============================================
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	--SELECT	ASSIGNMENTID,KM.KPIID,KUA.DISPTYPEID,FLEETID,BOXID,REFRESHFREQUENCY,MINRANGE,MAXRANGE,DURATION,
	--		dbo.rvlf_fn_KPIDbd_ChangeKPITemplate_PhoneGap(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),
	--		 replace(TILETEMPLATE,'li','div') ,'#457dc7',ASSIGNMENTID,KUA.CUSTOMTITLE,
	--		KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,REFRESHFREQUENCY,DURATION,@bigUserID,@bigOrganizationId) AS GENERATEDKPI
	--FROM	RVLFKPIUSERASSIGNMENT KUA
	--INNER	JOIN RVLFKPIMASTER KM ON KUA.KPIID = KM.KPIID
	--INNER	JOIN RVLFKPIDISPLAY KD ON KUA.DISPTYPEID = KD.DISPLAYID
	--INNER	JOIN rvlfUser Usr ON KUA.USERID = Usr.UserId
	--INNER   JOIN rvlfOrganization Org ON Usr.OrganizationId = Org.OrganizationId 
	--WHERE	KUA.USERID = @bigUserID AND Org.OrganizationId = @bigOrganizationId
	--AND		ASSIGNMENTID IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@nvASSIGNMENTIDs,','))	
	--												--(SELECT * FROM @nvASSIGNMENTIDs) 
	
    select @nvASSIGNMENTIDs= COALESCE(@nvASSIGNMENTIDs + ',','') + cast(assignmentid as varchar(25)) from rvlfKPIuserassignment where userid=@bigUserID   

    
	-- Insert statements for procedure here	
	SELECT	GENERATEDKPI, REPLACE(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),
			RIGHT(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),2),'') AS KPISTATUS,
			KPIID,DISPTYPEID,REFRESHFREQUENCY
	FROM(
		SELECT	--ASSIGNMENTID,KM.KPIID,KUA.DISPTYPEID,FLEETID,BOXID,REFRESHFREQUENCY,MINRANGE,MAXRANGE,DURATION,@bigUserID,@bigOrganizationId,
				CASE KUA.ISREVERSED 
				WHEN 0 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplate_PhoneGap(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),TILETEMPLATE_Mobile,'#457dc7',ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId)
				WHEN 1 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplateReversed_PhoneGap(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),TILETEMPLATE_Mobile,'#457dc7',ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId)
				END  AS GENERATEDKPI,KM.KPIID,KUA.DISPTYPEID,REFRESHFREQUENCY
		FROM	RVLFKPIUSERASSIGNMENT KUA
		INNER	JOIN RVLFKPIMASTER KM ON KUA.KPIID = KM.KPIID
		INNER	JOIN RVLFKPIDISPLAY KD ON KUA.DISPTYPEID = KD.DISPLAYID
		INNER	JOIN rvlfUser Usr ON KUA.USERID = Usr.UserId
		INNER   JOIN rvlfOrganization Org ON Usr.OrganizationId = Org.OrganizationId 
		INNER	JOIN rvlfScreenRefreshFrequency scref ON REFRESHFREQUENCY = scref.FrequencyId
		WHERE	KUA.USERID = @bigUserID AND Org.OrganizationId = @bigOrganizationId
		AND		ASSIGNMENTID IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@nvASSIGNMENTIDs,','))
													--(SELECT * FROM @nvASSIGNMENTIDs) 
	) KPITEMPLATE
END



--select * from RVLFKPIUSERASSIGNMENT

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_KPIDbd_GenerateSelectedKPIs_Responsive]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Anbarasu.e
-- Create date: 29-08-2016
-- Description:	Generates the Selected KPIs from the pre-defined Templates availalble
--				[rvlf_sp_KPIDbd_GenerateSelectedKPIs_Responsive] '23',219,6
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_KPIDbd_GenerateSelectedKPIs_Responsive]
	-- Add the parameters for the stored procedure here
	--@nvASSIGNMENTIDs	AS KPIAssignmentIDs READONLY,
	@nvASSIGNMENTIDs	Varchar(1000) = NULL,
	@bigUserID			bigint = NULL,
	@bigOrganizationId	bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
	SET NOCOUNT ON;
    
	-- Insert statements for procedure here	
	SELECT	GENERATEDKPI, REPLACE(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),
			RIGHT(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),2),'') AS KPISTATUS
	FROM(
		SELECT	--ASSIGNMENTID,KM.KPIID,KUA.DISPTYPEID,FLEETID,BOXID,REFRESHFREQUENCY,MINRANGE,MAXRANGE,DURATION,@bigUserID,@bigOrganizationId,
				CASE KUA.ISREVERSED 
				--WHEN 0 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplate_Responsive_Test(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),ResponsiveTemplate,TITLECLRCODE,ASSIGNMENTID,
				--			KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KUA.TemperatureType,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
				--			scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId)
				--WHEN 1 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplateReversed_Responsive(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),ResponsiveTemplate,TITLECLRCODE,ASSIGNMENTID,
				--			KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KUA.TemperatureType,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
				--			scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId)
				WHEN 0 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplate_Responsive_Test(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),ResponsiveTemplate,TITLECLRCODE,ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KUA.TemperatureType,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId,TemperatureType,KUA.CurrEnergytype)
				WHEN 1 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplateReversed_Responsive_Test(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),ResponsiveTemplate,TITLECLRCODE,ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KUA.TemperatureType,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId,TemperatureType)
				END  AS GENERATEDKPI
		FROM	RVLFKPIUSERASSIGNMENT KUA
		INNER	JOIN RVLFKPIMASTER KM ON KUA.KPIID = KM.KPIID
		INNER	JOIN RVLFKPIDISPLAY KD ON KUA.DISPTYPEID = KD.DISPLAYID
		INNER	JOIN rvlfUser Usr ON KUA.USERID = Usr.UserId
		INNER   JOIN rvlfOrganization Org ON Usr.OrganizationId = Org.OrganizationId 
		INNER	JOIN rvlfScreenRefreshFrequency scref ON REFRESHFREQUENCY = scref.FrequencyId
		WHERE	KUA.USERID = @bigUserID AND Org.OrganizationId = @bigOrganizationId
		AND		ASSIGNMENTID IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@nvASSIGNMENTIDs,','))
													--(SELECT * FROM @nvASSIGNMENTIDs) 
	) KPITEMPLATE
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_KPIDbd_GetKPIList]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasu.e
-- Create date: 18-11-2015
-- Description:	Get the List of KPIs related for the requesting User to be bound to the sidebar.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_KPIDbd_GetKPIList]
	-- Add the parameters for the stored procedure here
	@bigUserID			bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here	
	SELECT	ASSIGNMENTID, CASE WHEN LEN(CUSTOMTITLE) > 20 THEN SUBSTRING(CUSTOMTITLE, 0, 20) + '...' ELSE CUSTOMTITLE END AS CUSTOMTITLE,
			CUSTOMTITLE AS CUSTOMTITLETOOLTIP
	FROM	[dbo].[RVLFKPIUSERASSIGNMENT] KUA
	INNER	JOIN [dbo].[RVLFKPIMASTER] KM ON KUA.KPIID = KM.KPIID
	WHERE	ISDELETE = 0 and ISASSIGN = 1 and USERID = @bigUserID 

	--SELECT	COUNT(ASSIGNMENTID) AS TOTALKPI FROM	[TRINETRA_Pilot].[dbo].[RVLFKPIUSERASSIGNMENT] KUA
	--INNER	JOIN	[TRINETRA_Pilot].[dbo].[RVLFKPIMASTER] KM ON KUA.KPIID = KM.KPIID
	--WHERE	ISDELETE = 0 and USERID = @bigUserID 
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_KPIDbd_KPIExport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasu.e
-- Create date: 29-08-2016
-- Description:	Exports the Selected KPIs from the pre-defined Templates availalble
--				[rvlf_sp_KPIDbd_KPIExport] '9,10,11,12,13,14,15,186,23',219,6
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_KPIDbd_KPIExport]
	-- Add the parameters for the stored procedure here
	--@nvASSIGNMENTIDs	AS KPIAssignmentIDs READONLY,
	@nvASSIGNMENTIDs	Varchar(1000) = NULL,
	@bigUserID			bigint = NULL,
	@bigOrganizationId	bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
	SET NOCOUNT ON;
    
	-- Insert statements for procedure here
	DECLARE @HoursToBeAdded		int = 0
	DECLARE @MinsToBeAdded		int = 0
	DECLARE @DefaultDateFormat	int = 0

	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                                                      
			@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		(@bigUserID IS NULL OR @bigUserID='' OR up.UserId = @bigUserID)

	DECLARE @tblExportedKPIs TABLE(Sno int,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,IsReversed bit,bigUserId bigint,bigOrganizationID	bigint)

	INSERT INTO @tblExportedKPIs
	SELECT	ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),ASSIGNMENTID,KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,
			KUA.TemperatureType,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,scref.REFRESHFREQUENCYVALUE,DURATION,KUA.IsReversed,@bigUserID,@bigOrganizationId
	FROM	RVLFKPIUSERASSIGNMENT KUA
	INNER	JOIN RVLFKPIMASTER KM ON KUA.KPIID = KM.KPIID
	INNER	JOIN RVLFKPIDISPLAY KD ON KUA.DISPTYPEID = KD.DISPLAYID
	INNER	JOIN rvlfUser Usr ON KUA.USERID = Usr.UserId
	INNER   JOIN rvlfOrganization Org ON Usr.OrganizationId = Org.OrganizationId 
	INNER	JOIN rvlfScreenRefreshFrequency scref ON REFRESHFREQUENCY = scref.FrequencyId
	WHERE	KUA.USERID = @bigUserID AND Org.OrganizationId = @bigOrganizationId
	AND		ASSIGNMENTID IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@nvASSIGNMENTIDs,','))
		
	DECLARE
	@Sno				int,
	@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,
	@IsReversed			bit

	DECLARE	@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))

	DECLARE @intAssignmentId int = (SELECT MIN(AssignmentID) From @tblExportedKPIs)
	
	WHILE @intAssignmentId IS NOT NULL
	BEGIN
		SELECT	@Sno = Sno, @AssignmentID = ASSIGNMENTID, @CustomTitle = CustomTitle, @KPIID = KPIID, @KPIName = KPIName, @DisplayTypeID = DisplayTypeID, 
				@CostKPIsValue = CostKPIsValue, @TemperatureType = TemperatureType, @UnitName = UnitName, @MinRange = MinRange, @MaxRange = MaxRange,
				@FleetId = FLEETID, @BoxId = BOXID, @RefFreq = RefFreq, @Duration = DURATION, @IsReversed = IsReversed
		FROM	@tblExportedKPIs 
		WHERE	AssignmentID = @intAssignmentId
		SELECT @intAssignmentId = (SELECT MIN(AssignmentID) FROM @tblExportedKPIs WHERE AssignmentID > @intAssignmentId)
		
		IF @IsReversed = 0
		BEGIN
			INSERT INTO @KPIExport
			SELECT * FROM [dbo].[rvlf_fn_KPIDbd_ExportKPIs] (@Sno, @AssignmentID, @CustomTitle, @KPIID, @KPIName, @DisplayTypeID, 
															@CostKPIsValue, @TemperatureType, @UnitName, @MinRange, @MaxRange, 
															@FleetId, @BoxId, @RefFreq, @Duration, @bigUserID, @bigOrganizationId)
		END
		ELSE
		BEGIN
			INSERT INTO @KPIExport
			SELECT * FROM [dbo].[rvlf_fn_KPIDbd_ExportKPIs_Reversed] (@Sno, @AssignmentID, @CustomTitle, @KPIID, @KPIName, @DisplayTypeID, 
															@CostKPIsValue, @TemperatureType, @UnitName, @MinRange, @MaxRange, 
															@FleetId, @BoxId, @RefFreq, @Duration, @bigUserID, @bigOrganizationId)
		END
	END

	Select *, Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat) + ' ' + 
			  Convert(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate
	From @KPIExport	
	
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_KPIDbd_KPIExport_Test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasu.e
-- Create date: 29-08-2016
-- Description:	Exports the Selected KPIs from the pre-defined Templates availalble
--				[rvlf_sp_KPIDbd_KPIExport] '9,10,11,12,13,14,15,186,23',219,6
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_KPIDbd_KPIExport_Test]
	-- Add the parameters for the stored procedure here
	--@nvASSIGNMENTIDs	AS KPIAssignmentIDs READONLY,
	@nvASSIGNMENTIDs	Varchar(1000) = NULL,
	@bigUserID			bigint = NULL,
	@bigOrganizationId	bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
	SET NOCOUNT ON;
    
	-- Insert statements for procedure here
	DECLARE @HoursToBeAdded		int = 0
	DECLARE @MinsToBeAdded		int = 0
	DECLARE @DefaultDateFormat	int = 0

	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                                                      
			@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		(@bigUserID IS NULL OR @bigUserID='' OR up.UserId = @bigUserID)

	DECLARE @tblExportedKPIs TABLE(Sno int,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,IsReversed bit,bigUserId bigint,bigOrganizationID	bigint, Curenergytype Int)

	INSERT INTO @tblExportedKPIs
	SELECT	ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),ASSIGNMENTID,KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,
			KUA.TemperatureType,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,scref.REFRESHFREQUENCYVALUE,DURATION,KUA.IsReversed,@bigUserID,@bigOrganizationId,CurrEnergytype
	FROM	RVLFKPIUSERASSIGNMENT KUA
	INNER	JOIN RVLFKPIMASTER KM ON KUA.KPIID = KM.KPIID
	INNER	JOIN RVLFKPIDISPLAY KD ON KUA.DISPTYPEID = KD.DISPLAYID
	INNER	JOIN rvlfUser Usr ON KUA.USERID = Usr.UserId
	INNER   JOIN rvlfOrganization Org ON Usr.OrganizationId = Org.OrganizationId 
	INNER	JOIN rvlfScreenRefreshFrequency scref ON REFRESHFREQUENCY = scref.FrequencyId
	WHERE	KUA.USERID = @bigUserID AND Org.OrganizationId = @bigOrganizationId
	AND		ASSIGNMENTID IN (SELECT ASSIGNMENTIDS FROM [dbo].[rvlf_fn_KPIDbd_SplitforKPI] (@nvASSIGNMENTIDs,','))
		
	DECLARE
	@Sno				int,
	@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,
	@IsReversed			bit,
	@Curenergytype int

	DECLARE	@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 varchar(1000), 
								VehicleDescription nvarchar(75), LicensePlate varchar(50), Vin varchar(50), Value nvarchar(50), Status nvarchar(10))

	DECLARE @intAssignmentId int = (SELECT MIN(AssignmentID) From @tblExportedKPIs)
	
	WHILE @intAssignmentId IS NOT NULL
	BEGIN
		SELECT	@Sno = Sno, @AssignmentID = ASSIGNMENTID, @CustomTitle = CustomTitle, @KPIID = KPIID, @KPIName = KPIName, @DisplayTypeID = DisplayTypeID, 
				@CostKPIsValue = CostKPIsValue, @TemperatureType = TemperatureType, @UnitName = UnitName, @MinRange = MinRange, @MaxRange = MaxRange,
				@FleetId = FLEETID, @BoxId = BOXID, @RefFreq = RefFreq, @Duration = DURATION, @IsReversed = IsReversed,@Curenergytype = Curenergytype
		FROM	@tblExportedKPIs 
		WHERE	AssignmentID = @intAssignmentId
		SELECT @intAssignmentId = (SELECT MIN(AssignmentID) FROM @tblExportedKPIs WHERE AssignmentID > @intAssignmentId)
		
		IF @IsReversed = 0
		BEGIN
			INSERT INTO @KPIExport
			SELECT * FROM [dbo].[rvlf_fn_KPIDbd_ExportKPIs_Test] (@Sno, @AssignmentID, @CustomTitle, @KPIID, @KPIName, @DisplayTypeID, 
															@CostKPIsValue, @TemperatureType, @UnitName, @MinRange, @MaxRange, 
															@FleetId, @BoxId, @RefFreq, @Duration, @bigUserID, @bigOrganizationId,@TemperatureType,@Curenergytype)
		END
		ELSE
		BEGIN
			INSERT INTO @KPIExport
			SELECT * FROM [dbo].[rvlf_fn_KPIDbd_ExportKPIs_Reversed] (@Sno, @AssignmentID, @CustomTitle, @KPIID, @KPIName, @DisplayTypeID, 
															@CostKPIsValue, @TemperatureType, @UnitName, @MinRange, @MaxRange, 
															@FleetId, @BoxId, @RefFreq, @Duration, @bigUserID, @bigOrganizationId)
		END
	END

	Select *, Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat) + ' ' + 
			  Convert(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate
	From @KPIExport	
	
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_KPIDbd_LoadDefaultKPIs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasu.e
-- Create date: 26-11-2015
-- Description:	Generates the Selected KPIs from the pre-defined Templates availalble
--				rvlf_sp_KPIDbd_LoadDefaultKPIs 66,6
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_KPIDbd_LoadDefaultKPIs]
	-- Add the parameters for the stored procedure here
	--@nvASSIGNMENTIDs	AS KPIAssignmentIDs READONLY,
	@bigUserID			bigint = NULL,
	@bigOrganizationId	bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
	SET NOCOUNT ON;
    
	-- Insert statements for procedure here
	SELECT	ASSIGNMENTID, CASE WHEN LEN(CUSTOMTITLE) > 20 THEN SUBSTRING(CUSTOMTITLE, 0, 20) + '...' ELSE CUSTOMTITLE END AS CUSTOMTITLE, GENERATEDKPI, 
			REPLACE(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),
			RIGHT(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),2),'') AS KPISTATUS
	FROM(
		SELECT	ASSIGNMENTID,CUSTOMTITLE,--KM.KPIID,KUA.DISPTYPEID,FLEETID,BOXID,REFRESHFREQUENCY,MINRANGE,MAXRANGE,DURATION,
				CASE KUA.ISREVERSED 
				WHEN 0 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplate(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),TILETEMPLATE,TITLECLRCODE,ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KUA.TEMPERATURETYPE,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId)
				WHEN 1 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplateReversed(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),TILETEMPLATE,TITLECLRCODE,ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KUA.TEMPERATURETYPE,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId)
				END  AS GENERATEDKPI
		FROM	RVLFKPIUSERASSIGNMENT KUA
		INNER	JOIN RVLFKPIMASTER KM ON KUA.KPIID = KM.KPIID
		INNER	JOIN RVLFKPIDISPLAY KD ON KUA.DISPTYPEID = KD.DISPLAYID
		INNER	JOIN rvlfUser Usr ON KUA.USERID = Usr.UserId
		INNER   JOIN rvlfOrganization Org ON Usr.OrganizationId = Org.OrganizationId 
		INNER	JOIN rvlfScreenRefreshFrequency scref ON REFRESHFREQUENCY = scref.FrequencyId
		WHERE	KUA.ISDELETE = 0	AND		KUA.ISASSIGN = 1
		AND		KUA.USERID = @bigUserID AND Org.OrganizationId = @bigOrganizationId
		AND		KM.KPIID	Between 1 AND 10 
	)	KPITEMPLATE
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_KPIDbd_LoadDefaultKPIs_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasu.e
-- Create date: 26-11-2015
-- Description:	Generates the Selected KPIs from the pre-defined Templates availalble
--				rvlf_sp_KPIDbd_LoadDefaultKPIs_PhoneGap 66,6
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_KPIDbd_LoadDefaultKPIs_PhoneGap]
	-- Add the parameters for the stored procedure here
	--@nvASSIGNMENTIDs	AS KPIAssignmentIDs READONLY,
	@bigUserID			bigint = NULL,
	@bigOrganizationId	bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
	SET NOCOUNT ON;
    
	-- Insert statements for procedure here
	SELECT	ASSIGNMENTID, CASE WHEN LEN(CUSTOMTITLE) > 20 THEN SUBSTRING(CUSTOMTITLE, 0, 20) + '...' ELSE CUSTOMTITLE END AS CUSTOMTITLE, reverse(right(reverse(Replace(GENERATEDKPI,'''', '"')), 
	len(Replace(GENERATEDKPI,'''', '"')) - charindex('>',reverse(Replace(GENERATEDKPI,'''', '"')),1) + 1)) as GENERATEDKPI, 
			REPLACE(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),
			RIGHT(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),2),'') AS KPISTATUS,
			KPIID,DISPTYPEID,REFRESHFREQUENCY,ChartDivID,
			(Case when DISPTYPEID = 4 then ISNULL([dbo].[rvlf_fn_GetParamValueWithIndex](Replace(GENERATEDKPI,'''', '"'),'Safe#',';') ,0) else 0 end) as SafeValue,
			(Case when DISPTYPEID = 4 then ISNULL([dbo].[rvlf_fn_GetParamValueWithIndex](Replace(GENERATEDKPI,'''', '"'),'Warning#',';') ,0)else 0 end) as WarningValue,
			(Case when DISPTYPEID = 4 then ISNULL([dbo].[rvlf_fn_GetParamValueWithIndex](Replace(GENERATEDKPI,'''', '"'),'Critical#',';') ,0)else 0 end) as CriticalValue
	FROM(
		SELECT	ASSIGNMENTID,CUSTOMTITLE,--KM.KPIID,KUA.DISPTYPEID,FLEETID,BOXID,REFRESHFREQUENCY,MINRANGE,MAXRANGE,DURATION,
				CASE KUA.ISREVERSED 
				WHEN 0 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplate_PhoneGap(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),TILETEMPLATE_Mobile,'#457dc7',ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId)
				WHEN 1 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplateReversed_PhoneGap(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),TILETEMPLATE_Mobile,'#457dc7',ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId)
				END  AS GENERATEDKPI,KM.KPIID,KUA.DISPTYPEID,REFRESHFREQUENCY,
				(Case when DISPTYPEID = 4 then 'chart_div' + cast (ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID) as varchar(10)) else '-' end) as ChartDivID			
		FROM	RVLFKPIUSERASSIGNMENT KUA
		INNER	JOIN RVLFKPIMASTER KM ON KUA.KPIID = KM.KPIID
		INNER	JOIN RVLFKPIDISPLAY KD ON KUA.DISPTYPEID = KD.DISPLAYID
		INNER	JOIN rvlfUser Usr ON KUA.USERID = Usr.UserId
		INNER   JOIN rvlfOrganization Org ON Usr.OrganizationId = Org.OrganizationId 
		INNER	JOIN rvlfScreenRefreshFrequency scref ON REFRESHFREQUENCY = scref.FrequencyId
		WHERE	KUA.ISDELETE = 0	AND		KUA.ISASSIGN = 1
		AND		KUA.USERID = @bigUserID AND Org.OrganizationId = @bigOrganizationId
		AND		KM.KPIID	Between 1 AND 10 
	)	KPITEMPLATE
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_KPIDbd_LoadDefaultKPIs_Responsive]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Anbarasu.e
-- Create date: 29-08-2016
-- Description:	Generates the Selected KPIs from the pre-defined Templates availalble
--				[rvlf_sp_KPIDbd_LoadDefaultKPIs_Responsive] 219,6
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_KPIDbd_LoadDefaultKPIs_Responsive]
	-- Add the parameters for the stored procedure here
	--@nvASSIGNMENTIDs	AS KPIAssignmentIDs READONLY,
	@bigUserID			bigint = NULL,
	@bigOrganizationId	bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
	SET NOCOUNT ON;
    
	-- Insert statements for procedure here
	--Declare @x int = 0, @y int = 0
	SELECT	ASSIGNMENTID, CASE WHEN LEN(CUSTOMTITLE) > 20 THEN SUBSTRING(CUSTOMTITLE, 0, 20) + '...' ELSE CUSTOMTITLE END AS CUSTOMTITLE, GENERATEDKPI, 
			REPLACE(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),
			RIGHT(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),2),'') AS KPISTATUS
	FROM(
		SELECT	ASSIGNMENTID,CUSTOMTITLE,--KM.KPIID,KUA.DISPTYPEID,FLEETID,BOXID,REFRESHFREQUENCY,MINRANGE,MAXRANGE,DURATION,
				CASE KUA.ISREVERSED 
				WHEN 0 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplate_Responsive(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),ResponsiveTemplate,TITLECLRCODE,ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KUA.TemperatureType,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId)
				WHEN 1 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplateReversed_Responsive(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),ResponsiveTemplate,TITLECLRCODE,ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KUA.TemperatureType,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId)
				END  AS GENERATEDKPI
		FROM	RVLFKPIUSERASSIGNMENT KUA
		INNER	JOIN RVLFKPIMASTER KM ON KUA.KPIID = KM.KPIID
		INNER	JOIN RVLFKPIDISPLAY KD ON KUA.DISPTYPEID = KD.DISPLAYID
		INNER	JOIN rvlfUser Usr ON KUA.USERID = Usr.UserId
		INNER   JOIN rvlfOrganization Org ON Usr.OrganizationId = Org.OrganizationId 
		INNER	JOIN rvlfScreenRefreshFrequency scref ON REFRESHFREQUENCY = scref.FrequencyId
		WHERE	KUA.ISDELETE = 0	AND		KUA.ISASSIGN = 1
		AND		KUA.USERID = @bigUserID AND Org.OrganizationId = @bigOrganizationId
		AND		KM.KPIID	Between 1 AND 10 
	)	KPITEMPLATE
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_KPIDbd_LoadDefaultKPIs_Responsive_Test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.e
-- Create date: 29-08-2016
-- Description:	Generates the Selected KPIs from the pre-defined Templates availalble
--				[rvlf_sp_KPIDbd_LoadDefaultKPIs_Responsive] 458,86
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_KPIDbd_LoadDefaultKPIs_Responsive_Test]
	-- Add the parameters for the stored procedure here
	--@nvASSIGNMENTIDs	AS KPIAssignmentIDs READONLY,
	@bigUserID			bigint = NULL,
	@bigOrganizationId	bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
	SET NOCOUNT ON;
    
	-- Insert statements for procedure here
	--Declare @x int = 0, @y int = 0
	SELECT	ASSIGNMENTID, CASE WHEN LEN(CUSTOMTITLE) > 20 THEN SUBSTRING(CUSTOMTITLE, 0, 20) + '...' ELSE CUSTOMTITLE END AS CUSTOMTITLE, GENERATEDKPI, 
			REPLACE(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),
			RIGHT(SUBSTRING(GENERATEDKPI,CHARINDEX('KPIStatus:',GENERATEDKPI,1)+len('KPIStatus:'),CHARINDEX('KPIStatus',GENERATEDKPI,1)+len('KPIStatus:')),2),'') AS KPISTATUS
	FROM(
		SELECT	ASSIGNMENTID,CUSTOMTITLE,--KM.KPIID,KUA.DISPTYPEID,FLEETID,BOXID,REFRESHFREQUENCY,MINRANGE,MAXRANGE,DURATION,
				CASE KUA.ISREVERSED 
				WHEN 0 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplate_Responsive_Test(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),ResponsiveTemplate,TITLECLRCODE,ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KUA.TemperatureType,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId,TemperatureType,CurrEnergytype)
				WHEN 1 THEN dbo.rvlf_fn_KPIDbd_ChangeKPITemplateReversed_Responsive_Test(ROW_NUMBER() OVER (ORDER BY ASSIGNMENTID),ResponsiveTemplate,TITLECLRCODE,ASSIGNMENTID,
							KUA.CUSTOMTITLE,KM.KPIID,KM.KPINAME,KUA.DISPTYPEID,KUA.COSTKPISVALUE,KUA.TemperatureType,KM.UNITNAME,MINRANGE,MAXRANGE,FLEETID,BOXID,
							scref.REFRESHFREQUENCYVALUE,DURATION,@bigUserID,@bigOrganizationId,TemperatureType)
				END  AS GENERATEDKPI
		FROM	RVLFKPIUSERASSIGNMENT KUA
		INNER	JOIN RVLFKPIMASTER KM ON KUA.KPIID = KM.KPIID
		INNER	JOIN RVLFKPIDISPLAY KD ON KUA.DISPTYPEID = KD.DISPLAYID
		INNER	JOIN rvlfUser Usr ON KUA.USERID = Usr.UserId
		INNER   JOIN rvlfOrganization Org ON Usr.OrganizationId = Org.OrganizationId 
		INNER	JOIN rvlfScreenRefreshFrequency scref ON REFRESHFREQUENCY = scref.FrequencyId
		WHERE	KUA.ISDELETE = 0	AND		KUA.ISASSIGN = 1
		AND		KUA.USERID = @bigUserID AND Org.OrganizationId = @bigOrganizationId
		--AND		KM.KPIID	Between 1 AND 10 
	)	KPITEMPLATE
END





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_KPIDbdSaveKPIPosition]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasu.E
-- Create date: 26-Oct-2016
-- Description:	Saves the Positions of KPI tiles for the current user.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_KPIDbdSaveKPIPosition] 
	-- Add the parameters for the stored procedure here
	@tblKPIPositionXML xml = Null, 
	@bigUserId bigint = 0
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DECLARE	@docHandle int       
	DECLARE  @temptable TABLE (AssignmentId bigint,x tinyint,y tinyint, width tinyint, height tinyint)
        
	IF @tblKPIPositionXML IS NOT NULL     
	BEGIN                        
		   
	EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblKPIPositionXML
		       
	INSERT INTO @tempTable    
	SELECT * FROM OPENXML(@docHandle, '/DocumentElement/rvlfKPIGridPosition')   
	WITH     
	( 
		AssignmentId	bigint		'AssignmentId',
		x				tinyint		'x',
		y				tinyint		'y',
		width			tinyint		'width',
		height			tinyint		'height'
	)          
	END
	
	DELETE FROM rvlfKPIGridPosition WHERE AssignmentId in (SELECT AssignmentId From @temptable)

	INSERT INTO rvlfKPIGridPosition
	SELECT * FROM @temptable
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_LoadFeedbackforUsers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.e
-- Create date: 18-05-2015
-- Description:	Loads User Feedback for User View.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_LoadFeedbackforUsers]
	-- Add the parameters for the stored procedure here
	@bigUserId				bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT	'Posted: ' + convert(varchar,ufb.FeedbackDate,106) as FeedbackDate, ufb.FeedbackText, 
			Case ufb.Status 
			When 0 then 'Not viewed'
			When 1 then 'Replied'
			End as Status,
			'Replied: ' + convert(varchar,ufb.ReplyDate,106) as ReplyDate, ufb.ReplyText
	FROM	rvlfUserFeedback ufb	
	WHERE	ufb.UserId = @bigUserId
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_LoadFeedbackText]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.e
-- Create date: 15-05-2015
-- Description:	Loads User Feedback text for Reply panel.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_LoadFeedbackText]
	-- Add the parameters for the stored procedure here
	@bigUserFeedbackId				bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT	ufb.FeedbackText, ufb.Status
	FROM	rvlfUserFeedback ufb
	WHERE	ufb.UserFeedbackId = @bigUserFeedbackId
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_LoadFirmwareType]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvlf_sp_LoadFirmwareType]
/******************************************************************************/
--	Name		:	rvlf_sp_LoadFirmwareType
--	Description	:	To get the Firmware Types
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	21-Apr-2010	MJJC	Created Intial Version 
/******************************************************************************/
AS
BEGIN
 SELECT * FROM rvlfFirmwareType
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_LoadLeaseSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.e
-- Create date: 26-02-2016
-- Description:	rvlf_sp_LoadLeaseSettings 14,219,6
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_LoadLeaseSettings]
	-- Add the parameters for the stored procedure here
	 @bigVendorVehicleSettingsId		bigint = 0, 	 
	 @bigUserId							bigint = NULL,
	 @bigOrganizationId					bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here

	--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

	Select	VendorVehicleSettingsId,VendorVehicleAssignId,CONVERT(nvarchar,ContractFrom,106) ContractFrom,
			CONVERT(nvarchar,ContractTo,106) ContractTo,ExpNotificationType,ExpNotification1,ExpNotification2,
			MonthlyRunningDistance,IsDistanceNotify,MonthlyEngineHrs,IsEngineHrsNotify,IsRenew,Remarks
	From	rvlfVendorVehicleSettings Where VendorVehicleSettingsId = @bigVendorVehicleSettingsId
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_LoadTrendParamByVehicleId]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_LoadTrendParamByVehicleId]
@bigVehicleId bigint = NULL,
@bigOrganizationID bigint = NULL,
@bigUserID bigint = NULL,
@IsDeviceBased TINYINT = NULL
AS 
-- =============================================
-- Author:		Asanraj N
-- Create date: 18-06-2019
-- Description:	Get Trend Parameters details for vehicle Type Based.
-- Proce Name	rvlf_sp_LoadTrendParamByVehicleId	984,132
-- =============================================
BEGIN
 DECLARE @VehType INT = 0
 DECLARE @DeviceId Varchar(10)

 SELECT @VehType = Md.SubTypeId, @DeviceId=Md.BoxId from rvlfVehicle V INNER JOIN rvlfVehicleAssignment va ON v.vehicleid = va.VehicleId
 INNER JOIN rvlfMAKDevices Md ON Md.BoxId = va.BoxId  WHERE V.VehicleId = @bigVehicleId AND
  Md.OrganizationId = @bigOrganizationID AND Md.IsDelete =0

IF(@IsDeviceBased='1')
 BEGIN
  SELECT ParamId, ParamName FROM rvlfTrendParamMst WHERE (@VehType =1 AND ParamId IN (1,2,3,5,6,12,13,16,17,19,21,22,23,24,25,26)) 
     OR (@VehType =2 AND ParamId IN(1,2,3,4,5,6,7,12,13,16,17,18,19,21,22,23,24,25,26,27,28,29))
     OR (@VehType =3 AND ParamId IN(1,2,3,5,6,12,13,14,15,16,17,19,21,22,23,24,25,26))
     OR (@VehType =4 AND ParamId IN(1,2,3,4,5,6,7,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29))
  Union 
  select * from rvlf_fn_Compactordetails(@bigVehicleId)
 END
ELSE 
  select ParamId, ParamName from rvlfTrendParamMst where ParamId IN(1,2,3,5,6,12,13,16,17,19,21,22,23,24,25,26)
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_LogNotificaitons]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_LogNotificaitons]            
 @uimessageInID as uniqueIdentifier,            
 @tiBoxMsgInTypeId tinyint = null            
AS            
/****************************************************************************************************/            
-- Name  : rvlf_sp_LogNotificaitons            
-- Description : To get log the notificaitons.            
-- Author  : M. Jebamalai Jaya Chitra            
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--   : 17-Nov-2009 MJJC Created initial version            
--   : 25-Jan-2010 MJJC To update the alarm details function parameters            
--   : 19-Jun-2010 MJJC Included a check for the duration when             
--   : 30-Jun-2010 Kumu Changed the logging of Sensor Name            
--   : 19-Aug-2010 Kumu Removed the Vehicle Display Name            
--          : 13-Dec-2010 Kumu Blocked the SMS for Org. US Embassy            
--          : 20-Dec-2010 Kumu Unblocked the SMS for Org. US Embassy and             
--            checked SMS Count for the current date for each Box Id            
--   : 30-Dec-2010 VN Restrict the users if the user is deleted.            
--   : 07-Apr-2011 LK Removed the Street Address checking for Geozone level notification          
--   : VN --DISABLE THE SMS RIGHTS FOR EXPIRED ORG AND PACKAGE OPERATION.            
--   : 13-Oct-2011 Restrict the SMS, based on Mas SMS Limit by BoxId - Sakthi          
--   : 30-Jan-2012 Notify by Email for deleted geozones - Sakthi          
--   : 13-Mar-2012 Restrict the SMS by Box and organization wise - Sakthi          
/***************************************************************************************************/            
          
BEGIN            
 BEGIN TRY            
 --DISABLE THE SMS RIGHTS FOR EXPIRED ORG AND PACKAGE OPERATION.          
 IF EXISTS(SELECT UserID  FROM rvlfNotificationList WHERE SMS=1 AND          
 UserID NOT IN (SELECT distinct NL.UserID FROM rvlfNotificationList NL          
 INNER JOIN RVLFUSER U ON U.USERID=NL.UserID           
 INNER JOIN rvlfOrganizationPackage OP ON OP.OrganizationID=U.OrganizationId AND OP.IsActive=1          
 INNER JOIN rvlfPackageOperations PO ON PO.PackageId=OP.PackageId AND PO.OperationID IN(136)          
 WHERE NL.SMS=1 AND OP.ExpiresOn > GETUTCDATE()))          
 BEGIN          
  UPDATE rvlfNotificationList SET SMS=NULL WHERE SMS=1 AND          
   UserID NOT IN (SELECT DISTINCT NL.UserID FROM rvlfNotificationList NL          
   INNER JOIN RVLFUSER U ON U.USERID=NL.UserID           
   INNER JOIN rvlfOrganizationPackage OP ON OP.OrganizationID=U.OrganizationId AND OP.IsActive=1          
   INNER JOIN rvlfPackageOperations PO ON PO.PackageId=OP.PackageId AND PO.OperationID IN(136)          
   WHERE NL.SMS=1 AND OP.ExpiresOn > GETUTCDATE())          
 END          
             
    DECLARE @bigOrgId AS BIGINT = 0            
    DECLARE @inBoxId AS INT = 0            
    DECLARE @intSMSCount AS INT = 0            
    DECLARE @tiMaxSMSLimit AS SMALLINT = NULL            
    DECLARE @IsSMSsent bit=1            
    DECLARE @intNoOfBoxes AS INT = 0              
    DECLARE @intBoxSMSCount AS INT = 0            
    DECLARE @bitSMSReached AS bit = 0          
    DECLARE @SMSMessage VARCHAR(100) = NULL             
    DECLARE @cVehicleDesc VARCHAR(45) = NULL          
              
    SELECT @bigOrgId = v.OrganizationId,@cVehicleDesc=v.VehicleDescription,@inBoxId = h.BoxId, @tiMaxSMSLimit = ISNULL(o.MaxSMSLimit,0) FROM rvlfMsgInHst h             
    INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId            
    INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId            
    INNER JOIN rvlfOrganization o ON o.OrganizationId = v.OrganizationId          
    WHERE h.MessageInID = @uimessageInID            
              
     --No of boxes          
    SELECT @intNoOfBoxes=COUNT(*) FROM dbo.rvlfBoxId WHERE OrganizationId=@bigOrgId           
          
 --Get the total sms count          
    SELECT @intSMSCount = COUNT(MessageInID) FROM rvlfNotificationLog WHERE OrganizationID = @bigOrgId AND CanSendSMS = 1             
    AND SMSProcessedDate IS NOT NULL AND DATEPART(MONTH, OriginDateTime) = DATEPART(MONTH, GETUTCDATE())            
 AND  DATEPART(YEAR,OriginDateTime) = DATEPART(YEAR, GETUTCDATE())            
 AND IsSMSSent = 1           
          
 --Get the box sms count          
   SELECT @intBoxSMSCount = COUNT(MessageInID) FROM rvlfNotificationLog WHERE OrganizationID = @bigOrgId           
 AND BoxId=@inBoxId AND CanSendSMS = 1 AND SMSProcessedDate IS NOT NULL AND           
 DATEPART(MONTH, OriginDateTime) = DATEPART(MONTH, GETUTCDATE()) AND            
 DATEPART(YEAR,OriginDateTime) = DATEPART(YEAR, GETUTCDATE()) AND IsSMSSent  = 1          
              
 IF (@intBoxSMSCount > @tiMaxSMSLimit)           
 BEGIN          
  IF (@intBoxSMSCount = (@tiMaxSMSLimit+1))          
  BEGIN          
   SET @bitSMSReached=1          
   SET @SMSMessage = 'SMS Limit has been reached for '''+@cVehicleDesc+'''. Please contact administrator for activation'          
  END          
 END          
 IF (@intSMSCount = ((@tiMaxSMSLimit*@intNoOfBoxes)-25))            
 BEGIN          
  SET @bitSMSReached=1          
  SET @SMSMessage = 'SMS Limit to be reached.'          
 END          
 ELSE IF (@intSMSCount > (@tiMaxSMSLimit*@intNoOfBoxes))            
 BEGIN          
  SET @IsSMSsent=0            
  IF (@intSMSCount = ((@tiMaxSMSLimit*@intNoOfBoxes)+1)) AND @bitSMSReached =0          
  BEGIN          
   SET @bitSMSReached=1          
   SET @SMSMessage = 'SMS Limit has been reached. Please contact administrator for activation'          
  END          
 END          
       
 --Check the same message "SMS Limit"      
 DECLARE @checkMsgTempCount int = 0      
 SELECT @checkMsgTempCount = COUNT(MessageInID) FROM rvlfNotificationLog WHERE OrganizationID = @bigOrgId           
 AND BoxId=@inBoxId AND MessageDetails=@SMSMessage AND          
 DATEPART(MONTH, OriginDateTime) = DATEPART(MONTH, GETUTCDATE()) AND            
 DATEPART(YEAR,OriginDateTime) = DATEPART(YEAR, GETUTCDATE()) AND IsSMSSent = 1      
 IF @checkMsgTempCount > 0      
 BEGIN      
 SET @IsSMSsent=0       
 END      
           
 IF @bitSMSReached = 1 AND ISNULL(@tiMaxSMSLimit,0) <> 0 AND @IsSMSsent=1      
 BEGIN          
  INSERT INTO rvlfNotificationLog               
  (              
   [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,               
   [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,               
   [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],              
   [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,               
   [Subjectsufix] , [Duration] , [MessageDetails]               
  )              
  SELECT h.MessageInID,h.OriginDateTime,h.DateTimeReceived,1 AS CanSendEmail,0 AS IsMailSent,            
  1 AS CanSendSMS,0 AS IsSMSSent,u.UserId,v.OrganizationId,u.DisplayName,            
  u.Email,u.MobileNo,h.StreetAddress,            
  '0.00 MPH' AS Speed,h.BoxId,m.BoxMsgInTypeDesc,va.VehicleId,v.VehicleDescription,v.VehicleDescription,          
  f.FleetId,f.FleetName,v.LicensePlate,'Notify' AS Subjectsufix,NULL AS Duration,            
  @SMSMessage            
  FROM rvlfMsgInHst h INNER JOIN rvlfBoxMsgInType m ON m.BoxMsgInTypeId=h.BoxMsgInTypeId           
  INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId          
  INNER JOIN rvlfBoxId B ON B.BoxId=va.BoxId            
  INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId            
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId            
  INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId            
  INNER JOIN rvlfUser u ON u.OrganizationId=v.OrganizationId          
  WHERE f.FleetId = (SELECT TOP 1 FleetId From rvlfFleet WHERE OrganizationId=B.OrganizationId ORDER BY FleetId ASC) AND            
  u.UserId IN (SELECT TOP 1 UserId FROM rvlfUser WHERE OrganizationId=B.OrganizationId AND UserName like '%Admin%') AND          
  h.MessageInID = @uimessageInID           
    END          
              
    BEGIN            
  IF (@tiBoxMsgInTypeId = 2 OR @tiBoxMsgInTypeId = 3)            
   BEGIN            
    DECLARE @tiSensorNo tinyint            
    DECLARE @tiSensorStatus tinyint            
    DECLARE @intBoxID int            
    DECLARE @bitAction bit            
    DECLARE @intAlarmLevel int            
               
    SELECT @intBoxID=h.BoxId, @tiSensorNo = CASE WHEN BoxMsgInTypeId = 2             
    THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,            
     CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END ,            
     @bitAction = 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,             
     @tiBoxMsgInTypeId = BoxMsgInTypeId , @intAlarmLevel = e.AlarmLevelId             
     FROM rvlfMsgInHst h            
     LEFT OUTER JOIN rvlfBoxSensorsCfg s ON s.BoxId= h.BoxId and             
      s.SensorId = CASE WHEN BoxMsgInTypeId = 2 OR BoxMsgInTypeId = 3            
       THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,            
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END            
     INNER JOIN rvlfSeverity e ON e.AlarmLevelId  = CASE WHEN BoxMsgInTypeId=2 OR BoxMsgInTypeId = 3 THEN CAST( CASE WHEN (SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,            
     CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1)) = 'ON' THEN s.AlarmLevelOn ELSE s.AlarmLevelOff END as int)            
     ELSE 0 END            
     where MessageInID= @uimessageInID            
                   
    IF (@tiBoxMsgInTypeId = 2 OR @tiBoxMsgInTypeId = 3) AND @intAlarmLevel !=4            
     BEGIN                
      /* Vehicle Level Notification for Sensors*/            
      INSERT INTO rvlfNotificationLog             
      (            
       [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,             
       [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,             
       [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],            
       [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,             
       [Subjectsufix] , [Duration] , [MessageDetails]             
      )            
      SELECT h.MessageInID,             
       DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,             
       DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,             
       ISNULL(n.Email,0) as CanSendEmail,             
       CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,             
          -- Blocked the SMS for Org US Embassy 52 CASE WHEN v.OrganizationId = 52 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS,            
          CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,             
       u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,            
       CASE WHEN h.StreetAddress like 'Address Not Found' THEN             
         '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+            
         cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
        WHEN h.ValidGps = 0 THEN             
         h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )            
         +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
        ELSE h.StreetAddress END AS StreetAddress,            
       CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
       CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,            
       h.BoxId, m.BoxMsgInTypeName, v.VehicleId, v.VehicleDescription,            
        v.VehicleDescription  as VehicleName, null, null,            
       v.LicensePlate, S.AlarmLevelName  as Subjectsufix, null as Duration,             
       dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId, h.MessageInID, h.OriginDateTime) As MessageDetail            
      FROM rvlfMsgInHst h             
       INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId            
       INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId            
       INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId            
       LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID             
       INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
    INNER JOIN rvlfSeverity S ON S.AlarmLevelId=@intAlarmLevel          
       /**************** Map to user preferences *******************/            
       INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4            
       INNER JOIN rvlfUser u ON n.UserID = u.UserId            
       INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId            
       INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID            
       /**************** Map to user preferences *******************/            
      WHERE h.MessageInID=@uimessageInID /*AND IsNotificationSent = 0 and h.BoxMsgInTypeId = 11 in (2,3)*/ and h.StreetAddress IS NOT NULL            
       AND v.Notify != 4 AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0            
       AND H.IsNotificationSent=0            
       AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity            
        WHERE ModuleId = 26 and UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))            
                    
                  
      /* Fleet Level Notification for Sensors*/             
      INSERT INTO rvlfNotificationLog             
       (            
        [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,             
        [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,             
        [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],            
        [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,             
        [Subjectsufix] , [Duration] , [MessageDetails]             
       )            
      SELECT h.MessageInID,             
       DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,             
       DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,             
       ISNULL(n.Email,0) as CanSendEmail,             
       CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,             
        -- Blocked the SMS for Org US Embassy 52            
         CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,             
       u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,            
       CASE WHEN h.StreetAddress like 'Address Not Found' THEN             
         '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+            
         cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
        WHEN h.ValidGps = 0 THEN             
         h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )            
         +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
        ELSE h.StreetAddress END AS StreetAddress,            
       CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
       CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,            
       h.BoxId, m.BoxMsgInTypeName, v.VehicleId, v.VehicleDescription,            
        v.VehicleDescription  as VehicleName, null, null,            
       v.LicensePlate, 'Notify' as Subjectsufix, null as Duration,             
       dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId, h.MessageInID, h.OriginDateTime) As MessageDetail            
      FROM rvlfMsgInHst h             
       INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId            
       INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId            
       INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId            
       LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID             
       INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
       /**************** Map to user preferences *******************/            
       INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId            
       INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId            
       INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3            
       INNER JOIN rvlfUser u ON n.UserID = u.UserId            
       INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId            
       INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID            
       /**************** Map to user preferences *******************/            
      WHERE h.MessageInID=@uimessageInID /*AND IsNotificationSent = 0 and h.BoxMsgInTypeId = 11 in (2,3)*/ and h.StreetAddress IS NOT NULL            
       AND f.Notify !=4                   
       AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0            
       AND H.IsNotificationSent=0               
       AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity                
       WHERE ModuleId = 26 and UserGroupId IN             
       (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))            
     END            
   END            
    
PRINT 'Tamper'             
 /**********************************************************************************/            
 /**************************** Vehicle Level Notification ****************************/            
 /**********************************************************************************/            
 /**************************** Based on Tampering ****************************/            
  INSERT INTO rvlfNotificationLog             
   (            
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,             
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,             
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],            
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,             
    [Subjectsufix] , [Duration] , [MessageDetails]             
   )            
  SELECT h.MessageInID,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,             
    ISNULL(n.Email,0) as CanSendEmail,             
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,             
     -- Blocked the SMS for Org US Embassy 52            
     CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,             
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,            
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN             
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+            
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     WHEN h.ValidGps = 0 THEN             
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )            
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     ELSE h.StreetAddress END AS StreetAddress,            
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,            
    h.BoxId, m.BoxMsgInTypeName, v.VehicleId, v.VehicleDescription,            
     v.VehicleDescription  as VehicleName, null, null,            
    v.LicensePlate, 'Critical' as Subjectsufix, null as Duration,             
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId, h.MessageInID, h.OriginDateTime) As MessageDetails            
  FROM rvlfMsgInHst h             
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId            
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId            
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId            
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID             
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
                 
   /**************** Map to user preferences *******************/            
   INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4            
   INNER JOIN rvlfUser u ON n.UserID = u.UserId            
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId            
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID            
   /**************** Map to user preferences *******************/            
               
  WHERE h.MessageInID=@uimessageInID AND IsNotificationSent = 0 and h.BoxMsgInTypeId =11 /*in (2,3)*/ and h.StreetAddress IS NOT NULL            
   AND (case when            
    (case when v.Notify='true' then 'Notify' else '' end +                
    case when v.Warning='true' then 'Warning' else '' end +             
    case when v.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else            
    (case  when v.Notify='true' then (case when (v.Warning='true' or v.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +                
    case when v.Warning='true' then (case when v.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +             
    case when v.Critical='true' then 'Critical' else '' end)            
    end LIKE '%Critical%')             
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0            
   AND H.IsNotificationSent=0            
   AND dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId, h.MessageInID, h.OriginDateTime) = 'Tamper'            
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity            
   WHERE ModuleId = 26 and UserGroupId IN             
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))            
      
  PRINT 'Message'                      
 /**************************** Based on Box Message Severity ****************************/            
  INSERT INTO rvlfNotificationLog             
   (            
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,             
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,             
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],            
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,             
    [Subjectsufix] , [Duration] , [MessageDetails]             
   )            
  SELECT * FROM (            
  SELECT h.MessageInID,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,             
    ISNULL(n.Email,0) as CanSendEmail,             
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,             
     -- Blocked the SMS for Org US Embassy 52            
     CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,             
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,            
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN             
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+            
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     WHEN h.ValidGps = 0 THEN             
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )            
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     ELSE h.StreetAddress END AS StreetAddress,            
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,            
    h.BoxId, m.BoxMsgInTypeName, v.VehicleId, v.VehicleDescription,            
      v.VehicleDescription as VehicleName, null as FleetID, null as FleetName,            
    v.LicensePlate, s.AlarmLevelName as Subjectsufix,            
    CASE WHEN m.BoxMsgInTypeName<>'Sensor'             
     THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeName,CustomProp,1) = 1 THEN             
      SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,            
      CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END as Duration,             
    CASE WHEN h.BoxMsgInTypeId = 4 THEN m.BoxMsgInTypeDesc + ' ' +            
      CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
      CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END            
     ELSE dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails            
   FROM rvlfMsgInHst h             
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId            
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId            
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId            
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID             
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
   INNER JOIN rvlfBoxMsgSeverity ms ON h.BoxId = ms.BoxId and ms.BoxMsgInTypeId = h.BoxMsgInTypeId            
   INNER JOIN rvlfSeverity s ON ms.AlarmLevelID = s.AlarmLevelId             
               
   /**************** Map to user preferences *******************/            
   INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4            
   INNER JOIN rvlfUser u ON n.UserID = u.UserId            
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId            
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID            
   /**************** Map to user preferences *******************/            
  WHERE h.MessageInID=@uimessageInID AND h.IsNotificationSent=0 and h.StreetAddress IS NOT NULL and s.CanSendNotification = 1 and h.BoxMsgInTypeId not in (5,6,2,3,121)            
   AND  ( case when            
   (case when v.Notify='true' then 'Notify' else '' end +             
   case when v.Warning='true' then 'Warning' else '' end +             
   case when v.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else            
   (case  when v.Notify='true' then (case when (v.Warning='true' or v.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +                
   case when v.Warning='true' then (case when v.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +             
   case when v.Critical='true' then 'Critical' else '' end)            
   end LIKE '%'+s.AlarmLevelName +'%') AND s.CanSendNotification = 1            
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0            
   AND H.IsNotificationSent=0            
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity            
   WHERE ModuleId = 26 and UserGroupId IN             
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))            
  ) as a WHERE (Duration is null or Duration > 0)            
PRINT 'Default'              
 /**************************** Based on Default Severity ****************************/               
  INSERT INTO rvlfNotificationLog             
   (              [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,             
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,             
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],            
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,             
    [Subjectsufix] , [Duration] , [MessageDetails]             
   )            
   SELECT * FROM (            
   SELECT h.MessageInID,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,             
    ISNULL(n.Email,0) as CanSendEmail,             
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,             
     -- Blocked the SMS for Org US Embassy 52            
     CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,             
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,            
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN             
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+            
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     WHEN h.ValidGps = 0 THEN             
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )            
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     ELSE h.StreetAddress END AS StreetAddress,            
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,            
    h.BoxId, m.BoxMsgInTypeName, v.VehicleId, v.VehicleDescription,            
    --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'             
     --ELSE v.VehicleDescription END             
     v.VehicleDescription  as VehicleName, null as FleetID, null as FleetName,            
    v.LicensePlate, s.AlarmLevelName as Subjectsufix,            
    CASE WHEN m.BoxMsgInTypeName<>'Sensor'             
     THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeName,CustomProp,1) = 1 THEN             
      SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,            
      CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END as Duration,             
    CASE WHEN h.BoxMsgInTypeId = 4 THEN m.BoxMsgInTypeDesc + ' ' +            
      CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
      CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END            
     ELSE dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails            
   FROM rvlfMsgInHst h             
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId            
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId       
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId            
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID             
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
   INNER JOIN rvlfBoxProtocolMsgInType ms ON h.BoxMsgInTypeId = ms.BoxMsgInTypeId            
   INNER JOIN rvlfSeverity s ON ms.DefaultAlarmLevel = s.AlarmLevelId             
               
   /**************** Map to user preferences *******************/            
   INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4            
   INNER JOIN rvlfUser u ON n.UserID = u.UserId            
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId            
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID            
   /**************** Map to user preferences *******************/            
               
  WHERE h.MessageInID=@uimessageInID AND h.IsNotificationSent=0  and h.StreetAddress IS NOT NULL  and h.StreetAddress IS NOT NULL and s.CanSendNotification = 1 and h.BoxMsgInTypeId not in (5,6,2,3,121)            
   AND  ( case when            
   (case when v.Notify='true' then 'Notify' else '' end +                
   case when v.Warning='true' then 'Warning' else '' end +             
   case when v.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else            
   (case  when v.Notify='true' then (case when (v.Warning='true' or v.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +                
   case when v.Warning='true' then (case when v.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +             
   case when v.Critical='true' then 'Critical' else '' end)            
   end LIKE '%'+s.AlarmLevelName +'%') AND h.BoxMsgInTypeId NOT IN             
    (SELECT BoxMsgInTypeId  FROM rvlfBoxMsgSeverity bms WHERE bms.BoxId = h.BoxId ) AND s.CanSendNotification = 1            
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0            
   AND H.IsNotificationSent=0            
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity            
   WHERE ModuleId = 26 and UserGroupId IN             
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))            
         ) as a Where (Duration is null or Duration > 0)            
    PRINT 'Sensor'             
    /**************************** Based on Sensor Severity ****************************/            
  INSERT INTO rvlfNotificationLog             
   (            
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,             
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,             
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],            
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,             
    [Subjectsufix] , [Duration] , [MessageDetails]             
   )            
   SELECT h.MessageInID,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,             
    ISNULL(n.Email,0) as CanSendEmail,             
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,             
     -- Blocked the SMS for Org US Embassy 52            
     CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,             
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,            
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN             
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+            
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     WHEN h.ValidGps = 0 THEN       
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )            
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     ELSE h.StreetAddress END AS StreetAddress,            
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,            
    h.BoxId, m.BoxMsgInTypeName, v.VehicleId, v.VehicleDescription,            
    --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'             
     --ELSE v.VehicleDescription END             
     v.VehicleDescription  as VehicleName, null, null,            
    v.LicensePlate, s.AlarmLevelName as Subjectsufix, null as Duration,             
    --rs.SensorName+' '+SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,             
    --CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1) As MessageDetails            
    rs.SensorName + ' ' + CASE WHEN SUBSTRING(CustomProp,CHARINDEX('SENSOR_STATUS=',CustomProp,0)+14,          
   (CHARINDEX(';',CustomProp,(CHARINDEX('SENSOR_STATUS=',CustomProp,0)))-(CHARINDEX('SENSOR_STATUS=',CustomProp,0)+14))) = 'ON'             
    THEN rs.ActionOn ELSE rs.ActionOff END AS MessageDetails           
  FROM rvlfMsgInHst h             
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId            
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId            
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId            
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID             
   INNER JOIN rvlfSensor rs ON  CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,            
    CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) = rs.SensorId            
   INNER JOIN rvlfBoxSensorsCfg bs ON bs.SensorId = rs.SensorId AND h.BoxId = bs.BoxId            
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
   INNER JOIN rvlfSeverity s ON s.AlarmLevelId =            
    (CASE WHEN SUBSTRING(CustomProp,CHARINDEX('SENSOR_STATUS=',CustomProp,0)+14,          
   (CHARINDEX(';',CustomProp,(CHARINDEX('SENSOR_STATUS=',CustomProp,0)))-(CHARINDEX('SENSOR_STATUS=',CustomProp,0)+14)))                       
  IN ('OPEN','ON','NORMAL','OK')            
     THEN bs.AlarmLevelOn ELSE bs.AlarmLevelOff END)          
                 
   /**************** Map to user preferences *******************/            
   INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4            
   INNER JOIN rvlfUser u ON n.UserID = u.UserId            
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId            
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID            
   /**************** Map to user preferences *******************/            
               
  WHERE h.MessageInID=@uimessageInID AND h.BoxMsgInTypeId = 11 /*in (2,3)*/ AND h.IsNotificationSent = 0 and h.StreetAddress IS NOT NULL            
   AND (case when            
    (case when v.Notify='true' then 'Notify' else '' end +                
    case when v.Warning='true' then 'Warning' else '' end +             
    case when v.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else            
    (case  when v.Notify='true' then (case when (v.Warning='true' or v.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +                
    case when v.Warning='true' then (case when v.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +             
    case when v.Critical='true' then 'Critical' else '' end)            
    end LIKE '%'+s.AlarmLevelName +'%') AND s.CanSendNotification = 1           
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0            
   AND H.IsNotificationSent=0            
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity            
   WHERE ModuleId = 26 and UserGroupId IN             
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))            
 /**********************************************************************************/            
            
 /**********************************************************************************/            
 /**************************** Fleet Level Notification ****************************/            
 /**********************************************************************************/            
             
  /**************************** Based on Tampering ****************************/            
  INSERT INTO rvlfNotificationLog             
   (            
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,             
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,             
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],            
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,             
    [Subjectsufix] , [Duration] , [MessageDetails]             
   )            
  SELECT h.MessageInID,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,             
    ISNULL(n.Email,0) as CanSendEmail,             
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,             
     -- Blocked the SMS for Org US Embassy 52            
     CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,             
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,            
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN             
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+            
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     WHEN h.ValidGps = 0 THEN             
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )            
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     ELSE h.StreetAddress END AS StreetAddress,            
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,            
    h.BoxId, m.BoxMsgInTypeName, v.VehicleId, v.VehicleDescription,             
       v.VehicleDescription as VehicleName, f.FleetId , f.FleetName,            
    v.LicensePlate, 'Critical' as Subjectsufix, null as Duration,             
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId, h.MessageInID, h.OriginDateTime) As MessageDetails            
  FROM rvlfMsgInHst h             
              
    INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId            
    INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId            
    INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId            
    LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID             
    INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId            
    INNER JOIN rvlfFleet f On fv.FleetId = f.FleetID            
               
                 
   /**************** Map to user preferences *******************/            
   INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3            
   INNER JOIN rvlfUser u ON n.UserID = u.UserId            
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId            
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID            
 /**************** Map to user preferences *******************/            
               
  WHERE h.MessageInID=@uimessageInID AND IsNotificationSent = 0 and h.BoxMsgInTypeId = 11 /*in (2,3)*/ and h.StreetAddress IS NOT NULL            
   AND (case when            
    (case when f.Notify='true' then 'Notify' else '' end +                
    case when f.Warning='true' then 'Warning' else '' end +             
    case when f.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else            
    (case  when f.Notify='true' then (case when (f.Warning='true' or f.Critical='true')            
     then 'Notify;' else 'Notify' end ) else '' end +                
    case when f.Warning='true' then (case when f.Critical='true' then 'Warning;'             
    else 'Warning' end ) else '' end +             
    case when f.Critical='true' then 'Critical' else '' end)            
    end LIKE '%Critical%')             
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0            
   AND H.IsNotificationSent=0            
   AND dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId, h.MessageInID, h.OriginDateTime) = 'Tamper'            
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity            
   WHERE ModuleId = 26 and UserGroupId IN             
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))            
               
  /**************************** Based on Box Message Severity ****************************/            
   INSERT INTO rvlfNotificationLog             
    (            
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,             
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,             
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],            
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,             
    [Subjectsufix] , [Duration] , [MessageDetails]             
   )            
   SELECT * FROM (SELECT h.MessageInID,             
     DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,             
     DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,             
     ISNULL(n.Email,0) as CanSendEmail,             
     CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,             
      -- Blocked the SMS for Org US Embassy 52            
      CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,             
     u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,            
     CASE WHEN h.StreetAddress like 'Address Not Found' THEN             
       '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+            
       cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
      WHEN h.ValidGps = 0 THEN             
       h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )            
       +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
      ELSE h.StreetAddress END AS StreetAddress,            
     CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
     CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,            
     h.BoxId, m.BoxMsgInTypeName, v.VehicleId, v.VehicleDescription,              
       v.VehicleDescription as VehicleName, f.FleetId, f.FleetName,            
     v.LicensePlate, s.AlarmLevelName as Subjectsufix,            
     CASE WHEN m.BoxMsgInTypeName<>'Sensor'             
      THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeName,CustomProp,1) = 1 THEN             
       SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,            
       CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END as Duration,             
    CASE WHEN h.BoxMsgInTypeId = 4 THEN m.BoxMsgInTypeDesc + ' ' +            
      CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
      CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END            
      ELSE dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails            
   from rvlfMsgInHst h             
    INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId            
    INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId            
    INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId            
    LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID             
    INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId            
    INNER JOIN rvlfFleet f On fv.FleetId = f.FleetId            
    INNER JOIN rvlfBoxMsgSeverity ms ON h.BoxId = ms.BoxId and ms.BoxMsgInTypeId = h.BoxMsgInTypeId            
    INNER JOIN rvlfSeverity s ON ms.AlarmLevelID = s.AlarmLevelId             
                
    /**************** Map to user preferences *******************/            
    INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3            
    INNER JOIN rvlfUser u ON n.UserID = u.UserId            
    INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId            
    INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID            
    /**************** Map to user preferences *******************/            
                
   WHERE h.MessageInID=@uimessageInID AND h.IsNotificationSent=0  and h.StreetAddress IS NOT NULL  and h.StreetAddress IS NOT NULL and s.CanSendNotification = 1 and h.BoxMsgInTypeId not in (5,6,2,3,121)            
    AND  ( case when            
     (case when f.Notify='true' then 'Notify' else '' end +                
     case when f.Warning='true' then 'Warning' else '' end +             
     case when f.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else            
     (case  when f.Notify='true' then (case when (f.Warning='true' or f.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +                
     case when f.Warning='true' then (case when f.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +             
     case when f.Critical='true' then 'Critical' else '' end)            
     end LIKE '%'+s.AlarmLevelName +'%') AND s.CanSendNotification = 1            
    AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0            
    AND H.IsNotificationSent=0            
    AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity            
   WHERE ModuleId = 26 and UserGroupId IN             
    (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))            
    ) as a where (Duration is null Or Duration > 0)            
  /**************************** Based on Default Severity ****************************/               
   INSERT INTO rvlfNotificationLog  (            
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,             
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,             
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],            
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,             
    [Subjectsufix] , [Duration] , [MessageDetails]             
   )            
   SELECT * FROM (            
   SELECT h.MessageInID,             
     DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,             
     DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,             
     ISNULL(n.Email,0) as CanSendEmail,             
     CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,             
      -- Blocked the SMS for Org US Embassy 52            
       CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,             
     u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,            
     CASE WHEN h.StreetAddress like 'Address Not Found' THEN             
       '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+            
       cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
      WHEN h.ValidGps = 0 THEN             
       h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )            
       +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
      ELSE h.StreetAddress END AS StreetAddress,            
     CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
     CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,            
     h.BoxId, m.BoxMsgInTypeName, v.VehicleId, v.VehicleDescription,            
     --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'             
      --ELSE v.VehicleDescription END              
     v.VehicleDescription as VehicleName, f.FleetId, f.FleetName,        
     v.LicensePlate, s.AlarmLevelName as Subjectsufix,            
     CASE WHEN m.BoxMsgInTypeName<>'Sensor'             
      THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeName,CustomProp,1) = 1 THEN             
       SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,            
       CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END as Duration,             
    CASE WHEN h.BoxMsgInTypeId = 4 THEN m.BoxMsgInTypeDesc + ' ' +            
      CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
      CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END            
      ELSE dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails            
   from rvlfMsgInHst h             
    INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId            
    INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId            
    INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId            
    LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID             
    INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId            
    INNER JOIN rvlfFleet f On fv.FleetId = f.FleetId            
    INNER JOIN rvlfBoxProtocolMsgInType ms ON h.BoxMsgInTypeId = ms.BoxMsgInTypeId            
    INNER JOIN rvlfSeverity s ON ms.DefaultAlarmLevel = s.AlarmLevelId             
                
    /**************** Map to user preferences *******************/            
    INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3            
    INNER JOIN rvlfUser u ON n.UserID = u.UserId            
    INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId            
    INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID            
    /**************** Map to user preferences *******************/            
                
   WHERE h.MessageInID=@uimessageInID AND h.IsNotificationSent=0  and h.StreetAddress IS NOT NULL and s.CanSendNotification = 1 and h.BoxMsgInTypeId not in (5,6,2,3,121)            
    AND  ( case when            
     (case when f.Notify='true' then 'Notify' else '' end +                
     case when f.Warning='true' then 'Warning' else '' end +             
     case when f.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else            
     (case  when f.Notify='true' then (case when (f.Warning='true' or f.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +                
     case when f.Warning='true' then (case when f.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +             
     case when f.Critical='true' then 'Critical' else '' end)            
     end LIKE '%'+s.AlarmLevelName +'%')             
    AND h.BoxMsgInTypeId NOT IN             
     (SELECT BoxMsgInTypeId  FROM rvlfBoxMsgSeverity bms WHERE bms.BoxId = h.BoxId ) AND s.CanSendNotification = 1            
    AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0            
    AND H.IsNotificationSent=0            
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity            
   WHERE ModuleId = 26 and UserGroupId IN             
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))            
    ) as A Where (Duration is null or Duration > 0)            
  /**************************** Based on Sensor Severity ****************************/            
   INSERT INTO rvlfNotificationLog             
    (            
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,             
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,             
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],            
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,             
    [Subjectsufix] , [Duration] , [MessageDetails]        
   )            
   SELECT h.MessageInID,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,             
    ISNULL(n.Email,0) as CanSendEmail,             
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,             
     -- Blocked the SMS for Org US Embassy 52            
     CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,             
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,            
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN             
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+            
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     WHEN h.ValidGps = 0 THEN             
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )            
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     ELSE h.StreetAddress END AS StreetAddress,            
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,            
    h.BoxId, m.BoxMsgInTypeName, v.VehicleId, v.VehicleDescription,                
     v.VehicleDescription as VehicleName, f.FleetId, f.FleetName,            
    v.LicensePlate, s.AlarmLevelName as Subjectsufix,null as Duration,                
   rs.SensorName + ' ' + CASE WHEN SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,             
    CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1) = 'ON'             
    THEN rs.ActionOn ELSE rs.ActionOff END AS MessageDetails            
  FROM rvlfMsgInHst h             
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId            
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId            
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId            
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID             
   INNER JOIN rvlfSensor rs ON  CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,            
    CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) = rs.SensorId            
   INNER JOIN rvlfBoxSensorsCfg bs ON bs.SensorId = rs.SensorId AND h.BoxId = bs.BoxId            
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId            
   INNER JOIN rvlfFleet f On fv.FleetId = f.FleetId            
   INNER JOIN rvlfSeverity s ON s.AlarmLevelId =            
    (CASE WHEN SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,            
     CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1)             
     IN ('OPEN','ON','NORMAL','OK')            
     THEN bs.AlarmLevelOn ELSE bs.AlarmLevelOff END)            
               
   /**************** Map to user preferences *******************/            
   INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3            
   INNER JOIN rvlfUser u ON n.UserID = u.UserId            
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId            
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID            
   /**************** Map to user preferences *******************/            
               
  WHERE h.MessageInID=@uimessageInID AND h.BoxMsgInTypeId = 11 /*in (2,3) */ AND h.IsNotificationSent = 0 and h.StreetAddress is not null            
   AND (case when            
    (case when f.Notify='true' then 'Notify' else '' end +                
    case when f.Warning='true' then 'Warning' else '' end +             
    case when f.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else            
    (case  when f.Notify='true' then (case when (f.Warning='true' or f.Critical='true')            
     then 'Notify;' else 'Notify' end ) else '' end +                
    case when f.Warning='true' then (case when f.Critical='true' then 'Warning;'             
    else 'Warning' end ) else '' end +             
    case when f.Critical='true' then 'Critical' else '' end)            
    end LIKE '%'+s.AlarmLevelName +'%') AND s.CanSendNotification = 1            
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0             
   AND H.IsNotificationSent=0            
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity            
   WHERE ModuleId = 26 and UserGroupId IN             
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))            
 /**********************************************************************************/            
 /**************************** Geozone Level Notification **************************/            
 /**********************************************************************************/            
       
 DECLARE @IsUnauthorized BIT = 0                          
 DECLARE @GeoID VARCHAR(5) = 0,@GeoBoxIDs BIGINT = 0, @geoZoneName NVARCHAR(250) = 0,                          
    @VehicleName NVARCHAR(250)        
          
          
    SELECT @GeoBoxIDs = BoxId,@GeoID =CASE WHEN @tiBoxMsgInTypeId=114 AND CustomProp Like 'GeozoneInOutWithDuration%' THEN  
    SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,0)+1,(CHARINDEX(';Dur',CustomProp,0)-(CHARINDEX('=',CustomProp,0)+1)))  
    ELSE SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,1)+1,                            
 (CHARINDEX(';',CustomProp,1) - CHARINDEX('=',CustomProp,1))-1) end   
    --(CAST( SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,1)+1,                            
 --(CHARINDEX(';',CustomProp,1) - CHARINDEX('=',CustomProp,1))-1) as bigint))                            
 FROM rvlfMsgInHst WHERE MessageInID = @uimessageInID                            
                             
 SELECT @geoZoneName = GeozoneName, @IsUnauthorized = IsUnAuthorizedGeozone,                          
 @VehicleName = V.VehicleDescription FROM rvlfVehicleAssignment VA          
 INNER JOIN rvlfVehicleGeozone VG ON VA.VehicleId = VG.VehicleId                            
 INNER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId = VG.GeozoneNo                          
 INNER JOIN rvlfVehicle V ON V.VehicleId = VA.VehicleId AND V.OrganizationId = OG.OrganizationId                            
 WHERE BoxId = @GeoBoxIDs AND GeozoneId = @GeoID           
       
       
       
       
 IF(@IsUnauthorized = 1 AND @tiBoxMsgInTypeId = 5)              
  BEGIN       
        
  INSERT INTO rvlfNotificationLog                                               
  (                                              
   [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,                                               
   [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,                                               
   [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],                                              
   [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,                           
   [Subjectsufix] , [Duration] , [MessageDetails]                                               
  )                                     
  SELECT DISTINCT h.MessageInID,                                
  DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,                                
  DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,                                
  ISNULL(n.Email,0) as CanSendEmail,                                
  CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,                                
  -- Blocked the SMS for Org US Embassy 52                                              
  CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,                                               
  u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,               
  CASE WHEN h.StreetAddress like 'Address Not Found' THEN                                
  '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+                                
  cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'                                              
  WHEN h.ValidGps = 0 THEN                                               
  h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )                                              
  +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'                                              
  ELSE h.StreetAddress END AS StreetAddress,          
  CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +                                               
  CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,                                              
  h.BoxId, 'Unauthorized Geozone IN ',--m.BoxMsgInTypeName           
  v.VehicleId, v.VehicleDescription,                                                  
  v.VehicleDescription as VehicleName, null, null,                                              
  v.LicensePlate, s.AlarmLevelName as Subjectsufix, '-' as Duration,                                                   
  --dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.boxMsgintypeid, h.boxid, h.MessageInid, h.origindatetime ) as MessageDetails                                              
  ('"' +               
  (CASE WHEN up.Lang = 'LanguageArNew' THEN VehicleDescription ELSE VehicleDescription  END)              
  + '"' +               
  (CASE WHEN up.Lang = 'LanguageArNew' THEN N'دخلت المنطقة الجغرافية غير المصرح به' ELSE ' entered the unauthorized geozone ' END)              
  +'"' +              
  (CASE WHEN up.Lang = 'LanguageArNew' THEN g.GeozoneName ELSE g.GeozoneName END)              
  +'"') as MessageDetails                          
  FROM rvlfMsgInHst h INNER JOIN rvlfVehicleAssignment a ON h.BoxId = a.BoxId                        
  INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId                                              
  INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId                                              
  LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID                                               
  INNER JOIN rvlfVehicle v ON a.VehicleId = v.VehicleId                                               
  INNER JOIN rvlfOrganizationGeozone g ON g.OrganizationId = v.OrganizationId                                              
  INNER JOIN rvlfVehicleGeozone vg ON g.GeozoneId = vg.GeozoneNo AND vg.VehicleId = v.VehicleId                                 
  /**************** Map to user preferences *******************/        
  INNER JOIN rvlfNotificationList n ON g.GeozoneNo = n.TypeID and n.NotificationType=1                                              
  INNER JOIN rvlfUser u ON n.UserID = u.UserId                                              
  INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId                                              
  INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID                                              
  /**************** Map to user preferences *******************/                                                        
  INNER JOIN rvlfSeverity s ON g.SeverityId = s.AlarmLevelId                                       
  WHERE h.MessageInID=@uimessageInID AND s.CanSendNotification = 1 AND h.BoxMsgInTypeId in (5) AND                                
  s.CanSendNotification=1 AND h.IsNotificationSent = 0 and h.StreetAddress IS NOT NULL                              
  AND g.GeozoneId = @GeoID--(CAST( SUBSTRING(h.CustomProp,CHARINDEX('=',h.CustomProp,1)+1,(CHARINDEX(';',h.CustomProp,1)- CHARINDEX('=',h.CustomProp,1))-1) as bigint))                                    
  AND vg.IsUnAuthorizedGeozone = 1                          
  AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0                                       
  AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity                                              
  WHERE ModuleId = 26 and UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))                                
        
   END      
   ELSE BEGIN      
          
       
  INSERT INTO rvlfNotificationLog             
   (            
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,             
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,             
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],            
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,             
    [Subjectsufix] , [Duration] , [MessageDetails]      
   )      
   SELECT DISTINCT(h.MessageInID),             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,             
    ISNULL(n.Email,0) as CanSendEmail,             
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,             
     -- Blocked the SMS for Org US Embassy 52            
    CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,             
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,            
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN             
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+            
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     WHEN h.ValidGps = 0 THEN             
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )            
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     ELSE h.StreetAddress END AS StreetAddress,            
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,            
    h.BoxId, m.BoxMsgInTypeName, v.VehicleId, v.VehicleDescription,                
     v.VehicleDescription as VehicleName, null, null,            
    v.LicensePlate, s.AlarmLevelName as Subjectsufix, null as Duration,                 
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.boxMsgintypeid, h.boxid, h.MessageInid, h.origindatetime ) as MessageDetails            
 FROM rvlfMsgInHst h             
   INNER JOIN rvlfVehicleAssignment a ON h.BoxId = a.BoxId            
   INNER JOIN rvlfBoxMsgInType m ON m.BoxMsgInTypeId = --m.BoxMsgInTypeId   
   (CASE WHEN (h.BoxMsgInTypeId = 114 AND h.CustomProp Like 'GeozoneInOutWith%') THEN 132 ELSE  h.BoxMsgInTypeId END)              
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId            
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID             
  INNER JOIN rvlfVehicle v ON a.VehicleId = v.VehicleId             
  INNER JOIN rvlfOrganizationGeozone g ON g.OrganizationId = v.OrganizationId            
   INNER JOIN rvlfVehicleGeozone vg ON g.GeozoneId=vg.GeozoneNo            
  /**************** Map to user preferences *******************/            
   INNER JOIN rvlfNotificationList n ON g.GeozoneNo = n.TypeID and n.NotificationType=1            
   INNER JOIN rvlfUser u ON n.UserID = u.UserId            
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId            
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID            
  /**************** Map to user preferences *******************/            
              
  INNER JOIN rvlfSeverity s ON g.SeverityId = s.AlarmLevelId            
  --INNER JOIN rvlftimebasedgeozone tbg ON tbg.geozoneid = vg.GeozoneNo         
  WHERE h.MessageInID=@uimessageInID 
  AND s.CanSendNotification=1 and
  (h.BoxMsgInTypeId in (5,6) OR (h.BoxMsgInTypeId=114 AND h.CustomProp LIKE 'GeozoneInOutWithDuration%')) and
  --AND h.BoxMsgInTypeId in (5,6) AND--h.StreetAddress IS NOT NULL  AND            
    h.IsNotificationSent = 0 and h.StreetAddress IS NOT NULL            
   AND g.GeozoneId = @GeoID--(CAST( SUBSTRING(h.CustomProp,CHARINDEX('=',h.CustomProp,1)+1,(CHARINDEX(';',h.CustomProp,1) - CHARINDEX('=',h.CustomProp,1))-1) as bigint))   
     AND s.CanSendNotification = 1            
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0            
   AND H.IsNotificationSent=0            
  AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity            
   WHERE ModuleId = 26 and UserGroupId IN             
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))       
         
   END           
--    AND (tbg.FromDate IS NULL AND tbg.Todate IS NULL OR(          
--    (DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))              
--   BETWEEN tbg.FromDate AND tbg.Todate)               
--   AND (DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))              
--   BETWEEN  DATEADD(MINUTE,CAST(substring(fromtime,CHARINDEX(':',fromtime)+1,2) AS INT),DATEADD(Hour,CAST(substring(fromtime,0,CHARINDEX(':',fromtime)) AS INT),DATEADD(Day, DATEDIFF(Day, 0,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded,    
-- h.OriginDa      
--teTime))), 0) ))              
--AND  DATEADD(MINUTE,CAST(substring(totime,CHARINDEX(':',totime)+1,2) AS INT),DATEADD(Hour,CAST(substring(totime,0,CHARINDEX(':',totime)) AS INT),DATEADD(Day, DATEDIFF(Day, 0,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))),0) 
  
     
        
--))              
--   OR(              
--   DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))                 
--BETWEEN  DATEADD(MINUTE,CAST(substring(fromtime1,CHARINDEX(':',fromtime1)+1,2) AS INT),DATEADD(Hour,CAST(substring(fromtime1,0,CHARINDEX(':',fromtime1)) AS INT),DATEADD(Day, DATEDIFF(Day, 0,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.Origi 
  
     
--nDateTime))), 0)))              
--AND DATEADD(MINUTE,CAST(substring(totime1,CHARINDEX(':',totime1)+1,2) AS INT),DATEADD(Hour,CAST(substring(totime1,0,CHARINDEX(':',totime1)) AS INT),DATEADD(Day, DATEDIFF(Day, 0,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))), 
  
     
-- 0)))))              
                    
--   AND (tbg.recurrencedays IS NULL OR (tbg.recurrencedays LIKE '%'+ CAST(DATEPART(weekday,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime))) AS VARCHAR(15))+'%'))))          
             
 /*******************************Notify for Deleted geozones***********************************/           
 -- IF NOT EXISTS(SELECT * FROM rvlfNotificationLog WHERE MessageInID =@uimessageInID)          
 --BEGIN            
 -- INSERT INTO rvlfNotificationLog           
 -- (          
 --  [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,           
 --  [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,           
 --  [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],          
 --  [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,           
 --  [Subjectsufix] , [Duration] , [MessageDetails]           
 -- )            
 -- SELECT Geo.MessageInID,Geo.OriginDateTime,Geo.DateTimeReceived,Geo.CanSendEmail,Geo.IsMailSent,          
 --  Geo.CanSendSMS,Geo.IsSMSSent,Geo.UserId,Geo.OrganizationId,Geo.Username,Geo.Email,          
 --  Geo.MobileNo,Geo.StreetAddress,Geo.Speed,Geo.BoxId,Geo.BoxMsgInTypeDesc,Geo.VehicleId,          
 --  Geo.VehicleDescription,Geo.VehicleDescription,Geo.FleetId,Geo.FleetName,Geo.LicensePlate,          
 --  Geo.Subjectsufix,Geo.Duration,Geo.MessageDetails FROM          
-- (SELECT h.MessageInID,h.OriginDateTime,h.DateTimeReceived,1 AS CanSendEmail,0 AS IsMailSent,          
 -- 0 AS CanSendSMS,NULL  AS IsSMSSent,341 AS UserId,v.OrganizationId,'Sakthi' AS Username,          
 -- 'sakthigopinath@angleritech.com' AS Email,'' AS MobileNo,h.StreetAddress,          
 -- '0.00 MPH' AS Speed,h.BoxId,m.BoxMsgInTypeDesc,va.VehicleId,v.VehicleDescription,          
 -- f.FleetId,f.FleetName,v.LicensePlate,'Notify' AS Subjectsufix,NULL AS Duration,          
 -- dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,h.MessageInID,h.OriginDateTime) as MessageDetails          
 -- FROM rvlfMsgInHst h INNER JOIN rvlfBoxMsgInType m ON m.BoxMsgInTypeId=h.BoxMsgInTypeId          
 -- INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId           
 -- INNER JOIN rvlfBoxId B ON B.BoxId=va.BoxId          
 -- INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId          
 -- INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId          
 -- INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId          
 -- WHERE f.FleetId = (SELECT TOP 1 FleetId From rvlfFleet WHERE OrganizationId=B.OrganizationId ORDER BY FleetId ASC) AND          
 -- h.BoxMsgInTypeId in (5,6) AND h.MessageInID=@uimessageInID) AS Geo          
 -- WHERE Geo.MessageDetails like '%Deleted%'          
 --END          
 /*******************************End for Deleted Geozones***********************************************/             
             
 /**********************************************************************************/                
 /**************************** Landmark Level Notification *************************/            
 /**********************************************************************************/            
  INSERT INTO rvlfNotificationLog             
   (            
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,             
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,             
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],            
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,             
    [Subjectsufix] , [Duration] , [MessageDetails]             
   )            
   SELECT h.MessageInID,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,             
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,             
    ISNULL(n.Email,0) as CanSendEmail,             
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,             
     -- Blocked the SMS for Org US Embassy 52            
     CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,             
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,            
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN             
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+            
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     WHEN h.ValidGps = 0 THEN             
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )            
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'            
     ELSE h.StreetAddress END AS StreetAddress,            
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +             
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,            
    h.BoxId, m.BoxMsgInTypeName, v.VehicleId, v.VehicleDescription,            
    --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'             
     --ELSE v.VehicleDescription END            
     v.VehicleDescription  as VehicleName, null, null,            
    v.LicensePlate,             
    CASE WHEN fm.Notify = 1 THEN 'Notify' WHEN fm.Warning=1 THEN 'Warning' ELSE 'Critical' END AS Subjectsufix,             
    null as Duration,             
    --(CASE WHEN SUBSTRING(h.SensorMask,6,1) = 1 THEN 'Trip Start' ELSE 'Trip End' END)             
    --+ ' - ' + fm.LandmarkName  as MessageDetails           
   (CASE WHEN h.BoxMsgInTypeId = 4 THEN m.BoxMsgInTypeDesc ELSE            
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId,MessageInID,OriginDateTime) END) + ' - ' + fm.LandmarkName  as MessageDetails            
   FROM rvlfMsgInHst h             
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId            
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId            
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId            
    INNER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID             
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId            
   /**************** Map to user preferences *******************/            
   INNER JOIN rvlfNotificationList n ON fm.LandmarkID = n.TypeID and n.NotificationType=2            
   INNER JOIN rvlfUser u ON n.UserID = u.UserId            
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId            
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID    
   
   /************************************************************** Based on Rights************/   
   INNER join rvlfUserGroupSecurity US on US.OperationTypeID = m.OperationTypeId
   INNER JOIN rvlfUserGroupAssignment UA on US.UserGroupId = UA.UserGroupId 
   and N.UserID = UA.UserId             
   /**************** Map to user preferences *******************/            
  WHERE h.MessageInID=@uimessageInID AND h.IsNotificationSent=0 and h.BoxMsgInTypeId not in (5,6,19,20,21,22,28,35,34,31,121)             
   and h.StreetAddress IS NOT NULL and (fm.Notify=1 OR fm.Warning=1 OR fm.Critical=1)            
   --AND (h.MessageInID in (SELECT StartMessageInID FROM rvlfTripDetails) OR h.MessageInID             
   -- in (SELECT EndMessageInID  FROM rvlfTripDetails) )            
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0            
   AND H.IsNotificationSent=0            
/**********************************************************************************************************************************************************/             
   END            
END TRY            
BEGIN CATCH              
END CATCH            
 --UPDATE rvlfMsgInHst SET IsNotificationSent = 1 WHERE MessageInID = @uimessageInID            
END 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_LogNotificaitons_ForAlarms]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_LogNotificaitons_ForAlarms]
	@msgIDLastPacket as DateTime =NULL,
	@uimessageInID as uniqueIdentifier =NULL,
	@tiBoxMsgInTypeId tinyint = NULL
AS
/****************************************************************************************************/
-- Name : rvlf_sp_LogNotificaitons_ForAlarms '9B784671-FE6D-E711-80C7-00219B712B2E','9B784671-FE6D-E711-80C7-00219B712B2E',24
-- Description : To get log the notificaitons of alarms.
-- Author : N,.Ranjith
-- Company : Trinetra Wireless
-- History : <<Date(dd-MON-yyyy)>> Initial Reason
-- : 13-Apr-2017 N.Ranjith Created initial version
/***************************************************************************************************/
	BEGIN
	
			
				--DISABLE THE SMS RIGHTS FOR EXPIRED ORG AND PACKAGE OPERATION.
				IF EXISTS (SELECT UserID FROM rvlfNotificationList WHERE SMS=1 AND UserID NOT IN (SELECT distinct NL.UserID FROM rvlfNotificationList NL INNER JOIN RVLFUSER U ON U.USERID=NL.UserID INNER JOIN rvlfOrganizationPackage OP ON OP.OrganizationID=U.OrganizationId AND OP.IsActive=1 INNER JOIN rvlfPackageOperations PO ON PO.PackageId=OP.PackageId AND PO.OperationID IN(136) WHERE NL.SMS=1 AND OP.ExpiresOn > GETUTCDATE()))
					BEGIN
						UPDATE rvlfNotificationList SET SMS=NULL WHERE SMS=1 AND UserID NOT IN
						(SELECT DISTINCT NL.UserID
						FROM rvlfNotificationList NL
						INNER JOIN RVLFUSER U ON U.USERID=NL.UserID
						INNER JOIN rvlfOrganizationPackage OP ON OP.OrganizationID=U.OrganizationId AND OP.IsActive=1
						INNER JOIN rvlfPackageOperations PO ON PO.PackageId=OP.PackageId AND PO.OperationID IN(136)
						WHERE NL.SMS=1 AND OP.ExpiresOn > GETUTCDATE())
					END

				DECLARE @bigOrgId AS BIGINT = 0
				DECLARE @inBoxId AS nvarchar(200) = '0'
				DECLARE @intSMSCount AS INT = 0
				DECLARE @tiMaxSMSLimit AS SMALLINT = NULL
				DECLARE @IsSMSsent bit=1
				DECLARE @intNoOfBoxes AS INT = 0
				DECLARE @intBoxSMSCount AS INT = 0
				DECLARE @bitSMSReached AS bit = 0
				DECLARE @SMSMessage VARCHAR(100) = NULL
				DECLARE @cVehicleDesc VARCHAR(45) = NULL
				Declare @CurDateTime DateTime
				IF (@msgIDLastPacket IS NOT NULL)
					BEGIN
						SET @CurDateTime = @msgIDLastPacket
					END

				declare @TypeOfdevice int=1
				SELECT @bigOrgId = v.OrganizationId,
				@cVehicleDesc=v.VehicleDescription,
				@inBoxId = h.BoxId,
				@tiMaxSMSLimit = ISNULL(o.MaxSMSLimit,0)
				FROM rvlfMsgInHst_Techno h
				INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId
				INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId
				INNER JOIN rvlfOrganization o ON o.OrganizationId = v.OrganizationId
				WHERE h.MessageInID = @uimessageInID
				if(@bigOrgId is null)
					begin
						set @TypeOfdevice=2
						SELECT @bigOrgId = v.OrganizationId,
						@cVehicleDesc=v.VehicleDescription,
						@inBoxId = h.BoxId,
						@tiMaxSMSLimit = ISNULL(o.MaxSMSLimit,0)
						FROM rvlfMsgInHst_Techno_355 h
						INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId
						INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId
						INNER JOIN rvlfOrganization o ON o.OrganizationId = v.OrganizationId
						WHERE h.MessageInID = @uimessageInID
					end
					
				--Select @bigOrgId,@cVehicleDesc,@inBoxId,@tiMaxSMSLimit --To Check the Data
				-- No of boxes in the Organization
				SELECT @intNoOfBoxes=COUNT(*) FROM dbo.rvlfBoxId WHERE OrganizationId=@bigOrgId
				--Get the total sms count for the Organization
				SELECT @intSMSCount = COUNT(MessageInID)
				FROM rvlfNotificationLog WHERE OrganizationID = @bigOrgId AND CanSendSMS = 1 AND SMSProcessedDate IS NOT NULL
				AND DATEPART(MONTH, OriginDateTime) = DATEPART(MONTH, GETUTCDATE())AND DATEPART(YEAR,OriginDateTime) = DATEPART(YEAR, GETUTCDATE()) AND IsSMSSent = 1
				--Get the box sms count for the BOXId in the Organization
				SELECT @intBoxSMSCount = COUNT(MessageInID)
				FROM rvlfNotificationLog WHERE OrganizationID = @bigOrgId AND BoxId=@inBoxId AND CanSendSMS = 1 AND SMSProcessedDate IS NOT NULL
				AND DATEPART(MONTH, OriginDateTime) = DATEPART(MONTH, GETUTCDATE()) AND DATEPART(YEAR,OriginDateTime) = DATEPART(YEAR, GETUTCDATE()) AND IsSMSSent = 1
				--Select @intNoOfBoxes as intNoOfBoxes,@intSMSCount as intSMSCount,@intBoxSMSCount as intBoxSMSCount
				IF (@intBoxSMSCount > @tiMaxSMSLimit)
					BEGIN
						IF (@intBoxSMSCount = (@tiMaxSMSLimit+1))
							BEGIN
								SET @bitSMSReached=1
								SET @SMSMessage = 'SMS Limit has been reached for '''+@cVehicleDesc+'''. Please contact administrator for activation'
							END
					END
				IF (@intSMSCount = ((@tiMaxSMSLimit*@intNoOfBoxes)-25))
					BEGIN
						SET @bitSMSReached=1
						SET @SMSMessage = 'SMS Limit to be reached.'
					END
				ELSE IF (@intSMSCount > (@tiMaxSMSLimit*@intNoOfBoxes))
					BEGIN
						SET @IsSMSsent=0
						IF (@intSMSCount = ((@tiMaxSMSLimit*@intNoOfBoxes)+1)) AND @bitSMSReached =0
							BEGIN
								SET @bitSMSReached=1
								SET @SMSMessage = 'SMS Limit has been reached. Please contact administrator for activation'
							END
					END
					
				--Check the same message "SMS Limit"
				DECLARE @checkMsgTempCount int = 0
				SELECT @checkMsgTempCount = COUNT(MessageInID)
				FROM rvlfNotificationLog WHERE OrganizationID = @bigOrgId AND BoxId=@inBoxId AND MessageDetails=@SMSMessage
				AND DATEPART(MONTH, OriginDateTime) = DATEPART(MONTH, GETUTCDATE()) AND DATEPART(YEAR,OriginDateTime) = DATEPART(YEAR, GETUTCDATE()) AND IsSMSSent = 1
				IF @checkMsgTempCount > 0
					BEGIN
						SET @IsSMSsent=0
					END
				IF @bitSMSReached = 1 AND ISNULL(@tiMaxSMSLimit,0) <> 0 AND @IsSMSsent=1
					BEGIN
						IF(@TypeOfdevice=1)
							begin
								INSERT INTO rvlfNotificationLog(
								[MessageInID],[OriginDateTime],[DateTimeReceived],[CanSendEmail],[IsMailSent],[CanSendSMS],[IsSMSSent],[UserID],[OrganizationID],[UserName],[Email],[MobileNo],[StreetAddress],
								[Speed],[BoxId],[BoxMsgInTypeName],[VehicleID],[VehicleDescription],[VehicleName],[FleetID],[FleetName],[LicensePlate],[Subjectsufix],[Duration],[MessageDetails])
								SELECT h.MessageInID,h.OriginDateTime,h.DateTimeReceived,1 AS CanSendEmail,0 AS IsMailSent,1 AS CanSendSMS,0 AS IsSMSSent,u.UserId,v.OrganizationId,u.DisplayName,u.Email,u.MobileNo,h.StreetAddress,
								'0.00 MPH' AS Speed,h.BoxId,m.BoxMsgInTypeDesc,MD.VehicleId,v.VehicleDescription,v.VehicleDescription,--f.FleetId,f.FleetName,
								ISNULL((SELECT FleetId FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From rvlfFleetVehicles Where VehicleId = V.VehicleId and FleetId <> 176)), '-') as FleetId,
								ISNULL((SELECT FleetName FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From rvlfFleetVehicles Where VehicleId = V.VehicleId and FleetId <> 176)), '-') as FleetName,
								v.LicensePlate,'Notify' AS Subjectsufix,NULL AS Duration,@SMSMessage
								FROM rvlfMsgInHst_Techno h
								INNER JOIN rvlfBoxMsgInType m ON m.BoxMsgInTypeId=h.BoxMsgInTypeId
								INNER JOIN rvlfMAKDevices MD ON h.BoxId = MD.BoxId
								--INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId
								--INNER JOIN rvlfBoxId B ON B.BoxId=va.BoxId
								--INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId
								INNER JOIN rvlfBoxId B ON B.BoxId=MD.BoxId
								INNER JOIN rvlfVehicle v ON v.VehicleId=MD.VehicleId
								INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
								INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId
								INNER JOIN rvlfUser u ON u.OrganizationId=v.OrganizationId
								WHERE f.FleetId = (SELECT TOP 1 FleetId From rvlfFleet WHERE OrganizationId=B.OrganizationId ORDER BY FleetId ASC) AND u.UserId IN (SELECT TOP 1 UserId FROM rvlfUser WHERE OrganizationId=B.OrganizationId AND UserName like '%Admin%')
								AND h.MessageInID = @uimessageInID -- and v.OrganizationId = 86
							end
						else
							begin
								INSERT INTO rvlfNotificationLog(
								[MessageInID],[OriginDateTime],[DateTimeReceived],[CanSendEmail],[IsMailSent],[CanSendSMS],[IsSMSSent],[UserID],[OrganizationID],[UserName],[Email],[MobileNo],[StreetAddress],
								[Speed],[BoxId],[BoxMsgInTypeName],[VehicleID],[VehicleDescription],[VehicleName],[FleetID],[FleetName],[LicensePlate],[Subjectsufix],[Duration],[MessageDetails])
								SELECT h.MessageInID,h.OriginDateTime,h.DateTimeReceived,1 AS CanSendEmail,0 AS IsMailSent,1 AS CanSendSMS,0 AS IsSMSSent,u.UserId,v.OrganizationId,u.DisplayName,u.Email,u.MobileNo,h.StreetAddress,
								'0.00 MPH' AS Speed,h.BoxId,m.BoxMsgInTypeDesc,MD.VehicleId,v.VehicleDescription,v.VehicleDescription,--f.FleetId,f.FleetName,
								ISNULL((SELECT FleetId FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From rvlfFleetVehicles Where VehicleId = V.VehicleId and FleetId <> 176)), '-') as FleetId,
								ISNULL((SELECT FleetName FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From rvlfFleetVehicles Where VehicleId = V.VehicleId and FleetId <> 176)), '-') as FleetName,
								v.LicensePlate,'Notify' AS Subjectsufix,NULL AS Duration,@SMSMessage
								FROM rvlfMsgInHst_Techno_355 h
								INNER JOIN rvlfBoxMsgInType m ON m.BoxMsgInTypeId=h.BoxMsgInTypeId
								INNER JOIN rvlfMAKDevices MD ON h.BoxId = MD.BoxId
								--INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId
								--INNER JOIN rvlfBoxId B ON B.BoxId=va.BoxId
								--INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId
								INNER JOIN rvlfBoxId B ON B.BoxId=MD.BoxId
								INNER JOIN rvlfVehicle v ON v.VehicleId=MD.VehicleId
								INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId
								INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId
								INNER JOIN rvlfUser u ON u.OrganizationId=v.OrganizationId
								WHERE f.FleetId = (SELECT TOP 1 FleetId From rvlfFleet WHERE OrganizationId=B.OrganizationId ORDER BY FleetId ASC) AND u.UserId IN (SELECT TOP 1 UserId FROM rvlfUser WHERE OrganizationId=B.OrganizationId AND UserName like '%Admin%')
								AND h.MessageInID = @uimessageInID -- and v.OrganizationId = 86
							end
					END
					BEGIN
						--Select * from rvlfAlarm A
						-- where A.[Description] not in (Select B.[Description] from rvlfAlarm B where B.MessageInID = @msgIDLastPacket)
						-- and A.MessageInID = @uimessageInID
						--select MessageInID,[Description] from rvlfAlarm where MessageInID = @uimessageInID
						IF(@TypeOfdevice=1)
							begin
								INSERT INTO rvlfNotificationLog
								([MessageInID],[OriginDateTime],[DateTimeReceived],[CanSendEmail],[IsMailSent],[CanSendSMS],[IsSMSSent],[UserID],[OrganizationID],[UserName],[Email],[MobileNo],[StreetAddress],
								[Speed],[BoxId],[BoxMsgInTypeName],[VehicleID],[VehicleDescription],[VehicleName],[FleetID],[FleetName],[LicensePlate],[Subjectsufix],[Duration],[MessageDetails])
								select Distinct h.MessageInID,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,
								ISNULL(n.Email,0) as CanSendEmail,CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent,
								CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent,u.UserId,u.OrganizationId,u.UserName,u.Email as Email,u.MobileNo,
								Null AS StreetAddress, Null as Speed,
								h.BoxId,m.BoxMsgInTypeName,v.VehicleId,v.VehicleDescription,v.VehicleDescription as VehicleName,
								ISNULL((SELECT FleetId FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From rvlfFleetVehicles Where VehicleId = V.VehicleId and FleetId <> 176)), '-') as FleetId,
								ISNULL((SELECT FleetName FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From rvlfFleetVehicles Where VehicleId = V.VehicleId and FleetId <> 176)), '-') as FleetName,
								v.LicensePlate, S.AlarmLevelName as Subjectsufix, (case WHEN (A.IsClosed IS NULL OR A.IsClosed = 0) Then 'Open' Else 'Closed' END) AS Duration,A.Description as MessageDetails
								FROM rvlfMsgInHst_Techno h
								--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
								INNER JOIN rvlfMAKDevices MD ON h.BoxId = MD.BoxId
								INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId
								INNER JOIN rvlfAlarm A on A.MessageInID = h.MessageInID --and A.AlarmRepeatFlag = 1
								--INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId and V.OrganizationId in (6,86)
								INNER JOIN rvlfVehicle v ON MD.VehicleId = v.VehicleId and V.OrganizationId in (6,86)
								INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4
								INNER JOIN rvlfUser u ON n.UserID = u.UserId and u.OrganizationId in (1,6,86,132)
								INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId
								INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID
								INNER JOIN rvlfSeverity s ON A.AlarmLevelID = s.AlarmLevelId
								INNER join rvlfUserGroupSecurity US on US.OperationTypeID = m.OperationTypeId
								INNER JOIN rvlfUserGroupAssignment UA on US.UserGroupId = UA.UserGroupId and N.UserID = UA.UserId
								--WHERE h.MessageInID IN(@uimessageInID) AND h.IsNotificationSent=0 and h.BoxMsgInTypeId in (4,24)
								WHERE --h.IsNotificationSent=0 and h.BoxMsgInTypeId in (4,24) AND
								h.MessageInID IN(CASE WHEN @uimessageInID IS NULL THEN (Select MessageInID from rvlfAlarm where IsClosed=1 AND DateTimeClosed = @CurDateTime) ELSE @uimessageInID END)
																AND (case when
								(case when V.Notify='true' then 'Information' else '' end +
								case when v.Warning='true' then 'Warning' else '' end +
								case when v.ElecTripAlert='true' then 'Electrical Trip' else '' end + 
								case when v.ShutdownAlert='true' then 'Shutdown' else '' end)='' then 'No Alarm' else
							(case when v.Notify='true' then (case when (v.Warning='true' or v.ElecTripAlert='true'or v.ShutdownAlert='true') then 'Information;' else 'Information' end ) else '' end +
							case when v.Warning='true' then (case when (v.ElecTripAlert='true' or v.ShutdownAlert='true') then 'Warning;' else 'Warning' end) else '' end +
								case when v.ElecTripAlert='true' then  (case when v.ShutdownAlert='true' then 'Electrical Trip;' else 'Electrical Trip' end) else '' end + 
								case when v.ShutdownAlert='true' then  'Shutdown' else '' end)
								end LIKE '%'+s.AlarmLevelName +'%')
								AND s.CanSendNotification = 1 AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0
							end
						else
							begin
								INSERT INTO rvlfNotificationLog
								([MessageInID],[OriginDateTime],[DateTimeReceived],[CanSendEmail],[IsMailSent],[CanSendSMS],[IsSMSSent],[UserID],[OrganizationID],[UserName],[Email],[MobileNo],[StreetAddress],
								[Speed],[BoxId],[BoxMsgInTypeName],[VehicleID],[VehicleDescription],[VehicleName],[FleetID],[FleetName],[LicensePlate],[Subjectsufix],[Duration],[MessageDetails])
								select Distinct h.MessageInID,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,
								ISNULL(n.Email,0) as CanSendEmail,CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent,
								CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent,u.UserId,u.OrganizationId,u.UserName,u.Email as Email,u.MobileNo,
								Null AS StreetAddress, Null as Speed,
								h.BoxId,m.BoxMsgInTypeName,v.VehicleId,v.VehicleDescription,v.VehicleDescription as VehicleName,
								ISNULL((SELECT FleetId FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From rvlfFleetVehicles Where VehicleId = V.VehicleId and FleetId <> 176)), '-') as FleetId,
								ISNULL((SELECT FleetName FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From rvlfFleetVehicles Where VehicleId = V.VehicleId and FleetId <> 176)), '-') as FleetName,
								v.LicensePlate, S.AlarmLevelName as Subjectsufix, (case WHEN (A.IsClosed IS NULL OR A.IsClosed = 0) Then 'Open' Else 'Closed' END) AS Duration,A.Description as MessageDetails
								FROM rvlfMsgInHst_Techno_355 h
								--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
								INNER JOIN rvlfMAKDevices MD ON h.BoxId = MD.BoxId
								INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId
								INNER JOIN rvlfAlarm A on A.MessageInID = h.MessageInID --and A.AlarmRepeatFlag = 1
								--INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId and V.OrganizationId in (6,86)
								INNER JOIN rvlfVehicle v ON MD.VehicleId = v.VehicleId and V.OrganizationId in (6,86)
								INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4
								INNER JOIN rvlfUser u ON n.UserID = u.UserId and u.OrganizationId in (1,6,86,132)
								INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId
								INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID
								INNER JOIN rvlfSeverity s ON A.AlarmLevelID = s.AlarmLevelId
								INNER join rvlfUserGroupSecurity US on US.OperationTypeID = m.OperationTypeId
								INNER JOIN rvlfUserGroupAssignment UA on US.UserGroupId = UA.UserGroupId and N.UserID = UA.UserId
								--WHERE h.MessageInID IN(@uimessageInID) AND h.IsNotificationSent=0 and h.BoxMsgInTypeId in (4,24)
								WHERE --h.IsNotificationSent=0 and h.BoxMsgInTypeId in (4,24) AND
								h.MessageInID IN(CASE WHEN @uimessageInID IS NULL THEN (Select MessageInID from rvlfAlarm where IsClosed=1 AND DateTimeClosed = @CurDateTime) ELSE @uimessageInID END)
								AND (case when
								(case when V.Notify='true' then 'Information' else '' end +
								case when v.Warning='true' then 'Warning' else '' end +
								case when v.ElecTripAlert='true' then 'Electrical Trip' else '' end + 
								case when v.ShutdownAlert='true' then 'Shutdown' else '' end)='' then 'No Alarm' else
							(case when v.Notify='true' then (case when (v.Warning='true' or v.ElecTripAlert='true'or v.ShutdownAlert='true') then 'Information;' else 'Information' end ) else '' end +
							case when v.Warning='true' then (case when (v.ElecTripAlert='true' or v.ShutdownAlert='true') then 'Warning;' else 'Warning' end) else '' end +
								case when v.ElecTripAlert='true' then  (case when v.ShutdownAlert='true' then 'Electrical Trip;' else 'Electrical Trip' end) else '' end + 
								case when v.ShutdownAlert='true' then  'Shutdown' else '' end)
								end LIKE '%'+s.AlarmLevelName +'%')
								AND s.CanSendNotification = 1 AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0
							end
					END
			
		--UPDATE rvlfMsgInHst SET IsNotificationSent = 1 WHERE MessageInID = @uimessageInID
	END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_LogNotificaitons_Old]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_LogNotificaitons_Old]  
 @uimessageInID as uniqueIdentifier,  
 @tiBoxMsgInTypeId tinyint = null  
AS  
/****************************************************************************************************/  
-- Name  : rvlf_sp_LogNotificaitons  
-- Description : To get log the notificaitons.  
-- Author  : M. Jebamalai Jaya Chitra  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--			: 17-Nov-2009 MJJC Created initial version  
--			: 25-Jan-2010 MJJC To update the alarm details function parameters  
--			: 19-Jun-2010 MJJC Included a check for the duration when   
--			: 30-Jun-2010 Kumu Changed the logging of Sensor Name  
--			: 19-Aug-2010 Kumu Removed the Vehicle Display Name  
--          : 13-Dec-2010 Kumu Blocked the SMS for Org. US Embassy  
--          : 20-Dec-2010 Kumu Unblocked the SMS for Org. US Embassy and   
--            checked SMS Count for the current date for each Box Id  
--			: 30-Dec-2010 VN Restrict the users if the user is deleted.  
--			: 07-Apr-2011 LK Removed the Street Address checking for Geozone level notification
--			: VN --DISABLE THE SMS RIGHTS FOR EXPIRED ORG AND PACKAGE OPERATION.  
--			: 13-Oct-2011 Restrict the SMS, based on Mas SMS Limit by BoxId - Sakthi
/***************************************************************************************************/  
BEGIN   
 BEGIN TRY  
 
	--DISABLE THE SMS RIGHTS FOR EXPIRED ORG AND PACKAGE OPERATION.
	IF EXISTS(SELECT UserID  FROM rvlfNotificationList WHERE SMS=1 AND
		UserID NOT IN(SELECT NL.UserID FROM rvlfNotificationList NL
		INNER JOIN RVLFUSER U ON U.USERID=NL.UserID 
		INNER JOIN rvlfOrganizationPackage OP ON OP.OrganizationID=U.OrganizationId  AND OP.IsActive=1
		INNER JOIN rvlfPackageOperations PO ON PO.PackageId=OP.PackageId AND PO.OperationID IN(136)
		WHERE SMS=1 AND OP.ExpiresOn>GETUTCDATE()))
		BEGIN
			UPDATE rvlfNotificationList SET SMS=NULL WHERE SMS=1 AND
				UserID NOT IN(SELECT NL.UserID FROM rvlfNotificationList NL
				INNER JOIN RVLFUSER U ON U.USERID=NL.UserID 
				INNER JOIN rvlfOrganizationPackage OP ON OP.OrganizationID=U.OrganizationId  AND OP.IsActive=1
				INNER JOIN rvlfPackageOperations PO ON PO.PackageId=OP.PackageId AND PO.OperationID IN(136)
				WHERE SMS=1 AND OP.ExpiresOn>GETUTCDATE())
		END
   
    DECLARE @bigOrgId AS BIGINT = 0  
    DECLARE @inBoxId AS INT = 0  
    DECLARE @intSMSCount AS INT = 0  
    DECLARE @tiMaxSMSLimit AS TINYINT = NULL  
    DECLARE @IsSMSsent bit=1    
      
    SELECT @bigOrgId = v.OrganizationId, @inBoxId = h.BoxId, @tiMaxSMSLimit = o.MaxSMSLimit FROM rvlfMsgInHst h   
    INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId  
    INNER JOIN rvlfVehicle v ON v.VehicleId = va.VehicleId  
    INNER JOIN rvlfOrganization o ON o.OrganizationId = v.OrganizationId
    WHERE h.MessageInID = @uimessageInID  
      
    SELECT @intSMSCount = COUNT(MessageInID) FROM rvlfNotificationLog WHERE OrganizationID = @bigOrgId AND CanSendSMS = 1     
    AND SMSProcessedDate IS NOT NULL AND DATEPART(MONTH, OriginDateTime) = DATEPART(MONTH, GETUTCDATE())    
   AND  DATEPART(YEAR,OriginDateTime) = DATEPART(YEAR, GETUTCDATE())    
   AND IsSMSSent  = 1  
   
   --DISABLE THE SMS FOR NCM ORGANIZATION 
   IF @bigOrgId=96
		SET @IsSMSsent =0
		
 IF (@intSMSCount > @tiMaxSMSLimit)  
  SET @IsSMSsent=0  
    
    BEGIN  
  IF (@tiBoxMsgInTypeId = 2 OR @tiBoxMsgInTypeId = 3)  
   BEGIN  
    DECLARE @tiSensorNo tinyint  
    DECLARE @tiSensorStatus tinyint  
    DECLARE @intBoxID int  
    DECLARE @bitAction bit  
    DECLARE @intAlarmLevel int  
     
    SELECT @intBoxID=h.BoxId, @tiSensorNo = CASE WHEN BoxMsgInTypeId = 2   
    THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,  
     CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END ,  
     @bitAction = 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,   
     @tiBoxMsgInTypeId = BoxMsgInTypeId , @intAlarmLevel = e.AlarmLevelId   
     FROM rvlfMsgInHst h  
     LEFT OUTER JOIN rvlfBoxSensorsCfg s ON s.BoxId= h.BoxId and   
      s.SensorId = CASE WHEN BoxMsgInTypeId = 2 OR BoxMsgInTypeId = 3  
       THEN CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,  
        CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) ELSE 0 END  
     INNER JOIN rvlfSeverity e ON e.AlarmLevelId  = CASE WHEN BoxMsgInTypeId=2 OR BoxMsgInTypeId = 3 THEN CAST( CASE WHEN (SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,  
     CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1)) = 'ON' THEN s.AlarmLevelOn ELSE s.AlarmLevelOff END as int)  
     ELSE 0 END  
     where MessageInID= @uimessageInID  
      
    select @intBoxID, @tiSensorNo, @bitAction, @tiBoxMsgInTypeId, @intAlarmLevel     
 IF (@tiBoxMsgInTypeId = 2 OR @tiBoxMsgInTypeId = 3) AND @intAlarmLevel !=4    
     BEGIN        
      /* Vehicle Level Notification for Sensors*/    
      INSERT INTO rvlfNotificationLog     
      (    
       [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,     
       [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,     
       [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],    
       [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,     
       [Subjectsufix] , [Duration] , [MessageDetails]     
      )    
      SELECT h.MessageInID,     
       DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,     
       DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,     
       ISNULL(n.Email,0) as CanSendEmail,     
       CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,     
          -- Blocked the SMS for Org US Embassy 52 CASE WHEN v.OrganizationId = 52 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS,    
       CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,     
       u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,    
       CASE WHEN h.StreetAddress like 'Address Not Found' THEN     
         '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+    
         cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'    
        WHEN h.ValidGps = 0 THEN     
         h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )    
         +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'    
        ELSE h.StreetAddress END AS StreetAddress,    
       CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +     
       CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,    
       h.BoxId, m.BoxMsgInTypeDesc, v.VehicleId, v.VehicleDescription,    
        v.VehicleDescription  as VehicleName, null, null,    
       v.LicensePlate, S.AlarmLevelName  as Subjectsufix, null as Duration,     
       dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId, h.MessageInID, h.OriginDateTime) As MessageDetail    
      FROM rvlfMsgInHst h     
       INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId    
       INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId    
       INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId    
       LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID     
       INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId    
    INNER JOIN rvlfSeverity S ON S.AlarmLevelId=@intAlarmLevel  
       /**************** Map to user preferences *******************/    
       INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4    
       INNER JOIN rvlfUser u ON n.UserID = u.UserId    
       INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId    
       INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID    
       /**************** Map to user preferences *******************/    
      WHERE h.MessageInID=@uimessageInID /*AND IsNotificationSent = 0 and h.BoxMsgInTypeId = 11 in (2,3)*/ and h.StreetAddress IS NOT NULL    
       AND v.Notify != 4 AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0    
       AND H.IsNotificationSent=0    
       AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity    
        WHERE ModuleId = 26 and UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))    
            
          
      /* Fleet Level Notification for Sensors*/     
      INSERT INTO rvlfNotificationLog     
       (    
        [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,     
        [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,     
        [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],    
        [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,     
        [Subjectsufix] , [Duration] , [MessageDetails]     
       )    
      SELECT h.MessageInID,     
       DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,     
       DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,     
       ISNULL(n.Email,0) as CanSendEmail,     
       CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,     
        -- Blocked the SMS for Org US Embassy 52    
    CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,     
       u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,    
       CASE WHEN h.StreetAddress like 'Address Not Found' THEN     
         '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+    
         cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'    
        WHEN h.ValidGps = 0 THEN     
         h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )    
         +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'    
        ELSE h.StreetAddress END AS StreetAddress,    
       CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +     
       CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,    
       h.BoxId, m.BoxMsgInTypeDesc, v.VehicleId, v.VehicleDescription,    
        v.VehicleDescription  as VehicleName, null, null,    
       v.LicensePlate, 'Notify' as Subjectsufix, null as Duration,     
       dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId, h.MessageInID, h.OriginDateTime) As MessageDetail    
      FROM rvlfMsgInHst h     
       INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId    
       INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId    
       INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId    
       LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID     
       INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId    
       /**************** Map to user preferences *******************/    
       INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId    
       INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId    
       INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3    
       INNER JOIN rvlfUser u ON n.UserID = u.UserId    
       INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId    
       INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID    
       /**************** Map to user preferences *******************/    
      WHERE h.MessageInID=@uimessageInID   
       AND f.Notify !=4            
       AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0    
       AND H.IsNotificationSent=0          
       AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity           
       WHERE ModuleId = 26 and UserGroupId IN     
       (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))    
     END    
 END  
   
 /**********************************************************************************/  
 /**************************** Vehicle Level Notification ****************************/  
 /**********************************************************************************/  
 /**************************** Based on Tampering ****************************/  
  INSERT INTO rvlfNotificationLog   
   (  
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,   
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,   
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],  
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,   
    [Subjectsufix] , [Duration] , [MessageDetails]   
   )  
  SELECT h.MessageInID,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
    ISNULL(n.Email,0) as CanSendEmail,   
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,   
     -- Blocked the SMS for Org US Embassy 52  
    CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,     
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,  
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     WHEN h.ValidGps = 0 THEN   
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     ELSE h.StreetAddress END AS StreetAddress,  
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
    h.BoxId, m.BoxMsgInTypeDesc, v.VehicleId, v.VehicleDescription,  
     v.VehicleDescription  as VehicleName, null, null,  
    v.LicensePlate, 'Critical' as Subjectsufix, null as Duration,   
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId, h.MessageInID, h.OriginDateTime) As MessageDetails  
  FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
       
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
     
  WHERE h.MessageInID=@uimessageInID AND IsNotificationSent = 0 and h.BoxMsgInTypeId = 11 /*in (2,3)*/ and h.StreetAddress IS NOT NULL  
   AND (case when  
    (case when v.Notify='true' then 'Notify' else '' end +      
    case when v.Warning='true' then 'Warning' else '' end +   
    case when v.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
    (case  when v.Notify='true' then (case when (v.Warning='true' or v.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +      
    case when v.Warning='true' then (case when v.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +   
    case when v.Critical='true' then 'Critical' else '' end)  
    end LIKE '%Critical%')   
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0  
   AND H.IsNotificationSent=0  
   AND dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId, h.MessageInID, h.OriginDateTime) = 'Tamper'  
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity  
   WHERE ModuleId = 26 and UserGroupId IN   
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))  
     
 /**************************** Based on Box Message Severity ****************************/  
  INSERT INTO rvlfNotificationLog   
   (  
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,   
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,   
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],  
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,   
    [Subjectsufix] , [Duration] , [MessageDetails]   
   )  
  SELECT * FROM (  
  SELECT h.MessageInID,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
    ISNULL(n.Email,0) as CanSendEmail,   
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,   
     -- Blocked the SMS for Org US Embassy 52  
    CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,     
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,  
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     WHEN h.ValidGps = 0 THEN   
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     ELSE h.StreetAddress END AS StreetAddress,  
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
    h.BoxId, m.BoxMsgInTypeDesc, v.VehicleId, v.VehicleDescription,  
    --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'   
     --ELSE v.VehicleDescription END   
      v.VehicleDescription as VehicleName, null as FleetID, null as FleetName,  
    v.LicensePlate, s.AlarmLevelName as Subjectsufix,  
    CASE WHEN m.BoxMsgInTypeDesc<>'Sensor'   
     THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN   
      SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,  
      CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END as Duration,   
    CASE WHEN h.BoxMsgInTypeId = 4 THEN m.BoxMsgInTypeDesc + ' ' +  
      CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
      CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END  
     ELSE dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails  
   FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfBoxMsgSeverity ms ON h.BoxId = ms.BoxId and ms.BoxMsgInTypeId = h.BoxMsgInTypeId  
   INNER JOIN rvlfSeverity s ON ms.AlarmLevelID = s.AlarmLevelId   
     
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
  WHERE h.MessageInID=@uimessageInID AND h.IsNotificationSent=0 and h.StreetAddress IS NOT NULL and s.CanSendNotification = 1 and h.BoxMsgInTypeId not in (5,6,2,3)  
   AND  ( case when  
   (case when v.Notify='true' then 'Notify' else '' end +      
   case when v.Warning='true' then 'Warning' else '' end +   
   case when v.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
   (case  when v.Notify='true' then (case when (v.Warning='true' or v.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +      
   case when v.Warning='true' then (case when v.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +   
   case when v.Critical='true' then 'Critical' else '' end)  
   end LIKE '%'+s.AlarmLevelName +'%') AND s.CanSendNotification = 1  
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0  
   AND H.IsNotificationSent=0  
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity  
   WHERE ModuleId = 26 and UserGroupId IN   
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))  
  ) as a WHERE (Duration is null or Duration > 0)  
 /**************************** Based on Default Severity ****************************/     
  INSERT INTO rvlfNotificationLog   
   (  
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,   
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,   
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],  
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,   
    [Subjectsufix] , [Duration] , [MessageDetails]   
   )  
   SELECT * FROM (  
   SELECT h.MessageInID,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
    ISNULL(n.Email,0) as CanSendEmail,   
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,   
     -- Blocked the SMS for Org US Embassy 52  
    CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,     
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,  
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     WHEN h.ValidGps = 0 THEN   
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     ELSE h.StreetAddress END AS StreetAddress,  
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
    h.BoxId, m.BoxMsgInTypeDesc, v.VehicleId, v.VehicleDescription,  
    --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'   
     --ELSE v.VehicleDescription END   
     v.VehicleDescription  as VehicleName, null as FleetID, null as FleetName,  
    v.LicensePlate, s.AlarmLevelName as Subjectsufix,  
    CASE WHEN m.BoxMsgInTypeDesc<>'Sensor'   
     THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN   
      SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,  
      CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END as Duration,   
    CASE WHEN h.BoxMsgInTypeId = 4 THEN m.BoxMsgInTypeDesc + ' ' +  
      CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
      CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END  
     ELSE dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails  
   FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfBoxProtocolMsgInType ms ON h.BoxMsgInTypeId = ms.BoxMsgInTypeId  
   INNER JOIN rvlfSeverity s ON ms.DefaultAlarmLevel = s.AlarmLevelId   
     
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
     
  WHERE h.MessageInID=@uimessageInID AND h.IsNotificationSent=0  and h.StreetAddress IS NOT NULL  and h.StreetAddress IS NOT NULL and s.CanSendNotification = 1 and h.BoxMsgInTypeId not in (5,6,2,3)  
   AND  ( case when  
   (case when v.Notify='true' then 'Notify' else '' end +      
   case when v.Warning='true' then 'Warning' else '' end +   
   case when v.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
   (case  when v.Notify='true' then (case when (v.Warning='true' or v.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +      
   case when v.Warning='true' then (case when v.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +   
   case when v.Critical='true' then 'Critical' else '' end)  
   end LIKE '%'+s.AlarmLevelName +'%') AND h.BoxMsgInTypeId NOT IN   
    (SELECT BoxMsgInTypeId  FROM rvlfBoxMsgSeverity bms WHERE bms.BoxId = h.BoxId ) AND s.CanSendNotification = 1  
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0  
   AND H.IsNotificationSent=0  
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity  
   WHERE ModuleId = 26 and UserGroupId IN   
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))  
         ) as a Where (Duration is null or Duration > 0)  
    /**************************** Based on Sensor Severity ****************************/  
  INSERT INTO rvlfNotificationLog   
   (  
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,   
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,   
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],  
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,   
    [Subjectsufix] , [Duration] , [MessageDetails]   
   )  
   SELECT h.MessageInID,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
    ISNULL(n.Email,0) as CanSendEmail,   
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,   
     -- Blocked the SMS for Org US Embassy 52  
    CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,     
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,  
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     WHEN h.ValidGps = 0 THEN   
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     ELSE h.StreetAddress END AS StreetAddress,  
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
    h.BoxId, m.BoxMsgInTypeDesc, v.VehicleId, v.VehicleDescription,  
    --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'   
     --ELSE v.VehicleDescription END   
     v.VehicleDescription  as VehicleName, null, null,  
    v.LicensePlate, s.AlarmLevelName as Subjectsufix, null as Duration,   
    --rs.SensorName+' '+SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,   
    --CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1) As MessageDetails  
    rs.SensorName + ' ' + CASE WHEN SUBSTRING(CustomProp,CHARINDEX('SENSOR_STATUS=',CustomProp,0)+14,  
   (CHARINDEX(';',CustomProp,(CHARINDEX('SENSOR_STATUS=',CustomProp,0)))-(CHARINDEX('SENSOR_STATUS=',CustomProp,0)+14))) = 'ON'   
    THEN rs.ActionOn ELSE rs.ActionOff END AS MessageDetails  
  FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfSensor rs ON  CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,  
    CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) = rs.SensorId  
   INNER JOIN rvlfBoxSensorsCfg bs ON bs.SensorId = rs.SensorId AND h.BoxId = bs.BoxId  
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfSeverity s ON s.AlarmLevelId =  
    --(CASE WHEN SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,  
    -- CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1)   
    -- IN ('OPEN','ON','NORMAL','OK')  
    -- THEN bs.AlarmLevelOn ELSE bs.AlarmLevelOff END)  
    (CASE WHEN SUBSTRING(CustomProp,CHARINDEX('SENSOR_STATUS=',CustomProp,0)+14,  
     (CHARINDEX(';',CustomProp,(CHARINDEX('SENSOR_STATUS=',CustomProp,0)))-(CHARINDEX('SENSOR_STATUS=',CustomProp,0)+14)))               
      IN ('OPEN','ON','NORMAL','OK')    
      THEN bs.AlarmLevelOn ELSE bs.AlarmLevelOff END)  
       
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON v.VehicleId = n.TypeID and n.NotificationType=4  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
     
  WHERE h.MessageInID=@uimessageInID AND h.BoxMsgInTypeId = 11 /*in (2,3)*/ AND h.IsNotificationSent = 0 and h.StreetAddress IS NOT NULL  
   AND (case when  
    (case when v.Notify='true' then 'Notify' else '' end +      
    case when v.Warning='true' then 'Warning' else '' end +   
    case when v.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
    (case  when v.Notify='true' then (case when (v.Warning='true' or v.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +      
    case when v.Warning='true' then (case when v.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +   
    case when v.Critical='true' then 'Critical' else '' end)  
    end LIKE '%'+s.AlarmLevelName +'%') AND s.CanSendNotification = 1  
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0  
   AND H.IsNotificationSent=0  
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity  
   WHERE ModuleId = 26 and UserGroupId IN   
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))  
 /**********************************************************************************/  
  
 /**********************************************************************************/  
 /**************************** Fleet Level Notification ****************************/  
 /**********************************************************************************/  
   
  /**************************** Based on Tampering ****************************/  
  INSERT INTO rvlfNotificationLog   
   (  
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,   
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,   
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],  
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,   
    [Subjectsufix] , [Duration] , [MessageDetails]   
   )  
  SELECT h.MessageInID,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
    ISNULL(n.Email,0) as CanSendEmail,   
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,   
     -- Blocked the SMS for Org US Embassy 52  
    CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,     
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,  
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     WHEN h.ValidGps = 0 THEN   
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     ELSE h.StreetAddress END AS StreetAddress,  
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
    h.BoxId, m.BoxMsgInTypeDesc, v.VehicleId, v.VehicleDescription,  
    --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'   
     --ELSE v.VehicleDescription END   
       v.VehicleDescription as VehicleName, f.FleetId , f.FleetName,  
    v.LicensePlate, 'Critical' as Subjectsufix, null as Duration,   
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId, h.MessageInID, h.OriginDateTime) As MessageDetails  
  FROM rvlfMsgInHst h   
    
    INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
    INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
    INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
    LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
    INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
    INNER JOIN rvlfFleet f On fv.FleetId = f.FleetID  
     
       
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
     
  WHERE h.MessageInID=@uimessageInID AND IsNotificationSent = 0 and h.BoxMsgInTypeId = 11 /*in (2,3)*/ and h.StreetAddress IS NOT NULL  
   AND (case when  
    (case when f.Notify='true' then 'Notify' else '' end +      
    case when f.Warning='true' then 'Warning' else '' end +   
    case when f.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
    (case  when f.Notify='true' then (case when (f.Warning='true' or f.Critical='true')  
     then 'Notify;' else 'Notify' end ) else '' end +      
    case when f.Warning='true' then (case when f.Critical='true' then 'Warning;'   
    else 'Warning' end ) else '' end +   
    case when f.Critical='true' then 'Critical' else '' end)  
    end LIKE '%Critical%')   
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0  
   AND H.IsNotificationSent=0  
   AND dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.BoxMsgInTypeId, h.BoxId, h.MessageInID, h.OriginDateTime) = 'Tamper'  
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity  
   WHERE ModuleId = 26 and UserGroupId IN   
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))  
     
  /**************************** Based on Box Message Severity ****************************/  
   INSERT INTO rvlfNotificationLog   
    (  
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,   
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,   
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],  
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,   
    [Subjectsufix] , [Duration] , [MessageDetails]   
   )  
   SELECT * FROM (SELECT h.MessageInID,   
     DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
     DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
     ISNULL(n.Email,0) as CanSendEmail,   
     CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,   
      -- Blocked the SMS for Org US Embassy 52  
     CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,     
     u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,  
     CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
       '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
       cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
      WHEN h.ValidGps = 0 THEN   
       h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
       +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
      ELSE h.StreetAddress END AS StreetAddress,  
     CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
     CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
     h.BoxId, m.BoxMsgInTypeDesc, v.VehicleId, v.VehicleDescription,  
     --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'   
      --ELSE v.VehicleDescription END   
       v.VehicleDescription as VehicleName, f.FleetId, f.FleetName,  
     v.LicensePlate, s.AlarmLevelName as Subjectsufix,  
     CASE WHEN m.BoxMsgInTypeDesc<>'Sensor'   
      THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN   
       SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,  
       CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END as Duration,   
    CASE WHEN h.BoxMsgInTypeId = 4 THEN m.BoxMsgInTypeDesc + ' ' +  
      CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
      CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END  
      ELSE dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails  
   from rvlfMsgInHst h   
    INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
    INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
    INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
    LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
    INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
    INNER JOIN rvlfFleet f On fv.FleetId = f.FleetId  
    INNER JOIN rvlfBoxMsgSeverity ms ON h.BoxId = ms.BoxId and ms.BoxMsgInTypeId = h.BoxMsgInTypeId  
    INNER JOIN rvlfSeverity s ON ms.AlarmLevelID = s.AlarmLevelId   
      
    /**************** Map to user preferences *******************/  
    INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3  
    INNER JOIN rvlfUser u ON n.UserID = u.UserId  
    INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
    INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
    /**************** Map to user preferences *******************/  
      
   WHERE h.MessageInID=@uimessageInID AND h.IsNotificationSent=0  and h.StreetAddress IS NOT NULL  and h.StreetAddress IS NOT NULL and s.CanSendNotification = 1 and h.BoxMsgInTypeId not in (5,6,2,3)  
    AND  ( case when  
     (case when f.Notify='true' then 'Notify' else '' end +      
     case when f.Warning='true' then 'Warning' else '' end +   
     case when f.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
     (case  when f.Notify='true' then (case when (f.Warning='true' or f.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +      
     case when f.Warning='true' then (case when f.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +   
     case when f.Critical='true' then 'Critical' else '' end)  
     end LIKE '%'+s.AlarmLevelName +'%') AND s.CanSendNotification = 1  
    AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0  
    AND H.IsNotificationSent=0  
    AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity  
    WHERE ModuleId = 26 and UserGroupId IN   
    (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))  
    ) as a where (Duration is null Or Duration > 0)  
  /**************************** Based on Default Severity ****************************/     
   INSERT INTO rvlfNotificationLog  (  
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,   
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,   
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],  
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,   
    [Subjectsufix] , [Duration] , [MessageDetails]   
   )  
   SELECT * FROM (  
   SELECT h.MessageInID,   
     DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
     DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
     ISNULL(n.Email,0) as CanSendEmail,   
     CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,   
      -- Blocked the SMS for Org US Embassy 52  
     CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,     
     u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,  
     CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
       '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
       cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
      WHEN h.ValidGps = 0 THEN   
       h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
       +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
      ELSE h.StreetAddress END AS StreetAddress,  
     CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
     CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
     h.BoxId, m.BoxMsgInTypeDesc, v.VehicleId, v.VehicleDescription,  
     --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'   
      --ELSE v.VehicleDescription END    
     v.VehicleDescription as VehicleName, f.FleetId, f.FleetName,  
     v.LicensePlate, s.AlarmLevelName as Subjectsufix,  
     CASE WHEN m.BoxMsgInTypeDesc<>'Sensor'   
      THEN (CASE WHEN CHARINDEX(m.BoxMsgInTypeDesc,CustomProp,1) = 1 THEN   
       SUBSTRING (CustomProp, CHARINDEX(':',CustomProp,1)+1,  
       CHARINDEX(';',customprop)-1 -CHARINDEX(':',Customprop,1)) END) ELSE '' END as Duration,   
    CASE WHEN h.BoxMsgInTypeId = 4 THEN m.BoxMsgInTypeDesc + ' ' +  
      CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
      CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END  
      ELSE dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId, h.MessageInID, h.OriginDateTime) END as MessageDetails  
   from rvlfMsgInHst h   
    INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
    INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
    INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
    LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
    INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
    INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
    INNER JOIN rvlfFleet f On fv.FleetId = f.FleetId  
    INNER JOIN rvlfBoxProtocolMsgInType ms ON h.BoxMsgInTypeId = ms.BoxMsgInTypeId  
    INNER JOIN rvlfSeverity s ON ms.DefaultAlarmLevel = s.AlarmLevelId   
      
    /**************** Map to user preferences *******************/  
    INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3  
    INNER JOIN rvlfUser u ON n.UserID = u.UserId  
    INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
    INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
    /**************** Map to user preferences *******************/  
      
   WHERE h.MessageInID=@uimessageInID AND h.IsNotificationSent=0  and h.StreetAddress IS NOT NULL and s.CanSendNotification = 1 and h.BoxMsgInTypeId not in (5,6,2,3)  
    AND  ( case when  
     (case when f.Notify='true' then 'Notify' else '' end +      
     case when f.Warning='true' then 'Warning' else '' end +   
     case when f.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
     (case  when f.Notify='true' then (case when (f.Warning='true' or f.Critical='true') then 'Notify;' else 'Notify' end ) else '' end +      
     case when f.Warning='true' then (case when f.Critical='true' then 'Warning;' else 'Warning' end ) else '' end +   
     case when f.Critical='true' then 'Critical' else '' end)  
     end LIKE '%'+s.AlarmLevelName +'%')   
    AND h.BoxMsgInTypeId NOT IN   
     (SELECT BoxMsgInTypeId  FROM rvlfBoxMsgSeverity bms WHERE bms.BoxId = h.BoxId ) AND s.CanSendNotification = 1  
    AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0  
    AND H.IsNotificationSent=0  
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity  
   WHERE ModuleId = 26 and UserGroupId IN   
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))  
    ) as A Where (Duration is null or Duration > 0)  
  /**************************** Based on Sensor Severity ****************************/  
   INSERT INTO rvlfNotificationLog   
    (  
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,   
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,   
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],  
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,   
    [Subjectsufix] , [Duration] , [MessageDetails]   
   )  
   SELECT h.MessageInID,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
    ISNULL(n.Email,0) as CanSendEmail,   
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,   
     -- Blocked the SMS for Org US Embassy 52  
    CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,     
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,  
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     WHEN h.ValidGps = 0 THEN   
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     ELSE h.StreetAddress END AS StreetAddress,  
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
    h.BoxId, m.BoxMsgInTypeDesc, v.VehicleId, v.VehicleDescription,  
    --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'   
     --ELSE v.VehicleDescription END  
     v.VehicleDescription as VehicleName, f.FleetId, f.FleetName,  
    v.LicensePlate, s.AlarmLevelName as Subjectsufix,null as Duration,   
   --rs.SensorName  + ' '+ SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,   
   --CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1) As MessageDetails  
   rs.SensorName + ' ' + CASE WHEN SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,   
    CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1) = 'ON'   
    THEN rs.ActionOn ELSE rs.ActionOff END AS MessageDetails  
  FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfSensor rs ON  CAST(SUBSTRING(CustomProp,CHARINDEX('=',CustomProp)+1,  
    CHARINDEX(';',CustomProp,1)-CHARINDEX('=',CustomProp)-1) As tinyint) = rs.SensorId  
   INNER JOIN rvlfBoxSensorsCfg bs ON bs.SensorId = rs.SensorId AND h.BoxId = bs.BoxId  
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId  
   INNER JOIN rvlfFleet f On fv.FleetId = f.FleetId  
   INNER JOIN rvlfSeverity s ON s.AlarmLevelId =  
    (CASE WHEN SUBSTRING(CustomProp,CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)+1,  
     CHARINDEX(';',CustomProp,15) - CHARINDEX('=',CustomProp,LEN('SENSOR_NUM=')+1)-1)   
     IN ('OPEN','ON','NORMAL','OK')  
     THEN bs.AlarmLevelOn ELSE bs.AlarmLevelOff END)  
     
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON f.FleetId = n.TypeID and n.NotificationType=3  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
     
  WHERE h.MessageInID=@uimessageInID AND h.BoxMsgInTypeId = 11 /*in (2,3) */ AND h.IsNotificationSent = 0 and h.StreetAddress is not null  
   AND (case when  
    (case when f.Notify='true' then 'Notify' else '' end +      
    case when f.Warning='true' then 'Warning' else '' end +   
    case when f.Critical='true' then 'Critical' else '' end)='' then 'No Alarm' else  
    (case  when f.Notify='true' then (case when (f.Warning='true' or f.Critical='true')  
     then 'Notify;' else 'Notify' end ) else '' end +      
    case when f.Warning='true' then (case when f.Critical='true' then 'Warning;'   
    else 'Warning' end ) else '' end +   
    case when f.Critical='true' then 'Critical' else '' end)  
    end LIKE '%'+s.AlarmLevelName +'%') AND s.CanSendNotification = 1  
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0   
   AND H.IsNotificationSent=0  
   AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity  
   WHERE ModuleId = 26 and UserGroupId IN   
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))  
 /**********************************************************************************/  
 /**************************** Geozone Level Notification **************************/  
 /**********************************************************************************/  
  INSERT INTO rvlfNotificationLog   
   (  
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,   
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,   
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],  
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,   
    [Subjectsufix] , [Duration] , [MessageDetails]   
   )  
   SELECT h.MessageInID,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
    ISNULL(n.Email,0) as CanSendEmail,   
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,   
     -- Blocked the SMS for Org US Embassy 52  
    CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,     
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,  
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     WHEN h.ValidGps = 0 THEN   
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     ELSE h.StreetAddress END AS StreetAddress,  
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
    h.BoxId, m.BoxMsgInTypeDesc, v.VehicleId, v.VehicleDescription,  
    --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'   
     --ELSE v.VehicleDescription END  
     v.VehicleDescription as VehicleName, null, null,  
    v.LicensePlate, s.AlarmLevelName as Subjectsufix, null as Duration,   
    --dbo.rvlf_fn_GetAlarmDetails(CAST( SUBSTRING(h.CustomProp,  
    --CHARINDEX('=',h.CustomProp,1)+1,(CHARINDEX(';',h.CustomProp,1)  
    --- CHARINDEX('=',h.CustomProp,1))-1) as bigint), h.BoxMsgInTypeId,h.BoxId )   
    dbo.rvlf_fn_GetAlarmDetails(h.CustomProp, h.boxMsgintypeid, h.boxid, h.MessageInid, h.origindatetime ) as MessageDetails  
 FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment a ON h.BoxId = a.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
   LEFT OUTER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
  INNER JOIN rvlfVehicle v ON a.VehicleId = v.VehicleId   
  INNER JOIN rvlfOrganizationGeozone g ON g.OrganizationId = v.OrganizationId  
    
  /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON g.GeozoneNo = n.TypeID and n.NotificationType=1  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
  /**************** Map to user preferences *******************/  
    
  INNER JOIN rvlfSeverity s ON g.SeverityId = s.AlarmLevelId  
  WHERE h.MessageInID=@uimessageInID AND s.CanSendNotification=1 AND h.BoxMsgInTypeId in (5,6)  
   AND h.IsNotificationSent = 0 --and h.StreetAddress IS NOT NULL  
   AND g.GeozoneId = (CAST( SUBSTRING(h.CustomProp,  
     CHARINDEX('=',h.CustomProp,1)+1,(CHARINDEX(';',h.CustomProp,1)  
     - CHARINDEX('=',h.CustomProp,1))-1) as bigint))  
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0  
  AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity  
   WHERE ModuleId = 26 and UserGroupId IN   
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))  
 /**********************************************************************************/      
 /**************************** Landmark Level Notification *************************/  
 /**********************************************************************************/  
  INSERT INTO rvlfNotificationLog   
   (  
    [MessageInID], [OriginDateTime], [DateTimeReceived], [CanSendEmail] , [IsMailSent] ,   
    [CanSendSMS] , [IsSMSSent] , [UserID] , [OrganizationID] , [UserName], [Email] ,   
    [MobileNo] , [StreetAddress], [Speed] , [BoxId] , [BoxMsgInTypeName] , [VehicleID],  
    [VehicleDescription] , [VehicleName] , [FleetID] , [FleetName] , [LicensePlate] ,   
    [Subjectsufix] , [Duration] , [MessageDetails]   
   )  
   SELECT h.MessageInID,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.OriginDateTime)) as OriginDateTime,   
    DATEADD(mi,t.MinToBeAdded,DATEADD(hh,t.HoursToBeAdded, h.DateTimeReceived)) as DateTimeReceived,   
    ISNULL(n.Email,0) as CanSendEmail,   
    CASE WHEN n.Email = 1 THEN 0 ELSE null END as IsMailSent ,   
     -- Blocked the SMS for Org US Embassy 52  
    CASE WHEN @IsSMSsent=0 THEN 0 ELSE ISNULL(n.SMS,0) END AS CanSendSMS, CASE WHEN n.SMS = 1 AND @IsSMSsent=1 THEN 0 ELSE null END as IsSMSSent ,     
    u.UserId, u.OrganizationId, u.UserName, u.Email as Email, u.MobileNo,  
    CASE WHEN h.StreetAddress like 'Address Not Found' THEN   
      '<a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )+','+  
      cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     WHEN h.ValidGps = 0 THEN   
      h.StreetAddress + '<br><a href=''http://maps.google.com/maps?q='+cast(h.Latitude as varchar(15) )  
      +','+cast(h.Longitude as varchar(15) ) +'''>View in Map</a>'  
     ELSE h.StreetAddress END AS StreetAddress,  
    CAST((h.Speed * CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END) as varchar(10)) +   
    CASE WHEN up.Distance =0 THEN ' MPH' ELSE ' KMPH' END as Speed,  
    h.BoxId, m.BoxMsgInTypeDesc, v.VehicleId, v.VehicleDescription,  
    --CASE WHEN LEN(v.VehicleDescription)>10 THEN SUBSTRING(v.VehicleDescription,1,7)+'...'   
     --ELSE v.VehicleDescription END  
     v.VehicleDescription  as VehicleName, null, null,  
    v.LicensePlate,   
    CASE WHEN fm.Notify = 1 THEN 'Notify' WHEN fm.Warning=1 THEN 'Warning' ELSE 'Critical' END AS Subjectsufix,   
    null as Duration,   
    (CASE WHEN SUBSTRING(h.SensorMask,6,1) = 1 THEN 'Trip Start' ELSE 'Trip End' END)   
    + ' - ' + fm.LandmarkName  as MessageDetails  
   --(CASE WHEN h.BoxMsgInTypeId = 4 THEN m.BoxMsgInTypeDesc ELSE  
   -- dbo.rvlf_fn_GetAlarmDetails(h.CustomProp,h.BoxMsgInTypeId,h.BoxId) END) + ' - ' + fm.LandmarkName  as MessageDetails  
   FROM rvlfMsgInHst h   
   INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId  
   INNER JOIN rvlfBoxMsgInType m ON h.BoxMsgInTypeId = m.BoxMsgInTypeId  
   INNER JOIN rvlfBoxProtocolType pt ON h.BoxProtocolTypeId = pt.BoxProtocolTypeId  
    INNER JOIN rvlfLandmark fm ON h.LandMarkID = fm.LandmarkID   
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId  
   /**************** Map to user preferences *******************/  
   INNER JOIN rvlfNotificationList n ON fm.LandmarkID = n.TypeID and n.NotificationType=2  
   INNER JOIN rvlfUser u ON n.UserID = u.UserId  
   INNER JOIN rvlfUserPreferences up ON u.UserId = up.UserId  
   INNER JOIN rvlfTimeZones t On up.TimezoneId = t.TimeZoneID  
   /**************** Map to user preferences *******************/  
  WHERE h.MessageInID=@uimessageInID AND h.IsNotificationSent=0 and h.BoxMsgInTypeId not in (5,6,19,20,21,22,28,35,34,31)   
   and h.StreetAddress IS NOT NULL and (fm.Notify=1 OR fm.Warning=1 OR fm.Critical=1)  
   AND (h.MessageInID in (SELECT StartMessageInID FROM rvlfTripDetails) OR h.MessageInID   
    in (SELECT EndMessageInID  FROM rvlfTripDetails) )  
   AND ISNULL(LEN(u.Email),0) > 0 AND u.IsActive=1 AND u.IsDelete=0  
   AND H.IsNotificationSent=0  
  --AND m.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity  
  -- WHERE ModuleId = 26 and UserGroupId IN   
  -- (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = n.UserID))  
/**********************************************************************************************************************************************************/  
----INSERT INTO testtable5 (logdate, MessageInID, msg ) values (GETDATE(), @uimessageInID,'Success' )  
   END  
END TRY  
BEGIN CATCH   
 ----INSERT INTO testtable5 (logdate, MessageInID, msg ) values (GETDATE(), @uimessageInID,CAST (@@Error as varchar(100)) )  
END CATCH  
 UPDATE rvlfMsgInHst SET IsNotificationSent = 1 WHERE MessageInID = @uimessageInID  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_LogOffUser]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_LogOffUser]
	@bigLoginID varchar(50),
	@dtLogOffDateTime datetime
AS
/******************************************************************************/
--	Name		:	rvlf_sp_LogOffUser
--	Description	:	To authenticate the users
--				:   Pass the value 0 (Zero) to @bigQueryingUser if the user is angler admin
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	06-Jul-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 
		UPDATE rvlfUserLogin set LogOffDateTime= @dtLogOffDateTime where LoginId = @bigLoginID
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_LogScheduledReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_LogScheduledReport]
	@bigReportScheduleID bigint,
	@bigUserID bigint = null,
	@vcEmail varchar(200) = null,
	@dtReportStartDate DateTime = null,
	@dtReportEndDate DateTIme = null,
	@dtGeneratedOn DateTime = null,
	@dtActualGeneration DateTime = null,
	@siTimeZoneID smallint = null,
	@bitIsError bit = null,
	@vcErrorMessage varchar(250) = null,
	@cErrorCode char(5) = null,
	@uiReportRef uniqueidentifier = null,
	@vcReportPath varchar(130) = null
AS
/******************************************************************************/
--	Name		:	rvlf_sp_LogScheduledReport
--	Description	:	To update the scheduled reports log
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	23-Mar-2010	MJJC	Created Intial Version 
--              :   22-Apr-2010 MJJC	Included the provision for report path
/******************************************************************************/
BEGIN
	SET NOCOUNT ON 
	BEGIN TRANSACTION UpdateScheduledReportsLog
		BEGIN TRY
			INSERT INTO rvlfScheduledReportLog	
				(ReportScheduleID, UserID, Email, ReportStartDate, ReportEndDate,GeneratedOn, 
				 ActualGeneration,TimeZoneID, IsError, ErrorMessage,ErrorCode, ReportRef, ReportPath)
			VALUES
				(@bigReportScheduleID, @bigUserID, @vcEmail, @dtReportStartDate,@dtReportEndDate,@dtGeneratedOn,
				 @dtActualGeneration,@siTimeZoneID,@bitIsError, @vcErrorMessage, @cErrorCode, @uiReportRef, @vcReportPath  )
			COMMIT
		END TRY
		BEGIN CATCH
			ROLLBACK
		END CATCH
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_MaintenanceCostAnalysis]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_MaintenanceCostAnalysis]    
  @bigOrganizationID bigint = null , 
  @bigFleetId bigint = null,   
  @intBoxId varchar(max) = null,    
  @dtStartDate DateTime =null,    
  @dtEndDate DateTime =null,    
  @tiType tinyint = 1,    
  @tiMaintenanceType tinyint =null,    
  @bigQueryingUser bigint = null    
AS    
/***************************************************************************************/    
-- Name  : rvlf_sp_MaintenanceCostAnalysis 6, 8, 0, '03/01/2010', '04/09/2011', 0, NULL, 140    
-- Description : Maintenance Cost Analysis - Annual & Last 5 Years Comparison Report    
-- Author  : Kumuthini. L    
-- Company  : Angler Technologies    
-- History  : 06-Apr-2011 Kumuthini. L Created Intial Version     
/***************************************************************************************/    
BEGIN    
    
 SET NOCOUNT ON     
    Declare @dtFDate datetime =@dtStartDate  
    Declare @dtEDate datetime =@dtEndDate  
    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 = @bigQueryingUser    
      
 CREATE TABLE #tempServiceCost(VehicleId bigint, VehicleDescription nvarchar(20), ExecutedOn Date,    
      ServiceCost Decimal(9,2))    
     
 INSERT INTO #tempServiceCost    
 SELECT v.VehicleId, VehicleDescription, vm.ExecutedOn, vm.ServiceCost  
   
  FROM rvlfVehicleMaintenanceService VM    
   INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId    
   INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId    
   INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId    
   INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId = v.VehicleId    
  WHERE v.OrganizationId = @bigOrganizationID AND       
      CONVERT(DATE, vm.ExecutedOn, 101) BETWEEN CONVERT(DATE, @dtStartDate, 101) AND CONVERT(DATE, @dtEndDate, 101)    
   AND (@bigFleetId IS NULL OR @bigFleetId='' OR @bigFleetId = 0 OR fv.FleetId = @bigFleetId)    
   AND (@intBoxId IS NULL OR @intBoxId='' OR VA.BoxId in(select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))    
   AND (@tiMaintenanceType IS NULL OR @tiMaintenanceType='' OR @tiMaintenanceType = 0 OR @tiMaintenanceType = 1)    
   AND Status = 1 AND IsNearing = 1    
       
 UNION    
     
 SELECT v.VehicleId, v.VehicleDescription, ad.ExecutionOn AS ExecutedOn, ad.TotalServiceCost AS ServiceCost  
   
 FROM rvlfAdhocServices ad    
 INNER JOIN rvlfVehicle v ON v.VehicleId = ad.VehicleId    
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId    
 INNER JOIN rvlfVehicleAssignment va ON va.VehicleId = v.VehicleId    
 WHERE v.OrganizationId = @bigOrganizationID AND     
 CONVERT(DATE, ad.ExecutionOn, 101) BETWEEN CONVERT(DATE, @dtStartDate, 101) AND CONVERT(DATE, @dtEndDate, 101)    
 AND (@bigFleetId IS NULL OR (@bigFleetId='') OR @bigFleetId = 0 OR fv.FleetId = @bigFleetId)    
 AND ((@intBoxId IS NULL) OR (@intBoxId ='')  OR (va.BoxId in(select * from rvlf_fn_ConvertArrayToTable(@intBoxID,','))))    
 AND (@tiMaintenanceType IS NULL OR @tiMaintenanceType='' OR @tiMaintenanceType = 0 OR @tiMaintenanceType = 2)    
        select * from #tempServiceCost
        
    DECLARE @dtFromDate AS DATETIME    
 DECLARE @dtToDate AS DATETIME    
        
    IF @tiType = 0    
    BEGIN    
        
  CREATE TABLE #tempQuarterlySummary(VehicleId bigint, Qtr1 Decimal(9,2), Qtr2 Decimal(9,2), Qtr3 Decimal(9,2),     
   Qtr4 Decimal(9,2), Total Decimal(9,2))    
          
  INSERT INTO #tempQuarterlySummary    
  SELECT DISTINCT t.VehicleId, 0, 0, 0, 0, 0 FROM #tempServiceCost t    
  INNER JOIN rvlfVehicle V ON V.VehicleId = t.VehicleId    
   
  -- 1st Quarter    
  SET @dtFromDate = @dtStartDate    
  SET @dtToDate = DATEADD(D, -1, DATEADD(M, 3, @dtFromDate))    
      
  -- To get Quarter Name    
  DECLARE @vcQtr1_Name varchar(50)    
  DECLARE @vcQtr2_Name varchar(50)    
  DECLARE @vcQtr3_Name varchar(50)    
  DECLARE @vcQtr4_Name varchar(50)    
      
  SET @vcQtr1_Name = SUBSTRING(DATENAME(M,@dtFromDate),1,3) + SUBSTRING(CONVERT(VARCHAR(4),YEAR(@dtFromDate)),3,2) + ' - ' + SUBSTRING(DATENAME(M,@dtToDate),1,3) + SUBSTRING(CONVERT(VARCHAR(4),YEAR(@dtToDate)),3,2)    
      
  IF EXISTS (SELECT VehicleId FROM #tempServiceCost WHERE ExecutedOn BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101))    
  BEGIN    
      
   UPDATE #tempQuarterlySummary SET Qtr1 =     
   (     
    SELECT SUM(ISNULL(ServiceCost, 0)) FROM #tempServiceCost     
    WHERE ExecutedOn BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101)    
    AND #tempQuarterlySummary.VehicleId = #tempServiceCost.VehicleId    
    GROUP BY VehicleId    
   )    
      
  END     
     
  -- 2nd Quarter    
  SET @dtFromDate = DATEADD(D, 1, @dtToDate)    
  SET @dtToDate = DATEADD(D, -1, DATEADD(M, 3, @dtFromDate))    
     
     SET @vcQtr2_Name = SUBSTRING(DATENAME(M,@dtFromDate),1,3) + SUBSTRING(CONVERT(VARCHAR(4),YEAR(@dtFromDate)),3,2) + ' - ' + SUBSTRING(DATENAME(M,@dtToDate),1,3) + SUBSTRING(CONVERT(VARCHAR(4),YEAR(@dtToDate)),3,2)    
     
  IF EXISTS (SELECT VehicleId FROM #tempServiceCost WHERE ExecutedOn BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101))    
  BEGIN    
      
   UPDATE #tempQuarterlySummary SET Qtr2 =     
   (     
    SELECT SUM(ISNULL(ServiceCost, 0)) FROM #tempServiceCost     
    WHERE ExecutedOn BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101)    
    AND #tempQuarterlySummary.VehicleId = #tempServiceCost.VehicleId    
    GROUP BY VehicleId    
   )    
      
  END     
     
  -- 3rd Quarter    
  SET @dtFromDate = DATEADD(D, 1, @dtToDate)    
  SET @dtToDate = DATEADD(D, -1, DATEADD(M, 3, @dtFromDate))    
     
     SET @vcQtr3_Name = SUBSTRING(DATENAME(M,@dtFromDate),1,3) + SUBSTRING(CONVERT(VARCHAR(4),YEAR(@dtFromDate)),3,2) + ' - ' + SUBSTRING(DATENAME(M,@dtToDate),1,3) + SUBSTRING(CONVERT(VARCHAR(4),YEAR(@dtToDate)),3,2)    
     
  IF EXISTS (SELECT VehicleId FROM #tempServiceCost WHERE ExecutedOn BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101))    
  BEGIN    
      
   UPDATE #tempQuarterlySummary SET Qtr3 =     
   (     
    SELECT SUM(ISNULL(ServiceCost, 0)) FROM #tempServiceCost     
    WHERE ExecutedOn BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101)    
    AND #tempQuarterlySummary.VehicleId = #tempServiceCost.VehicleId    
    GROUP BY VehicleId    
   )    
      
  END     
     
  -- 4th Quarter    
  SET @dtFromDate = DATEADD(D, 1, @dtToDate)    
  SET @dtToDate = DATEADD(D, -1, DATEADD(M, 3, @dtFromDate))    
      
  SET @vcQtr4_Name = SUBSTRING(DATENAME(M,@dtFromDate),1,3) + SUBSTRING(CONVERT(VARCHAR(4),YEAR(@dtFromDate)),3,2) + ' - ' + SUBSTRING(DATENAME(M,@dtToDate),1,3) + SUBSTRING(CONVERT(VARCHAR(4),YEAR(@dtToDate)),3,2)    
      
  IF EXISTS (SELECT VehicleId FROM #tempServiceCost WHERE ExecutedOn BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101))    
  BEGIN    
      
   UPDATE #tempQuarterlySummary SET Qtr4 =     
   (     
    SELECT SUM(ISNULL(ServiceCost, 0)) FROM #tempServiceCost     
    WHERE ExecutedOn BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101)    
    AND #tempQuarterlySummary.VehicleId = #tempServiceCost.VehicleId    
    GROUP BY VehicleId    
   )    
      
  END     
      
  UPDATE #tempQuarterlySummary SET Total = ISNULL(Qtr1, 0) + ISNULL(Qtr2, 0) + ISNULL(Qtr3, 0) + ISNULL(Qtr4, 0)     
     
     DECLARE @vcQuery varchar(max)    
  
  Declare @PasQry varchar(max)   
    
  set @PasQry ='   
  Convert(varchar,'''+ Convert(varchar,@dtFDate,@DefaultDateFormat) + ''',' + cast(@DefaultDateFormat as varchar) + ')' +  '+'' ' + ' ''+ ' + 'Convert(varchar,cast('''+ Convert(varchar,@dtFDate,22) + ''' as time),22) as PasStartDate,  
  Convert(varchar,'''+ Convert(varchar,@dtEDate,@DefaultDateFormat) +''',' + cast(@DefaultDateFormat as varchar) + ')' +  '+'' ' + ' ''+ ' + 'Convert(varchar,cast(''' + Convert(varchar,@dtEDate,22) + ''' as Time),22) as PasEndDate,      
  Convert(varchar,'''+ Convert(varchar,Getdate(),@DefaultDateFormat) +''',' + cast(@DefaultDateFormat as varchar) + ')' + '+'' ' + ' ''+ ' + 'Convert(varchar,cast(''' + Convert(varchar,Getdate(),22) + ''' as Time),22) as PasGeneratedDate'   
  SET @vcQuery = 'SELECT V.VehicleId, V.VehicleDescription, V.LicensePlate, M.MakeName AS Make, Mo.ModelName AS Model,     
      V.ModelYear AS [Year], ISNULL(t.Qtr1, 0) AS '''+ @vcQtr1_Name +''', ISNULL(t.Qtr2, 0) AS '''+ @vcQtr2_Name +''',     
      ISNULL(t.Qtr3, 0) AS '''+ @vcQtr3_Name +''', ISNULL(t.Qtr4, 0) AS '''+ @vcQtr4_Name +''', ISNULL(t.Qtr1, 0) AS Qtr1,    
      ISNULL(t.Qtr2, 0) AS Qtr2, ISNULL(t.Qtr3, 0) AS Qtr3, ISNULL(t.Qtr4, 0) AS Qtr4, ISNULL(t.Total, 0) AS Total,'  
       + @PasQry + '   
  FROM #tempQuarterlySummary t    
  RIGHT OUTER JOIN rvlfVehicle V ON V.VehicleId = t.VehicleId    
  LEFT JOIN rvlfMake M ON M.MakeId = V.MakeId     
  LEFT JOIN rvlfModel Mo ON Mo.ModelId = V.ModelId    
  WHERE V.OrganizationId = '+ cast(@bigOrganizationID as varchar(5))+' '     
  print @vcQuery  
  Exec(@vcQuery)    
      
  DROP TABLE #tempQuarterlySummary    
      
 END    
 ELSE    
 BEGIN    
     
  CREATE TABLE #tempYearlySummary(VehicleId bigint, Year1 Decimal(9,2), Year2 Decimal(9,2), Year3 Decimal(9,2),     
   Year4 Decimal(9,2), Year5 Decimal(9,2), Year6 Decimal(9,2), Total Decimal(9,2))    
          
  INSERT INTO #tempYearlySummary    
  SELECT DISTINCT t.VehicleId, 0, 0, 0, 0, 0, 0, 0 FROM #tempServiceCost t    
  INNER JOIN rvlfVehicle V ON V.VehicleId = t.VehicleId    
    
  DECLARE @vrSQL AS nvarchar(4000) = ''    
  DECLARE @tiLoop AS tinyint = 0     
      
  SET @dtFromDate = @dtStartDate    
  SET @dtToDate = DATEADD(D, -1, DATEADD(YEAR, 1, @dtFromDate))    
      
  WHILE @tiLoop < 6    
  BEGIN    
       
   IF EXISTS (SELECT VehicleId FROM #tempServiceCost WHERE ExecutedOn BETWEEN CONVERT(DATE, @dtFromDate, 101) AND CONVERT(DATE, @dtToDate, 101))    
   BEGIN    
    
    SET @vrSQL = N'UPDATE #tempYearlySummary SET Year' + CONVERT(Varchar(1), (@tiLoop + 1)) + ' = ('    
    SET @vrSQL += 'SELECT SUM(ISNULL(ServiceCost, 0)) FROM #tempServiceCost '     
    SET @vrSQL += 'WHERE ExecutedOn BETWEEN CONVERT(DATE,''' + CONVERT(Varchar(25), @dtFromDate) + ''', 101) AND CONVERT(DATE,''' + CONVERT(Varchar(25), @dtToDate) + ''', 101) '    
    SET @vrSQL += 'AND #tempYearlySummary.VehicleId = #tempServiceCost.VehicleId '    
    SET @vrSQL += 'GROUP BY #tempServiceCost.VehicleId)'    
        
    EXEC SP_ExecuteSql @vrSQL    
       
   END    
       
   SET @dtFromDate = DATEADD(D, 1, @dtToDate)    
      SET @dtToDate = DATEADD(D, -1, DATEADD(YEAR, 1, @dtFromDate))    
       
   SET @tiLoop = @tiLoop + 1    
      
  END    
      
  UPDATE #tempYearlySummary SET Total = ISNULL(Year1, 0) + ISNULL(Year2, 0) + ISNULL(Year3, 0)     
             + ISNULL(Year4, 0) + ISNULL(Year5, 0) + ISNULL(Year6, 0)    
   
  SET @vrSQL = N'SELECT rvlfVehicle.VehicleId, rvlfVehicle.VehicleDescription, rvlfVehicle.LicensePlate, M.MakeName AS Make, Mo.ModelName AS Model, ModelYear AS [Year],'    
  SET @vrSQL += 'ISNULL(Year1, 0) AS ''' + CONVERT(Varchar(4), DATEPART(YEAR, @dtStartDate)) + ''','    
  SET @vrSQL += 'ISNULL(Year2, 0) AS ''' + CONVERT(Varchar(4), DATEPART(YEAR, @dtStartDate)+1) + ''','    
     SET @vrSQL += 'ISNULL(Year3, 0) AS ''' + CONVERT(Varchar(4), DATEPART(YEAR, @dtStartDate)+2) + ''','    
     SET @vrSQL += 'ISNULL(Year4, 0) AS ''' + CONVERT(Varchar(4), DATEPART(YEAR, @dtStartDate)+3) + ''','    
     SET @vrSQL += 'ISNULL(Year5, 0) AS ''' + CONVERT(Varchar(4), DATEPART(YEAR, @dtStartDate)+4) + ''','    
     SET @vrSQL += 'ISNULL(Year6, 0) AS ''' + CONVERT(Varchar(4), DATEPART(YEAR, @dtStartDate)+5) + ''','    
  SET @vrSQL += 'ISNULL(Year1, 0) AS Year1, ISNULL(Year2, 0) AS Year2, ISNULL(Year3, 0) AS Year3,'    
  SET @vrSQL += 'ISNULL(Year4, 0) AS Year4, ISNULL(Year5, 0) AS Year5, ISNULL(Year6, 0) AS Year6, ISNULL(Total, 0) AS Total FROM #tempYearlySummary '    
  SET @vrSQL += 'RIGHT OUTER JOIN rvlfVehicle ON rvlfVehicle.VehicleId = #tempYearlySummary.VehicleId '    
  SET @vrSQL += 'LEFT JOIN rvlfMake M ON M.MakeId = rvlfVehicle.MakeId '    
  SET @vrSQL += 'LEFT JOIN rvlfModel Mo ON Mo.ModelId = rvlfVehicle.ModelId '    
  SET @vrSQL += 'WHERE rvlfVehicle.OrganizationId = ' + CONVERT(Varchar(10), @bigOrganizationID)    
      
  EXEC SP_ExecuteSql @vrSQL    
      
  DROP TABLE #tempYearlySummary    
     
 END    
        
    DROP TABLE #tempServiceCost    
        
 SET NOCOUNT OFF    
     
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ManualAddressUpdate]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================      
-- Author:  Vijay N      
-- Create date: 9-Sep-2012      
-- Description: To update the address in landmark.    
-- =============================================      
CREATE PROCEDURE [dbo].[rvlf_sp_ManualAddressUpdate]      
 -- Add the parameters for the stored procedure here       
 @LandMarkId AS BIGINT = NULL,      
 @StreetAddress AS NVARCHAR(250) = NULL      
AS      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;      
    -- Insert statements for procedure here      
    IF(@LandMarkId IS NULL)      
    BEGIN      
  SELECT TOP 1 LandmarkID,(CAST(Latitude AS VARCHAR(10))+','+ CAST(Longitude AS VARCHAR(10))) coord       
  FROM rvlfLandmark WHERE (StreetAddress IS NULL OR StreetAddress  = '')      
 END      
 ELSE       
 BEGIN       
  UPDATE rvlfLandmark SET StreetAddress = @StreetAddress WHERE     
  LandmarkID = @LandMarkId      
 END      
       
 SET NOCOUNT OFF;      
END      
    
    
   

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_MoveOldData]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_MoveOldData]
/******************************************************************************/
--	Name		:	rvlf_sp_MoveOldData 
--	Description	:	To get the data older than 2 months and move to master backup Database
--	Author		:	Sathish
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	07-Feb-2011	Created
/******************************************************************************/
As
BEGIN
DECLARE @topMsg uniqueidentifier
--SELECT TOP 1 @topmsg = MessageInID from TRINETRA_TEST..rvlfmsginhst order by OriginDateTime desc

--DECLARE @maxMsg uniqueidentifier
--SELECT Top 1 @maxMsg = MessageInID from TRINETRA_Pilot..rvlfmsginhst 
--WHERE CONVERT(Date,OriginDateTime) < CONVERT(date,DATEADD(mm,-2,GETDATE())) order by OriginDateTime desc

--INSERT INTO TRINETRA_Test..rvlfMsgInHst
--SELECT * from TRINETRA_Pilot..rvlfMsgInHst where MessageInID between @topMsg and @maxMsg

-- DELETE from TRINETRA_Pilot..rvlfMsgInHst where MessageInID between @topMsg and @maxMsg

END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_NotificationReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE  PROCEDURE [dbo].[rvlf_sp_NotificationReport]                            
 @bigOrganizationID bigint = 6,     
 @Userid bigint =null,           
 @bigQueryingUser bigint = 502                
AS                
/******************************************************************************/                
-- Name  : [rvlf_sp_NotificationReport] 6,null,502    
-- Description : To get the details of configured notifications for the users and modules            
-- Author  : Gopal.K
-- Company  : Angler Technologies                
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                
--    : 28-Jun-2016 VN Created Intial Version               
/******************************************************************************/                
 BEGIN                
                  
 SET NOCOUNT ON  

 DECLARE @HoursToBeAdded INT = 0
 DECLARE @MinsToBeAdded INT = 0
 DECLARE @ConversionFactor numeric (10,2) = 1.0  
 DECLARE @DistanceCaptionPrefix varchar(15)
 DECLARE @SpeedCaptionPrefix varchar(15)              
 DECLARE @DefaultDateFormat INT = 0;     
  DECLARE @Lang varchar(50),  @LangSetting varchar(20)      
                   
    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,@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  
	--select @HoursToBeAdded,@MinsToBeAdded
 declare @table table (UserID bigint,NotificationType tinyint,TypeID bigint,Email bit,
SMS	bit,UserName nvarchar(100),DisplayName nvarchar(200),MobileNo varchar(15),Emailid varchar(200),NotificationTypeName varchar(100),Createdatetime datetime)
 insert into @table
 select nl.UserID,nl.NotificationType,nl.TypeID,case when nl.Email='' then null else nl.Email end,case when nl.SMS ='' then null else nl.SMS end,u.UserName,u.DisplayName,u.PhoneNo,u.Email,nt.NotificationTypeName,
 DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,nl.Createdatetime)) 
    -- dbo.rvlf_fn_DayLightSavings('2015-09-08 00:00:00',@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,nl.Createdatetime)        
 from rvlfNotificationList
 NL 
 inner join rvlfUser U on nl.UserID=u.UserId inner join rvlfNotificationListTypes NT on nl.NotificationType=nt.NotificationTypeId
 where u.IsDelete != 1 and u.OrganizationId=@bigOrganizationID and (@Userid is null or @Userid=0 or nl.UserID=@Userid) 
--select * from @table order by notificationtype ,UserID
--select * from rvlfNotificationListTypes

declare @tblNotification table (UserID bigint,Username varchar(100),Displayname varchar(200),Emailid varchar(200),MobileNo varchar(15),NotificationType tinyint,NotificationTypeName varchar(100),Email bit,SMS bit,Typeid bigint,Name varchar(200),Createdatetime datetime) 

insert into @tblNotification

select t.UserID,t.UserName,t.DisplayName,t.Emailid,t.MobileNo,t.NotificationType,t.NotificationTypeName,t.Email,t.SMS,t.TypeID,og.GeozoneName,t.Createdatetime 
from rvlfOrganizationGeozone OG inner join @table T on og.GeozoneNo=t.TypeID 
where NotificationType=1
union all
select t.UserID,t.UserName,t.DisplayName,t.Emailid,t.MobileNo,t.NotificationType,t.NotificationTypeName,t.Email,t.SMS,t.TypeID,l.LandmarkName,t.Createdatetime
 from rvlfLandmark L inner join @table T on L.LandmarkID=t.TypeID 
where NotificationType=2
union all
select t.UserID,t.UserName,t.DisplayName,t.Emailid,t.MobileNo,t.NotificationType,t.NotificationTypeName,t.Email,t.SMS,t.TypeID,f.FleetName,t.Createdatetime
 from rvlfFleet F  inner join @table T on F.FleetId=t.TypeID 
where NotificationType=3
union all
select t.UserID,t.UserName,t.DisplayName,t.Emailid,t.MobileNo,t.NotificationType,t.NotificationTypeName,t.Email,t.SMS,t.TypeID,v.VehicleDescription,t.Createdatetime
 from rvlfVehicle v  inner join @table T on v.VehicleId=t.TypeID 
where NotificationType=4
union all
select t.UserID,t.UserName,t.DisplayName,t.Emailid,t.MobileNo,t.NotificationType,t.NotificationTypeName,t.Email,t.SMS,t.TypeID,RT.ReportTypesName
+ ' ( '+convert(varchar,DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.EffectiveFrom)),@DefaultDateFormat) 
+ ' '+ convert(varchar,cast(DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.EffectiveFrom))as time),22) 
+ ' to '+        
         isnull(convert(varchar,DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.EffectiveTo)),@DefaultDateFormat)  
		 +' ' + convert(varchar,cast(DATEADD(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SR.EffectiveTo)) as time),22)
		 ,'No end') +' )'
,t.Createdatetime 
   
 from rvlfSchedulingReport SR  inner join @table T on SR.ReportScheduleId=t.TypeID 
inner join rvlfReportTypes RT on sr.ReportTypesId=rt.ReportTypesId
where NotificationType=5


--select * from rvlfMaintenancePlan MP  inner join @table T on mp.PlanId=t.TypeID 
--where NotificationType=6
union all
select t.UserID,t.UserName,t.DisplayName,t.Emailid,t.MobileNo,t.NotificationType,t.NotificationTypeName,t.Email,t.SMS,t.TypeID,MS.ServiceName,t.Createdatetime
 from rvlfMaintenanceService MS  inner join @table T on MS.ServiceId=t.TypeID 
where NotificationType=7
union all
select t.UserID,t.UserName,t.DisplayName,t.Emailid,t.MobileNo,t.NotificationType,t.NotificationTypeName,t.Email,t.SMS,t.TypeID,MP.PlanName,t.Createdatetime
 from rvlfMaintenancePlan MP  inner join @table T on mp.PlanId=t.TypeID 
where NotificationType=8
union all
select t.UserID,t.UserName,t.DisplayName,t.Emailid,t.MobileNo,t.NotificationType,t.NotificationTypeName,t.Email,t.SMS,t.TypeID,DGM.DriverGroupName ,t.Createdatetime
from rvlfDriverGroupAssignment DG  inner join @table T on DG.DriverId=t.TypeID 
inner join rvlfDriverGroupMaster DGM on dg.DriverGroupId=DGM.DriverGroupId
where NotificationType=11
union all
select t.UserID,t.UserName,t.DisplayName,t.Emailid,t.MobileNo,t.NotificationType,t.NotificationTypeName,t.Email,t.SMS,t.TypeID,Tvm.TyreName,t.Createdatetime
 from rvlfTyreVehicleMapping TVM  inner join @table T on TVM.TyreMappingId=t.TypeID 
inner join rvlfTyreMaster TM on TVM.TyreID=tm.TyreId
where NotificationType=13
union all
select t.UserID,t.UserName,t.DisplayName,t.Emailid,t.MobileNo,t.NotificationType,t.NotificationTypeName,t.Email,t.SMS,t.TypeID,ITM.ItemName ,t.Createdatetime
from rvlfInvItemMaster ITM  inner join @table T on ITM.ItemSNo=t.TypeID 
where NotificationType=16


select n.UserID ,Username ,Displayname ,Emailid ,MobileNo ,NotificationType ,NotificationTypeName ,Email ,SMS ,Typeid ,Name  ,Totalcount,EmailCount,SMScount,
PasGenerateddate = dbo.rvlf_fn_DayLightSavings(null,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,GETUTCDATE()) 
,case when email=1 and sms =1 then 'Both'
when email=1 and (sms is null or sms =0) then 'Email'
when (Email is null or email =0) and sms=1 then 'SMS' end as Notify,n.Createdatetime from @tblNotification N 
inner join (
select UserID,count(*) as Totalcount,sum(cast(email as int)) as EmailCount,sum(cast(sms as int)) as SMScount from @tblNotification group by UserID) as CN
on n.UserID=CN.UserID 

END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_refgassignedvehicle]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE proc [dbo].[rvlf_sp_refgassignedvehicle]      
@VehicleId bigint      
as      
begin      
select * from rvlfrefrigeratorassignmt where vehicleid=@VehicleId  and UnAssignDate is null    
end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_RemoveMapping]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
              
CREATE PROCEDURE [dbo].[rvlf_sp_RemoveMapping]             

@Mode int = null

AS              
-- =============================================              
-- Name   : rvlf_sp_UpdateMapping              
-- Author  : Kapil              
-- Create date : 26-Mar-2014              
-- Description : CheckDuplicate Tyre Mapping Details              
-- Company  : TRINETRA
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
-- =============================================              
BEGIN              
 -- SET NOCOUNT ON added to prevent extra result sets from              
 -- interfering with SELECT statements.              
 SET NOCOUNT ON;      
 
 /****************************Reading XML File and Store into Temp table**************/   
	   IF(@Mode =0)  
  		
	   delete from rvlfTyreVehicleMapping where IsActive = 0 and IsRemap is null
	   
	    if EXISTS (select TyreMappingId from rvlfTyreVehicleMapping where TID in(
		        select TID from rvlfTyreVehicleMapping where TID in(     
		        select TID from rvlfTyreVehicleMapping where IsRethread = 2 and IsDelete=0 and IsActive = 1 and Category = 2) group by TID having Count(*) <2))
		        		       
				update rvlfTyreVehicleMapping set IsRethread = 4 where  TyreMappingId IN(		        
		        select TyreMappingId from rvlfTyreVehicleMapping where TID in(
		        select TID from rvlfTyreVehicleMapping where TID in(     
		        select TID from rvlfTyreVehicleMapping where IsRethread = 2 and IsDelete=0 and IsActive = 1 and Category =2) group by TID having Count(*) <2))
		        
		        
		        
	   
       else
       
       update rvlfTyreVehicleMapping set Category = prevCategory,IsRemap = 0 where IsRemap = 1
       delete from rvlfTyreHistory where IsRemap = 1
       delete from  rvlfTyreVehicleMapping where IsActive = 0 and IsRethread = 1 and prevCategory is NULL
       
        if EXISTS (select TyreMappingId from rvlfTyreVehicleMapping where TID in(
		        select TID from rvlfTyreVehicleMapping where TID in(     
		        select TID from rvlfTyreVehicleMapping where IsRethread = 2 and IsDelete=0 and IsActive = 1 and Category = 2) group by TID having Count(*) <2))
		        		       
				update rvlfTyreVehicleMapping set IsRethread = 4 where  TyreMappingId IN(		        
		        select TyreMappingId from rvlfTyreVehicleMapping where TID in(
		        select TID from rvlfTyreVehicleMapping where TID in(     
		        select TID from rvlfTyreVehicleMapping where IsRethread = 2 and IsDelete=0 and IsActive = 1 and Category =2) group by TID having Count(*) <2))
		        
		        
		        
                 
                   
END 





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_RemoveTyreMappingDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
      
CREATE PROCEDURE [dbo].[rvlf_sp_RemoveTyreMappingDetails]       
@TyreMapId int,
@bigOrganizationId bigint = Null   ,
@Comments varchar(150) = null 
AS      
-- =============================================      
-- Name   : rvlf_sp_RemoveTyreMappingDetails 26,6  
-- Author  : kapil      
-- Create date : 27-Feb-2014
-- Description : Remove Tyre Mapping Details      
-- Company  : Trinetra      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
-- Category Refers : 2 -> Removed, 1 -> Remapped, NULL -> Mapped  
-- =============================================      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;		 	   
SET ANSI_WARNINGS OFF;

 	DEClare @VehID INT = (select CASE WHEN ISNULL(Category,0)= 1 THEN ToVehicleID ELSE VehicleID END from rvlfTyreVehicleMapping where TyreMappingId = @TyreMapId AND IsDelete =0)
 		
 	--Update rvlfTyreVehicleMapping set Category=2, RemovedDate =GETUTCDATE() where TyreMappingId =@TyreMapId AND IsDelete =0
 	
 	declare @CurrentOdo BIGINT = (SELECT (select top 1 Odometer from rvlfMsgInHst where BoxId IN (Va.BoxID) order by DateTimeReceived desc) from rvlfVehicle VEH	 
	left join rvlfVehicleAssignment VA on VA.VehicleId = VEH.VehicleId
	WHERE veh.OrganizationId =@bigOrganizationId and VA.VehicleId = @VehID)
 	 
 	--SELECT @CurrentOdo,@VehID
 	
 	update rvlfTyreVehicleMapping set Category=2, RemovedDate =GETUTCDATE(),RemovedOdometer = isnull(@CurrentOdo,0),RemoveComments = @Comments,
 	Distance = ISNULL(Distance,0) +  
 	(select (@CurrentOdo- (CASE WHEN ISNULL(Category,0)= 1 THEN SwappedOdometer else Odometer end)) from rvlfTyreVehicleMapping where TyreMappingId = @TyreMapId) 	
  	where TyreMappingId =@TyreMapId 	
 		
	--update TV  set Tv.Category = 2, TV.RemovedDate = GETUTCDATE(), RemovedOdometer = Odo ( 		 	       
 --   SELECT (select MAX(Odometer) from rvlfMsgInHst where BoxId IN (Va.BoxID) group by BoxId) as Odo  from rvlfVehicle VEH	 
	--left join rvlfVehicleAssignment VA on VA.VehicleId = VEH.VehicleId
	--WHERE veh.OrganizationId =@bigOrganizationId and VA.VehicleId = @VehID)  from rvlfTyreVehicleMapping TV where TyreMappingId =@TyreMapId 
	

 	
		
 Set Nocount Off; 

END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_rescheduleToExpireCommands]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_rescheduleToExpireCommands]
@ScheduleID bigint
AS
/******************************************************************************/  
-- Name        : [rvlf_sp_rescheduleToExpireCommands]  
-- Description : To update / reschedule the expired commands
-- Author	   : Sakthi Gopinath S
-- Company	   : Angler Technologies  
-- History     : 29-May-2013 Sakthi Created Intial Version   
/******************************************************************************/ 
BEGIN
SET NOCOUNT ON
	DECLARE @oldFrom DATETIME
	DECLARE @oldTo DATETIME
	DECLARE @days tinyint
	BEGIN TRAN trnUpdate
		SELECT @oldFrom=EffectiveFrom,@oldTo=EffectiveTo FROM rvlfScheduleOfCommandsMaster WHERE ScheduleId=@ScheduleID
		SELECT @days=DATEDIFF(DD,@oldFrom,@oldTo)
	
		UPDATE rvlfScheduleOfCommandsMaster SET EffectiveFrom=GETUTCDATE(),EffectiveTo=DATEADD(DD,@days,GETUTCDATE()),
		PacketInfo=PacketInfo ,
		NextExecutionOn=NULL,ActualExecutionDate=NULL WHERE ScheduleId=@ScheduleID
	
		IF EXISTS(SELECT 1 FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId=@ScheduleID)
		BEGIN
			DELETE rvlfSchedulingOfCommandsLog WHERE ScheduleId=@ScheduleID
			INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId) VALUES(@ScheduleID)
		END
		ELSE
		BEGIN
			INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId) VALUES(@ScheduleID)
		END
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RAISERROR('Reschedule a command is failed',10,1)
		END
	COMMIT TRAN
SET NOCOUNT OFF
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_RFIDAssignment]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_RFIDAssignment] --6,999888,0            
@bigOrganizationID bigint=6,            
@intBoxID bigint=null,            
@bitIsAssigned bit=0,            
@bigQueryingUser BIGINT            
as            
/******************************************************************************/                                                      
-- Name  : rvlf_sp_RFIDAssignment   6,999982,1,292              
-- Description : Get Assigned RFID Details                                             
-- Author  : Gopal.R              
-- Company  : Angler Technologies              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
--Created Date -13-Oct-2014               
/******************************************************************************/              
begin            
if(@bitIsAssigned=1)            
begin            
declare @NoOfRFID int =(select count(BM.IButtonId)from rvlfIButtonMapping BM             
inner join rvlfDriverMaster DM on BM.DriverId=DM.DriverId            
left join rvlfVehicleRFIDs VR on BM.IButtonId=VR.IButtonID            
left join rvlfVehicleAssignment VA on VR.VehicleId=VA.VehicleId            
where dm.OrganizationID=@bigOrganizationID and VA.BoxId=@intBoxID and VR.IButtonID is not null)      
      
select VA.BoxID,BM.IButtonId,BM.IButtonKey,bm.IButtonKeyName, VR.IButtonID,BM.OrganizationID,@NoOfRFID as NoOfRFID       ,convert( varchar, VR.AssignedDate,106 ) as AssignedDate      
from rvlfIButtonMapping BM             
--inner join rvlfDriverMaster DM on BM.DriverId=DM.DriverId            
left join rvlfVehicleRFIDs VR on BM.IButtonId=VR.IButtonID            
left join rvlfVehicleAssignment VA on VR.VehicleId=VA.VehicleId    
where bm.OrganizationID=@bigOrganizationID and VA.BoxId=@intBoxID and VR.IButtonID is not null            
end            
else            
begin            
select BM.IButtonId,BM.IButtonKey,bm.IButtonKeyName--,dm.DriverId,dm.DriverName,dm.OrganizationID             
from rvlfIButtonMapping BM             
--inner join rvlfDriverMaster DM on BM.DriverId=DM.DriverId            
--left join rvlfVehicleRFIDs VR on BM.IButtonId=VR.IButtonID       
left join rvlfVehicleAssignment VA on BM.BoxID=VA.BoxId    
where BM.OrganizationID=@bigOrganizationID and KeyType=3 --and VR.IButtonId is null--and VA.BoxId=@intBoxID             
end            
end 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_Route_GetUnassignedVehiclesDrivers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_Route_GetUnassignedVehiclesDrivers]  
(  
 @bitType BIT,  
 @bigRouteId BIGINT = 0,  
 @dtFromDateTime DATETIME = NULL,  
 @dtToDateTime DATETIME = NULL,  
 @bigOrganizationId BIGINT = 0,  
 @bigQueryingUser BIGINT = 0  
)  
AS  
/**************************************************************************************/  
-- Name  : rvlf_sp_Route_GetUnassignedVehiclesDrivers  
-- Description : To get the un-assigned Fleet Vehicles & Driver Group - Drivers from the particular Route  
-- Author  : Kumuthini. L  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 27-Sep-2010  Created Intial Version   
/**************************************************************************************/  
BEGIN  
SET NOCOUNT ON   
  
 DECLARE @HoursToBeAdded INT = 0  
 DECLARE @MinsToBeAdded INT = 0  
   
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded  
 FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz  
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser  
  
 SET @dtFromDateTime = DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtFromDateTime))  
 SET @dtToDateTime = DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtToDateTime))  
  
 IF (@bitType = 0) -- Fleet Vehicles  
 BEGIN  
   
 SELECT DISTINCT f.FleetId, f.FleetName FROM rvlfFleet f   
 INNER JOIN rvlfFleetVehicles fv ON fv.FleetId = f.FleetId  
 WHERE f.OrganizationId = @bigOrganizationId AND f.FleetName <> 'All'   
 ORDER BY FleetName ASC  
   
 SELECT fv.FleetId, v.VehicleId, v.VehicleDescription,   
  CASE WHEN EXISTS (SELECT AssignmentId FROM rvlfRouteVehicleAssignment WHERE VehicleId = v.VehicleId AND   
  ((CONVERT(DATE, FromDateTime) BETWEEN CONVERT(DATE, @dtFromDateTime) AND CONVERT(DATE, @dtToDateTime)) OR  
  (CONVERT(DATE, ToDateTime) BETWEEN CONVERT(DATE, @dtFromDateTime) AND CONVERT(DATE, @dtToDateTime))) AND   
  ((CONVERT(TIME, FromDateTime) BETWEEN CONVERT(TIME, @dtFromDateTime) AND CONVERT(TIME, @dtToDateTime)) OR  
  (CONVERT(TIME, ToDateTime) BETWEEN CONVERT(TIME, @dtFromDateTime) AND CONVERT(TIME, @dtToDateTime))))   
  THEN 1 ELSE 0 END AS AssignedStatus  
 FROM rvlfVehicle v  
 INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId  
 ORDER BY VehicleDescription ASC  
    
 END  
 ELSE -- Driver Group - Drivers  
 BEGIN  
   
 SELECT DISTINCT dg.DriverGroupId, dg.DriverGroupName FROM rvlfDriverGroupMaster dg  
 INNER JOIN rvlfDriverGroupAssignment dga ON dga.DriverGroupId = dg.DriverGroupId  
 WHERE dg.OrganizationId = @bigOrganizationId   
 ORDER BY DriverGroupName ASC  
      
 SELECT dg.DriverGroupId, d.DriverId, d.DriverName,  
 CASE WHEN EXISTS (SELECT AssignmentId FROM rvlfRouteDriverAssignment WHERE DriverId = d.DriverId AND   
  ((CONVERT(DATE, FromDateTime) BETWEEN CONVERT(DATE, @dtFromDateTime) AND CONVERT(DATE, @dtToDateTime)) OR  
  (CONVERT(DATE, ToDateTime) BETWEEN CONVERT(DATE, @dtFromDateTime) AND CONVERT(DATE, @dtToDateTime))) AND   
  ((CONVERT(TIME, FromDateTime) BETWEEN CONVERT(TIME, @dtFromDateTime) AND CONVERT(TIME, @dtToDateTime)) OR  
  (CONVERT(TIME, ToDateTime) BETWEEN CONVERT(TIME, @dtFromDateTime) AND CONVERT(TIME, @dtToDateTime))))   
  THEN 1 ELSE 0 END AS AssignedStatus   
 FROM rvlfDriverMaster d  
 INNER JOIN rvlfDriverGroupAssignment dg ON dg.DriverId = d.DriverId  
 ORDER BY DriverName ASC  
   
 END  
   
   
----------------------Assigned Driver Vehicle List--------------------            
SELECT            
RDA.AssignmentId,            
RDA.DriverId,            
DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),RDA.FromDateTime)) AS FromDateTime,              
DATEADD(HOUR,(@HoursToBeAdded),DATEADD(MINUTE,(@MinsToBeAdded),RDA.ToDateTime)) AS ToDateTime,            
RDA.RouteId,            
RVA.VehicleId            
FROM rvlfRouteDriverAssignment RDA INNER JOIN rvlfRouteVehicleAssignment RVA             
ON RVA.FromDateTime=RDA.FromDateTime             
AND RVA.ToDateTime=RDA.ToDateTime             
AND RDA.RouteId = RVA.RouteId             
AND RDA.AssignedDate = RVA.AssignedDate 

SET NOCOUNT OFF  
END  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_RouteDeviationReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROC [dbo].[rvlf_sp_RouteDeviationReport]                
@bigFleetID bigint = NULL,                              
@intBoxID varchar(max) = NULL,                              
@dtStartDate datetime = NULL,                              
@dtEndDate datetime =NULL,                              
@bigOrganizationID bigint = NULL,                              
@bigQueryingUser bigint = NULL,                
@ItemQty varchar(1)='0'                
AS                                          
/*******************************************************************************************************/                
-- Name  : [rvlf_sp_RouteDeviationReport] 8,null,'2015-07-21 08:00:00.000','2015-07-22 08:00:00.000',6,224,0              
-- Description : To get the Route Deviation details              
-- Created date : 27-Jun-2015                              
-- Created by : Gopalakrishnan.R                              
/*******************************************************************************************************/                                            
BEGIN                                          
SET NOCOUNT ON                                          
                                         
 DECLARE @dtFDate datetime =@dtStartDate   
 DECLARE @dtEDate datetime =@dtEndDate   
 DECLARE @HoursToBeAdded INT = 0   
 DECLARE @MinsToBeAdded INT = 0   
 DECLARE @DefaultDateFormat INT = 0   
                
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                                          
 @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(@bigQueryingUser IS NULL OR @bigQueryingUser='' OR up.UserId = @bigQueryingUser)                                  
 SET @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))         
 SET @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))         
         
Declare @RouteDetails table (Sno int identity(1,1) ,MessageInID uniqueidentifier,BoxId int,OriginDateTime datetime,BoxMsgInTypeId tinyint,
CustomProp varchar(2000),StreetAddress varchar(250),RouteId bigint,StopID bigint,NxtStopID bigint,AlertMsg varchar(3),OrganizationID bigint)            
            
INSERT into @RouteDetails            
select h.MessageInID,h.BoxId,h.OriginDateTime,h.BoxMsgInTypeId,h.CustomProp,h.StreetAddress             
,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'RouteID=',';')            
,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'StopID=',';')            
,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'NxtStopID=',';')            
,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'AlertMsg=',';') ,B.OrganizationId       
from rvlfMsgInHst h            
inner join rvlfVehicleAssignment VA on h.BoxId=VA.BoxId            
inner join rvlfFleetVehicles FV on VA.VehicleId=FV.VehicleId            
inner join rvlfBoxId B on h.BoxId=B.BoxId            
WHERE (OriginDateTime BETWEEN @dtStartDate ANd @dtEndDate) and                             
 (@bigFleetID IS NULL OR @bigFleetID=0 OR FV.FleetId=@bigFleetID) and                
 (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR B.OrganizationId=@bigOrganizationID) and CHARINDEX('34;Route',CustomProp,0)>0          
 order by OriginDateTime        
      
delete from @RouteDetails where AlertMsg in ('101','110')         
--select * from @RouteDetails            
            
DECLARE @RouteDeviated table (Dno int identity(1,1) ,MessageInID uniqueidentifier,BoxId int,OriginDateTime datetime,BoxMsgInTypeId tinyint,
CustomProp varchar(2000),StreetAddress varchar(250),RouteId bigint,StopID bigint,NxtStopID bigint,AlertMsg varchar(3),   
DeviatedStop bigint,EndDateTime datetime,OrganizationID bigint)   
DECLARE @RDetail table (Sno int identity(1,1) ,MessageInID uniqueidentifier,BoxId int,OriginDateTime datetime,BoxMsgInTypeId tinyint,
CustomProp varchar(2000),StreetAddress varchar(250),RouteId bigint,StopID bigint,NxtStopID bigint,AlertMsg varchar(3),
OrganizationID bigint)        
 DECLARE @intBoxLooping int            
 DECLARE @RouteID bigint=null            
 SELECT @intBoxLooping = MIN(Sno) from @RouteDetails                              
         
 WHILE @intBoxLooping IS NOT NULL             
 BEGIN              
 IF((select AlertMsg from @RouteDetails where Sno=@intBoxLooping)='001')            
 BEGIN             
  SELECT @RouteID=RouteId from @RouteDetails where Sno=@intBoxLooping            
 --select 'a',* from @RDetail             
  IF exists(select * from @RDetail)            
     BEGIN        
 --select *  from @RDetail a right join rvlfRouteDetails r on a.StopID=r.LndID where a.Sno is null and r.RouteID=@RouteID             
 -- SELECT MessageInID ,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,RouteId ,StopID ,NxtStopID ,AlertMsg from @RDetail   where AlertMsg='001' and RouteId=@RouteID              
 -- SELECT b.*,r.* from @RDetail a right join rvlfRouteDetails r on a.StopID=r.LndID             
 --join (SELECT MessageInID ,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,RouteId ,StopID ,NxtStopID ,AlertMsg from @    RDetail where AlertMsg='001' and RouteId=@RouteID) as b on r.RouteId=b.RouteId            
 -- where a.Sno is null and r.RouteID=@RouteID             
            
   INSERT INTO @RouteDeviated            
  SELECT b.MessageInID ,b.BoxId,b.OriginDateTime,b.BoxMsgInTypeId,b.CustomProp,b.StreetAddress,b.RouteId ,b.StopID ,b.NxtStopID,        
  b.AlertMsg,r.LndID,null,b.OrganizationID from @RDetail a right join rvlfRouteDetails r on a.StopID=r.LndID         
  INNER join (SELECT MessageInID ,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,RouteId ,StopID ,NxtStopID ,AlertMsg  
  ,OrganizationID        
  from @RDetail where AlertMsg='001' and RouteId=@RouteID) as b on r.RouteId=b.RouteId             
  where a.Sno is null and r.RouteID=@RouteID               
  --SELECT * FROM @RouteDeviated              
  DELETE FROM @RDetail              
  END             
  INSERT INTO @RDetail            
  SELECT MessageInID ,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,RouteId ,StopID ,NxtStopID ,AlertMsg,OrganizationID        
  FROM @RouteDetails where Sno=@intBoxLooping              
 END             
 ELSE IF ((select AlertMsg from @RouteDetails where Sno=@intBoxLooping)='100')            
 BEGIN               
  DECLARE @EndDatetime datetime=null          
  SELECT @RouteID=RouteId ,@EndDatetime=OriginDateTime from @RouteDetails where Sno=@intBoxLooping          
  INSERT INTO @RDetail            
  SELECT MessageInID ,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,RouteId ,StopID ,NxtStopID ,AlertMsg,OrganizationID  
   FROM @RouteDetails where Sno=@intBoxLooping              
  IF exists(select * from @RDetail)            
  BEGIN        
  INSERT INTO @RouteDeviated            
  SELECT b.MessageInID ,b.BoxId,b.OriginDateTime,b.BoxMsgInTypeId,b.CustomProp,b.StreetAddress,b.RouteId ,b.StopID ,b.NxtStopID,        
  b.AlertMsg,r.LndID,@EndDatetime,b.OrganizationID from @RDetail a         
  RIGHT JOIN rvlfRouteDetails r on a.StopID=r.LndID             
  INNER JOIN (SELECT MessageInID ,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,RouteId ,StopID ,NxtStopID ,AlertMsg  
  ,OrganizationID from @RDetail where AlertMsg='001' and RouteId=@RouteID) as b on r.RouteId=b.RouteId             
  where a.Sno is null and r.RouteID=@RouteID               
  --SELECT * FROM @RouteDeviated              
  DELETE FROM @RDetail              
  END             
 END             
 ELSE            
 BEGIN            
   INSERT INTO @RDetail            
  SELECT MessageInID ,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,RouteId ,StopID ,NxtStopID ,AlertMsg,OrganizationID  
   FROM @RouteDetails where Sno=@intBoxLooping            
 END             
 SELECT @intBoxLooping = MIN(Sno) from @RouteDetails WHERE Sno > @intBoxLooping            
 END    
    
     --Details display wihtout comma seperated value.     
--SELECT A.MessageInID ,A.BoxId ,A.OriginDateTime ,A.BoxMsgInTypeId ,A.CustomProp ,A.StreetAddress ,A.RouteId ,A.StopID ,A.NxtStopID ,        
--A.AlertMsg ,A.DeviatedStop ,A.EndDateTime,b.RouteName,c.GeozoneName,TD.DeviatedCnt,DS.Routcnt,DS.iscomplete,V.VehicleDescription,         
--  V.Vin,V.LicensePlate,        
----Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,RVA.FromDateTime)),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,RVA.FromDateTime)) as time),22) as RouteDate,   
--Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.OriginDateTime)),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.OriginDateTime)) as time),22) as RouteStartDate,  
--ISNULL(Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.EndDateTime)),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.EndDateTime)) as time),22),'-') as RouteEndDate,        
--CASE WHEN a.EndDateTime is null THEN '-'         
--ELSE dbo.rvlf_fn_GetHHMMSSFromSec(CAST(DATEDIFF(SECOND,a.OriginDateTime,a.EndDateTime) as bigint)) END AS Duration,        
--Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,         
--Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,         
--Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate        
--FROM @RouteDeviated a          
--INNER JOIN rvlfVehicleAssignment VA on A.BoxId=VA.BoxId         
--INNER JOIN rvlfVehicle V on VA.VehicleId=V.VehicleId        
--INNER JOIN rvlfRouteMaster b on a.RouteId=b.RouteID          
----INNER JOIN rvlfRouteVehicleAssignment RVA on VA.VehicleId=RVA.VehicleId and b.RouteID=RVA.RouteId        
--INNER JOIN rvlfOrganizationGeozone c on a.DeviatedStop=c.GeozoneId and b.OrgID=c.OrganizationId          
--INNER JOIN (select BoxId,MessageInID,OriginDateTime,COUNT(Dno) as Routecnt,COUNT(DeviatedStop) as DeviatedCnt from @RouteDeviated group by BoxId,MessageInID,          
--OriginDateTime ) as TD on  a.MessageInID=TD.MessageInID          
--inner join (          
-- select COUNT(MessageInID) as Routcnt,SUM(IsComplete) as iscomplete ,BoxId from (select distinct BoxId,MessageInID,case when EndDateTime is null then 1 else 0 end as IsComplete from @RouteDeviated group by BoxId,MessageInID,EndDateTime) td1          
--group by td1.BoxId)as DS on a.BoxId=DS.BoxId          
  
 SELECT A.MessageInID ,A.BoxId ,A.OriginDateTime ,A.BoxMsgInTypeId ,A.CustomProp ,A.StreetAddress ,A.RouteId ,A.StopID ,A.NxtStopID ,    
A.AlertMsg  ,A.EndDateTime,b.RouteName,TD.DeviatedCnt,DS.Routcnt,DS.iscomplete,V.VehicleDescription, V.Vin,V.LicensePlate,        
(select count(lndid) as cnt from rvlfRouteDetails rd where rd.RouteId=a.RouteID ) as StopCnt,  
Stuff((SELECT ',' + cast(A1.DeviatedStop as varchar(10)) FROM   @RouteDeviated A1 WHERE  A1.DeviatedStop = A1.DeviatedStop  
and A1.MessageInID=a.MessageInID FOR xml path ('')), 1, 1, '')as DeviatedStop,   
   
 Stuff((SELECT ',' + c1.GeozoneName  FROM   @RouteDeviated A1 INNER JOIN rvlfOrganizationGeozone c1 on A1.DeviatedStop=c1.GeozoneId   
  and A1.OrganizationID=c1.OrganizationId  
  WHERE  A1.DeviatedStop = A1.DeviatedStop and A1.MessageInID=a.MessageInID FOR xml path ('')), 1, 1, '')as GeozoneName,  
    
 Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.OriginDateTime)),@DefaultDateFormat)+ ' '
 + Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.OriginDateTime)) as time),22) as RouteStartDate,  
ISNULL(Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.EndDateTime)),@DefaultDateFormat)+ ' '
+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.EndDateTime)) as time),22),'-') as RouteEndDate, 
       
CASE WHEN a.EndDateTime is null THEN '-'         
ELSE dbo.rvlf_fn_GetHHMMSSFromSec(CAST(DATEDIFF(SECOND,a.OriginDateTime,a.EndDateTime) as bigint)) END AS Duration,        
Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,         
Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,         
Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '
+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,a.OrganizationID  
  
FROM @RouteDeviated a          
INNER JOIN rvlfVehicleAssignment VA on A.BoxId=VA.BoxId         
INNER JOIN rvlfVehicle V on VA.VehicleId=V.VehicleId        
INNER JOIN rvlfRouteMaster b on a.RouteId=b.RouteID   
  
--INNER JOIN rvlfRouteVehicleAssignment RVA on VA.VehicleId=RVA.VehicleId and b.RouteID=RVA.RouteId        
INNER JOIN rvlfOrganizationGeozone c on a.DeviatedStop=c.GeozoneId and b.OrgID=c.OrganizationId          
INNER JOIN (select BoxId,MessageInID,OriginDateTime,COUNT(Dno) as Routecnt,COUNT(DeviatedStop) as DeviatedCnt from @RouteDeviated group by BoxId,MessageInID,          
OriginDateTime ) as TD on  a.MessageInID=TD.MessageInID          
inner join (          
 select COUNT(MessageInID) as Routcnt,SUM(IsComplete) as iscomplete ,BoxId from (select distinct BoxId,MessageInID,
 case when EndDateTime is null then 1 else 0 end as IsComplete from @RouteDeviated group by BoxId,MessageInID,EndDateTime) td1          
group by td1.BoxId)  
as DS on a.BoxId=DS.BoxId         
 group by A.MessageInID ,A.BoxId ,A.OriginDateTime ,A.BoxMsgInTypeId ,A.CustomProp ,A.StreetAddress ,A.RouteId ,A.StopID ,A.NxtStopID ,    
A.AlertMsg  ,A.EndDateTime,b.RouteName,--c.GeozoneName,  
TD.DeviatedCnt,DS.Routcnt,DS.iscomplete,V.VehicleDescription,         
  V.Vin,V.LicensePlate, A.OriginDateTime,A.EndDateTime,a.OrganizationID  
          
SET NOCOUNT OFF                                          
END  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_RouteHistoryDtlsReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================          
-- Author:  Anbarasu.E          
-- Create date: 18-09-2015          
-- Description: Route History Details Report Query          
-- rvlf_sp_RouteHistoryDtlsReport      8,null,'2015-04-20 00:00:00.000','2015-10-20 23:00:00.000',6,224
-- rvlf_sp_RouteHistoryDtlsReport      8,null,'2015-10-06 00:00:00.000','2015-10-10 23:00:00.000',6,18
-- rvlf_sp_RouteHistoryDtlsReport      8,null,'2015-11-01 00:00:00.000','2015-11-02 23:00:00.000',6,18
-- =============================================          
CREATE PROCEDURE [dbo].[rvlf_sp_RouteHistoryDtlsReport]    
 -- Add the parameters for the stored procedure here          
 @bigFleetID   bigint = NULL,                        
 @intBoxID    varchar(max) = NULL,
 @dtStartDate   datetime = NULL,
 @dtEndDate    datetime =NULL,
 @bigOrganizationID  bigint = NULL,
 @bigQueryingUser  bigint = NULL
AS          
BEGIN          
 -- SET NOCOUNT ON added to prevent extra result sets from          
 -- interfering with SELECT statements.          
 --SET NOCOUNT ON;          
           
 DECLARE @dtFDate   datetime	= @dtStartDate             
 DECLARE @dtEDate   datetime	= @dtEndDate             
 DECLARE @HoursToBeAdded	INT = 0             
 DECLARE @MinsToBeAdded		INT = 0             
 DECLARE @DefaultDateFormat INT = 0             
                           
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                                                    
  @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 (@bigQueryingUser IS NULL OR @bigQueryingUser='' OR up.UserId = @bigQueryingUser)                                            
 SET  @dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                   
 SET  @dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))                    
 
 --Select @dtStartDate,@dtEndDate,@dtFDate,@dtEDate,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat

Declare @RouteDetails table (Sno int identity(1,1),MessageInID uniqueidentifier,BoxId int,OriginDateTime datetime,BoxMsgInTypeId tinyint,
CustomProp varchar(2000),StreetAddress varchar(250),RouteId bigint,StopID bigint,NxtStopID bigint,Distance float,AlertMsg varchar(3),OrganizationID bigint)          
          
INSERT INTO @RouteDetails          
select	h.MessageInID,h.BoxId,h.OriginDateTime,h.BoxMsgInTypeId,h.CustomProp,h.StreetAddress           
		,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'RouteID=',';')          
		,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'StopID=',';')          
		,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'NxtStopID=',';')          
		,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Distance=',';')
		----Odometer Values
		--,(Select ((MAX(CAST(dbo.rvlf_fn_GetParamValueWithIndex(mih.CustomProp,'Odometer=',';') AS BIGINT))) - 
		--		 (MIN(CAST(dbo.rvlf_fn_GetParamValueWithIndex(mih.CustomProp,'Odometer=',';') AS BIGINT))))	
		--  from	rvlfMsgInHst mih Where mih.BoxId = @intBoxID and CHARINDEX('Odometer',mih.CustomProp,0) > 0 
		--  and (mih.OriginDateTime BETWEEN @dtStartDate ANd @dtEndDate))
		----
		,dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'AlertMsg=',';') ,B.OrganizationId     
from	rvlfMsgInHst h          
inner	join rvlfVehicleAssignment VA on h.BoxId=VA.BoxId          
inner	join rvlfFleetVehicles FV on VA.VehicleId=FV.VehicleId          
inner	join rvlfBoxId B on h.BoxId=B.BoxId          
where	(OriginDateTime BETWEEN @dtStartDate ANd @dtEndDate) and                           
		(@bigFleetID IS NULL OR @bigFleetID=0 OR FV.FleetId=@bigFleetID) and              
		(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR B.OrganizationId=@bigOrganizationID) and CHARINDEX('34;Route',CustomProp,0)>0
--order	by OriginDateTime      
  
--SELECT * from @RouteDetails 

delete from @RouteDetails where AlertMsg in ('101','110')       

--SELECT Sno,MessageInID,BoxId,OriginDateTime,CustomProp,RouteId,StopID,NxtStopID,AlertMsg FROM @RouteDetails Order by OriginDateTime desc    

--Loop Start--
 DECLARE @RouteDeviated table (Dno int identity(1,1) ,MessageInID uniqueidentifier,BoxId int,OriginDateTime datetime,BoxMsgInTypeId tinyint,
		 CustomProp varchar(2000),StreetAddress varchar(250),RouteId bigint,StopID bigint,NxtStopID bigint,Distance float,AlertMsg varchar(3), DeviatedStop bigint,
		 EndDateTime datetime,OrganizationID bigint)
 DECLARE @RDetail table (Sno int identity(1,1) ,MessageInID uniqueidentifier,BoxId int,OriginDateTime datetime,BoxMsgInTypeId tinyint,
		 CustomProp varchar(2000),StreetAddress varchar(250),RouteId bigint,StopID bigint,NxtStopID bigint,Distance float,AlertMsg varchar(3),OrganizationID bigint)      
 DECLARE @intBoxLooping int          
 SELECT  @intBoxLooping = MIN(Sno) from @RouteDetails                            
 DECLARE @RouteID bigint=null  
 
 WHILE @intBoxLooping IS NOT NULL           
 BEGIN            
	 --SELECT  @intBoxLooping '@intBoxLooping'
	 IF((select AlertMsg from @RouteDetails where Sno=@intBoxLooping)='001')          
	 BEGIN           
		SELECT @RouteID=RouteId from @RouteDetails where Sno=@intBoxLooping          
		--select 'a',* from @RDetail           
		IF exists(select * from @RDetail)          
		BEGIN      
				INSERT	INTO @RouteDeviated          
				SELECT	b.MessageInID,b.BoxId,b.OriginDateTime,b.BoxMsgInTypeId,b.CustomProp,b.StreetAddress,
						b.RouteId,b.StopID,b.NxtStopID,(Select sum(Distance) from @RDetail),b.AlertMsg,r.LndID,null,b.OrganizationID 
				FROM	@RDetail a 
				RIGHT	JOIN rvlfRouteDetails r on a.StopID=r.LndID       
				INNER	JOIN (SELECT MessageInID,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,RouteId,StopID,NxtStopID,AlertMsg,OrganizationID  
							  FROM	 @RDetail WHERE  AlertMsg='001' and RouteId=@RouteID) as b ON r.RouteId=b.RouteId           
				WHERE	a.Sno is null and r.RouteID=@RouteID
				--SELECT 'rdstrt',* FROM @RouteDeviated
				DELETE FROM @RDetail            
		END           
		INSERT INTO @RDetail          
		SELECT MessageInID,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,RouteId,StopID,NxtStopID,Distance,AlertMsg,OrganizationID      
		FROM @RouteDetails where Sno=@intBoxLooping            
	 END           
	 ELSE IF ((select AlertMsg from @RouteDetails where Sno=@intBoxLooping)='100')          
	 BEGIN             
		DECLARE @EndDatetime datetime=null        
		SELECT @RouteID=RouteId ,@EndDatetime=OriginDateTime from @RouteDetails where Sno=@intBoxLooping        
		
		INSERT INTO @RDetail          
		SELECT MessageInID,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,RouteId,StopID,NxtStopID,Distance,AlertMsg,OrganizationID
		FROM @RouteDetails where Sno=@intBoxLooping            
		
		IF exists(select * from @RDetail)          
		BEGIN
			INSERT	INTO @RouteDeviated          			
			SELECT  MessageInID,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,
					a.RouteId,StopID,NxtStopID,(Select sum(Distance) from @RDetail),AlertMsg,Null LndID,@EndDatetime,OrganizationID
			FROM	@RDetail a
			--RIGHT	JOIN rvlfRouteDetails r ON a.StopID=r.LndID --and a.RouteId=r.RouteID
			WHERE	AlertMsg='001' and a.RouteId=@RouteID
			UNION
			--Deviated Routes Fetch
			SELECT	b.MessageInID ,b.BoxId,b.OriginDateTime,b.BoxMsgInTypeId,b.CustomProp,b.StreetAddress,b.RouteId ,b.StopID ,b.NxtStopID,      
					(Select sum(Distance) from @RDetail),b.AlertMsg,r.LndID,@EndDatetime,b.OrganizationID 
			FROM	@RDetail a
			RIGHT	JOIN rvlfRouteDetails r ON a.StopID=r.LndID           
			INNER	JOIN (SELECT MessageInID ,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,RouteId,StopID,NxtStopID,AlertMsg,OrganizationID 
						  FROM	 @RDetail WHERE AlertMsg='001' and RouteId=@RouteID) as b ON r.RouteId=b.RouteId           
			WHERE	a.Sno is null and r.RouteID=@RouteID             
			--SELECT	'rdcomp',* FROM @RouteDeviated            
			DELETE	FROM @RDetail            
		END           
	 END           
	 ELSE          
	 BEGIN          
		INSERT	INTO @RDetail          
		SELECT	MessageInID,BoxId,OriginDateTime,BoxMsgInTypeId,CustomProp,StreetAddress,RouteId,StopID,NxtStopID,Distance,AlertMsg,OrganizationID
		FROM	@RouteDetails where Sno=@intBoxLooping          
		--Select 'inter',* from @RDetail
	 END           
	 SELECT @intBoxLooping = MIN(Sno) from @RouteDetails WHERE Sno > @intBoxLooping          
 END 

 --Loop End--
		--SELECT * FROM @rdetail 
		--SELECT * FROM @routedeviated            

 SELECT A.MessageInID,A.BoxId,A.OriginDateTime,A.BoxMsgInTypeId,A.CustomProp,A.StreetAddress,A.RouteId,A.StopID,A.NxtStopID,A.AlertMsg,A.EndDateTime,
		b.RouteName,DS.Routcnt,DS.iscomplete Complete,(DS.Routcnt - DS.iscomplete) Incomplete,V.VehicleDescription,V.Vin,V.LicensePlate, 
		ISNULL((Select 'Time: '+ CAST (FromDateTime as varchar(20)) + ' - ' + CAST(ToDateTime as varchar(20)) + ' Distance: ' + b.TravelDistance From rvlfRouteVehicleAssignment
		 Where VehicleId = V.VehicleId and RouteId= a.RouteId and (DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.OriginDateTime))) Between FromDateTime And ToDateTime),'-') PlannedDetails,
		a.Distance,(select COUNT(lndid) from rvlfRouteDetails rd where rd.RouteId=a.RouteID) as StopCnt,TD.DeviatedCnt,
		--CASE TD.DeviatedCnt WHEN ((select count(lndid) from rvlfRouteDetails rd1 where rd1.RouteId=a.RouteID) - TD.DeviatedCnt)  THEN 0
		--ELSE TD.DeviatedCnt END AS DeviatedCnt,
		STUFF((SELECT	',' + CAST(A1.DeviatedStop as varchar(10)) FROM   @RouteDeviated A1 
				WHERE	A1.DeviatedStop = A1.DeviatedStop and A1.MessageInID=a.MessageInID FOR xml path ('')), 1, 1, '')	as DeviatedStop,  
		--Stuff((SELECT	',' + c1.GeozoneName  FROM   @RouteDeviated A1 INNER JOIN rvlfOrganizationGeozone c1 on A1.DeviatedStop=c1.GeozoneId 
		--				and A1.OrganizationID=c1.OrganizationId
		--		WHERE	A1.DeviatedStop = A1.DeviatedStop and A1.MessageInID=a.MessageInID FOR xml path ('')), 1, 1, '')as GeozoneName,  
		Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.OriginDateTime)),@DefaultDateFormat)+ ' '+ 
		Convert(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.OriginDateTime)) as time),22) as RouteStartDate,
		ISNULL(Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.EndDateTime)),@DefaultDateFormat)+ ' '+ 
		Convert(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,A.EndDateTime)) as time),22),'-') as RouteEndDate,      
		CASE WHEN a.EndDateTime is null THEN '-'       
		ELSE dbo.rvlf_fn_GetHHMMSSFromSec(CAST(DATEDIFF(SECOND,a.OriginDateTime,a.EndDateTime) as bigint)) END AS Duration,
		TotDur.TotalDuration TotDuration,		--'-' Distance,
		Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,CAST(@dtFDate as time),22) as PasStartDate,       
		Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,CAST(@dtEDate as Time),22) as PasEndDate,       
		Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ 
		Convert(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,a.OrganizationID
FROM	@RouteDeviated a        
INNER	JOIN rvlfVehicleAssignment VA on A.BoxId=VA.BoxId       
INNER	JOIN rvlfVehicle V on VA.VehicleId=V.VehicleId      
INNER	JOIN rvlfRouteMaster b on a.RouteId=b.RouteID 
INNER	JOIN rvlfRouteVehicleAssignment RVA on VA.VehicleId=RVA.VehicleId and b.RouteID=RVA.RouteId      
--INNER	JOIN rvlfOrganizationGeozone c on a.DeviatedStop=c.GeozoneId and b.OrgID=c.OrganizationId        
INNER	JOIN	(select	BoxId,MessageInID,OriginDateTime,COUNT(Dno) as Routecnt,COUNT(DeviatedStop) as DeviatedCnt from @RouteDeviated 
				 group	by BoxId,MessageInID,OriginDateTime) as TD on  a.MessageInID=TD.MessageInID
INNER	JOIN	(select COUNT(MessageInID) as Routcnt,COUNT(CASE IsComplete WHEN 1 THEN NULL ELSE IsComplete END) as iscomplete,BoxId 
				 from	(select distinct BoxId,MessageInID,case when EndDateTime is null then 1 else 0 end as IsComplete 
						 from @RouteDeviated group by BoxId,MessageInID,EndDateTime) td1        
				 group	by td1.BoxId) as DS on a.BoxId=DS.BoxId       
INNER	JOIN	(Select rd.BoxId,dbo.rvlf_fn_GetHHMMSSFromSec(SUM(CAST(DATEDIFF(SECOND,rd.OriginDateTime,rd.EndDateTime) as Bigint))) TotalDuration 						
				 From @RouteDeviated rd  Where rd.DeviatedStop IS NULL Group By rd.BoxId) AS TotDur ON a.BoxId = TotDur.BoxId
GROUP BY	A.MessageInID,A.BoxId,A.OriginDateTime,A.BoxMsgInTypeId,A.CustomProp,A.StreetAddress,A.RouteId,A.StopID,A.NxtStopID,  
			A.AlertMsg,A.EndDateTime,b.RouteName,a.Distance,b.TravelDistance,--c.GeozoneName,
			TD.DeviatedCnt,DS.Routcnt,DS.iscomplete,V.VehicleId,V.VehicleDescription,V.Vin,V.LicensePlate, A.OriginDateTime,a.OrganizationID,TotDur.TotalDuration
ORDER BY	A.OriginDateTime	DESC

--SELECT	rd.BoxId,dbo.rvlf_fn_GetHHMMSSFromSec(SUM(CASE	WHEN rd.EndDateTime IS NULL 
--														THEN (CAST(DATEDIFF(SECOND,rd.OriginDateTime,rd.OriginDateTime) as Bigint))
--														ELSE (CAST(DATEDIFF(SECOND,rd.OriginDateTime,rd.EndDateTime) as Bigint)) END)) duration
--FROM	@RouteDeviated rd Where DeviatedStop IS NULL 
--GROUP BY rd.BoxId
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_Save_notificationsList]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Procedure [dbo].[rvlf_sp_Save_notificationsList]
		@tblNotificationList as NotificaitonUserList READONLY,
		@tiNotificationType tinyint = null,
		@bigTypeID bigint = null
AS
/******************************************************************************/
--	Name		:	rvlf_sp_Save_notificationsList
--	Description	:	To save the list of users to whonm the notificaiton has to be given.
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	16-Sep-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	DECLARE @ErrorMessage varchar(800)
	BEGIN TRAN MessageTransaction
	BEGIN TRY
	
		DELETE FROM rvlfNotificationList WHERE NotificationType = @tiNotificationType AND TypeID = @bigTypeID
		
		INSERT INTO rvlfNotificationList (UserID, NotificationType, TypeID, Email, SMS,CreateDateTime)
			SELECT tn.UserID, @tiNotificationType, @bigTypeID, tn.Email, tn.SMS,getutcdate() FROM @tblNotificationList As tn
		
		COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during insert of the packet message : ' + ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END

--exec rvlf_sp_GetUserDetails @bigOrganizationID = 1

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAccidentDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveAccidentDetails]  
@nAccidentId INT = NULL,  
@nFleetId BIGINT = NULL,  
@nVehicleId BIGINT = NULL,  
@nDriverId BIGINT = NULL,  
@nAccidentTypeId INT = NULL,  
@dAccidentDate DATETIME = NULL,  
@vLocation VARCHAR(50) = NULL,  
@nTrip TINYINT = NULL,  
@vRouteName VARCHAR(50) = NULL,  
@vSupervisorName VARCHAR(50) = NULL,  
@nAccidentReasonId INT = NULL,  
@bIsAnyOneInjured BIT = NULL,  
@vAnyOneInjuredComments VARCHAR(250) = NULL,  
@nNoOfPassengers TINYINT = NULL,  
@nNoOfPassengersInjured TINYINT = NULL,  
@vDamageDetails VARCHAR(250) = NULL,  
@vDamageCost VARCHAR(20) = NULL,  
@vCompensationPaid VARCHAR(250) = NULL,  
@bIsInsuraceCoverage BIT = NULL,  
@bIsInsuranceClaimed BIT = NULL,  
@vInsuranceComents VARCHAR(250) = NULL,  
@vClaimedCost VARCHAR(20) = NULL,  
@dClaimedOn DATETIME = NULL,  
@nCorrectiveActionId INT = NULL,  
@vActionTaken VARCHAR(250) = NULL,  
@nOrganizationId BIGINT = NULL,  
@nUserId INT = NULL,  
@nOperationType TINYINT = NULL  
AS  
/*************************************************************************************        
Procedure Name  : rvlf_sp_SaveAccidentDetails  
Purpose     : Save accident details  
Created by    : Sakthi Gopinath S  
Created date   : 2014-Sep-25  
**************************************************************************************/        
BEGIN  
SET NOCOUNT ON  
 IF @nOperationType = 1  
 BEGIN  
  INSERT INTO dbo.rvlfAccidentDetails(FleetId,VehicleId,DriverId,AccidentTypeId,AccidentDate,Location,Trip,RouteName,SupervisorName,   
  AccidentReasonId,IsAnyOneInjured,AnyOneInjuredComments,NoOfPassengers,NoOfPassengersInjured,DamageDetails,DamageCost,CompensationPaid,  
  IsInsuraceCoverage,IsInsuranceClaimed,InsuranceComents, ClaimedCost,ClaimedOn,CorrectiveActionId,ActionTaken, OrganizationId,CreatedBy,  
  CreatedDate,ModifiedBy,ModifiedDate,IsDelete) VALUES  
  (@nFleetId,@nVehicleId,@nDriverId,@nAccidentTypeId,@dAccidentDate,@vLocation,@nTrip,@vRouteName,@vSupervisorName,@nAccidentReasonId,  
  @bIsAnyOneInjured,@vAnyOneInjuredComments,@nNoOfPassengers,@nNoOfPassengersInjured,@vDamageDetails,@vDamageCost,  
  @vCompensationPaid,@bIsInsuraceCoverage,@bIsInsuranceClaimed,@vInsuranceComents,@vClaimedCost,@dClaimedOn,@nCorrectiveActionId,  
  @vActionTaken,@nOrganizationId,@nUserId,GETUTCDATE(),NULL,NULL,0)  
 END  
 ELSE IF @nOperationType = 2  
 BEGIN  
  UPDATE dbo.rvlfAccidentDetails SET AccidentTypeId=@nAccidentTypeId,Trip=@nTrip,RouteName=@vRouteName,SupervisorName=@vSupervisorName,  
  AccidentReasonId=@nAccidentReasonId,IsAnyOneInjured=@bIsAnyOneInjured,AnyOneInjuredComments=@vAnyOneInjuredComments,  
  NoOfPassengers=@nNoOfPassengers,NoOfPassengersInjured=@nNoOfPassengersInjured,DamageDetails=@vDamageDetails,  
  DamageCost=@vDamageCost,CompensationPaid=@vCompensationPaid,IsInsuraceCoverage=@bIsInsuraceCoverage,IsInsuranceClaimed=@bIsInsuranceClaimed,  
  InsuranceComents=@vInsuranceComents,ClaimedCost=@vClaimedCost,ClaimedOn=@dClaimedOn,CorrectiveActionId=@nCorrectiveActionId,  
  ActionTaken=@vActionTaken,ModifiedBy=@nUserId,ModifiedDate=GETUTCDATE()   
  WHERE AccidentId=@nAccidentId  
 END  
 ELSE IF @nOperationType = 3  
 BEGIN  
  UPDATE dbo.rvlfAccidentDetails SET IsDelete=1,ModifiedBy=@nUserId,ModifiedDate=GETUTCDATE() WHERE AccidentId=@nAccidentId  
 END  
SET NOCOUNT OFF  
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAdhocServices]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE Procedure [dbo].[rvlf_sp_SaveAdhocServices]  
   
@bigVehicleId bigint,  
@dtExecutionOnDate Datetime,  
@nTotalServiceCost Numeric(18,2),  
@vcComments Varchar(250),  
@tblAdhocServices XML =NULL, 
--@tblAdhocServices AS AdhocServices READONLY,  
@CreatedBy bigint,  
@CreatedDateTime Datetime=null,
@Serviceimage1 nvarchar(max)=null,
@Serviceimage2  nvarchar(max)=null,
@ServicedBy  bigint 
  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_SaveAdhocServices  
-- Description : To save the Adhoc Maintenance Services  
-- Author  : Kumuthini. L  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 02-Feb-2010 LK Created Intial Version   
/******************************************************************************/  
BEGIN  
SET NOCOUNT ON   
 -- Local variables to hold the intermediate results  
 if(@CreatedDateTime is null)
 begin
	set @CreatedDateTime=GETUTCDATE()
 end
 DECLARE @ErrorMessage varchar(3000)  
 DECLARE @docHandle int   
 DECLARE  @tblAdhocServicesXML TABLE (ServiceId bigint,ServiceCost Numeric(18,2) ) 
 BEGIN TRAN AdhocServicesTransaction  
 BEGIN TRY  
   
   IF @tblAdhocServices IS NOT NULL             
 BEGIN                                
  EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblAdhocServices                                         
  INSERT INTO @tblAdhocServicesXML                                                      
  SELECT * FROM OPENXML(@docHandle, '/DocumentElement/AdhocServices')               
  WITH                 
  (                         
  ServiceId bigint 'ServiceId'                          
  ,ServiceCost  Numeric(18,2)  'ServiceCost'           
  )          
            
  declare @tblVehiclePlanDetails1 As AdhocServices          
  insert into  @tblVehiclePlanDetails1              
  select * from @tblAdhocServicesXML              
 END   
 
  DECLARE @bigAdhocServiceId AS BIGINT  
    
  IF EXISTS (SELECT VehicleId FROM rvlfAdhocServices WHERE VehicleId = @bigVehicleId AND ExecutionOn = @dtExecutionOnDate)  
  BEGIN  
    
   RAISERROR('The adhoc services for the vehicle on the selected execution on date already exists.',16,1)  
    
  END  
  ELSE  
  BEGIN  
    
   INSERT INTO rvlfAdhocServices (VehicleId, ExecutionOn, TotalServiceCost, Comments, CreatedBy, CreatedDateTime,Photo1,Photo2,ServicedBy)  
   VALUES (@bigVehicleId, @dtExecutionOnDate, @nTotalServiceCost, @vcComments, @CreatedBy, @CreatedDateTime,@Serviceimage1,@Serviceimage2,@ServicedBy)  
     
   SET @bigAdhocServiceId = @@IDENTITY  
     
   INSERT INTO rvlfAdhocServiceDetails (AdhocServiceId, ServiceId, ServiceCost)  
    SELECT @bigAdhocServiceId, ServiceId, ServiceCost FROM @tblAdhocServicesXML  
      
     END  
    select @bigAdhocServiceId as 'ServiceLogID'
  COMMIT TRAN  
 END TRY  
 BEGIN CATCH  
  ROLLBACK TRAN   
  SET @ErrorMessage = ERROR_MESSAGE()  
  RAISERROR( @ErrorMessage,16,1)  
 END CATCH  
SET NOCOUNT OFF  
END  
  
  
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAndDeleteMDTFormMessages]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveAndDeleteMDTFormMessages]
@vehID int = null,
@MsgCode int = null,
@MsgName varchar(150) = null,
@Answer varchar(25) = '',
@Title varchar(20)=null,
@Userid int = null,
@Operation int = null,
@typeId smallint = null,
@OrgId int = 6
AS
/*****************************************************************************************
PROCEDURE NAME : rvlf_sp_SaveAndDeleteMDTFormMessages 180,null,null,'',null,94,4
CREATED BY	 : Sakthi Gopinath S
CREATED DATE : 11-Aug-2012
*****************************************************************************************/
BEGIN
SET NOCOUNT ON
	DECLARE @boxID bigint
	SELECT @boxID=va.BoxId FROM rvlfVehicleAssignment va INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId
	WHERE v.VehicleId=@vehID
	IF @Operation = 1 -- Save form message
	BEGIN
		IF (SELECT COUNT(FormMsgId) FROM rvlfMDTFormMessages WHERE OrganizationId=@OrgId) = 0 
		BEGIN SET @MsgCode = 1 END
		ELSE BEGIN	SELECT @MsgCode = MAX(FormMsgId)+1 FROM rvlfMDTFormMessages WHERE OrganizationId=@OrgId END
		IF @typeId IS NULL OR @typeId = 1
		BEGIN
			INSERT INTO rvlfMDTFormMessages(FormMsgId,MsgName,Answer,CreatedDate,CreatedBy,BoxID,IsDelete,Title,OrganizationId,TypeId)
			VALUES(@MsgCode,@MsgName,@Answer,GETUTCDATE(),@Userid,0,0,@Title,@OrgId,@typeId)
		END
		ELSE IF @typeId = 2
		BEGIN
			INSERT INTO rvlfMDTFormMessages(FormMsgId,MsgName,Answer,CreatedDate,CreatedBy,BoxID,IsDelete,Title,
			OrganizationId,TypeId)
			VALUES(@MsgCode,@MsgName,@Answer,GETUTCDATE(),@Userid,0,0,@Title,@OrgId,@typeId)
		END
		SELECT CASE WHEN @@ROWCOUNT > 0 THEN 'Success' ELSE 'Failure' END 
	END
	ELSE IF @Operation = 2 -- Delete a form message
	BEGIN
		DELETE rvlfMDTFormMessages WHERE OrganizationId=@OrgId AND MsgNo=@MsgCode 
		--(SELECT MsgNo FROM rvlfMDTFormMessages WHERE OrganizationId=@OrgId AND FormMsgId=@MsgCode)
		SELECT CASE WHEN @@ROWCOUNT > 0 THEN 'Success' ELSE 'Failure' END 
	END
	ELSE IF @Operation = 3 --Delete all form messages
	BEGIN
		DELETE rvlfMDTFormAssigned WHERE VehicleId=@vehID 
		SELECT CASE WHEN @@ROWCOUNT > 0 THEN 'Success' ELSE 'Failure' END 
	END
	ELSE IF @Operation = 4 --Get all the form messages
	BEGIN
		SELECT MsgNo,FormMsgId,Title,MsgName,
		CASE WHEN EXISTS (SELECT TOP 1 MsgNo FROM rvlfMDTFormAssigned MF INNER JOIN rvlfVehicle v ON v.VehicleId=MF.VehicleId 
		WHERE MsgNo=FM.FormMsgId AND v.OrganizationId=@OrgId) 
		THEN 'False' ELSE 'True' END AS IsAssigned,
		CASE WHEN TypeId = 1 THEN 'Single' ELSE 'Multiple' END AS TypeName
		FROM rvlfMDTFormMessages FM WHERE OrganizationId=@OrgId AND IsDelete=0
		IF @vehID IS NOT NULL
		BEGIN
			SELECT MsgNo,FormMsgId,Title,
			(CASE WHEN EXISTS (SELECT MsgNo FROM rvlfMDTFormAssigned WHERE VehicleId=@vehID AND MsgNo=FM.FormMsgId) THEN 1 ELSE 0 END) 
			AS IsAssigned FROM rvlfMDTFormMessages FM WHERE OrganizationId=@OrgId ORDER BY Title ASC
			
			SELECT COUNT(MsgNo) AS AssignedCount,CASE WHEN COUNT(MsgNo) >= 11 THEN 0 ELSE 1 END AS IsValid FROM rvlfMDTFormAssigned WHERE VehicleId=@vehID
		END
	END
	ELSE IF @Operation = 5 --Get the maximum msg code and group id
	BEGIN
		DECLARE @typId smallint 
		SELECT @typId=TypeId FROM rvlfMDTFormMessages WHERE OrganizationId=@OrgId AND FormMsgId=@MsgCode
		IF 	@typId = 1 
		BEGIN
			SELECT CASE WHEN A.No_Of_Line = 0 THEN 1 WHEN A.No_Of_Line>3 THEN 3 ELSE A.No_Of_Line END AS [No_Of_Line],A.Title,
			A.[Line 1],A.[Line 2],A.[Line 3],
			DATALENGTH(A.[Line 1]) AS [Length 1],DATALENGTH(A.[Line 2]) AS [Length 2],DATALENGTH(A.[Line 3]) AS [Length 3],
			CASE WHEN CHARINDEX(A.[Line 1],A.MsgName) <= 0 THEN 1 ELSE CHARINDEX(A.[Line 1],A.MsgName) END AS Pos_Line1,
			CASE WHEN (CHARINDEX(A.[Line 2],A.MsgName) - 25) <= 0 THEN 1 ELSE (CHARINDEX(A.[Line 2],A.MsgName) - 25) END AS Pos_Line2,
			CASE WHEN (CHARINDEX(A.[Line 3],A.MsgName) - 50) <= 0 THEN 1 ELSE (CHARINDEX(A.[Line 3],A.MsgName) - 50) END AS Pos_Line3,A.MsgName,
			A.ValidAns1,A.AnswerStartIndex1,(A.AnswerEndIndex1-A.AnswerStartIndex1) AS AnswerLength1,
			A.ValidAns2,A.AnswerStartIndex2,(A.AnswerEndIndex2-A.AnswerStartIndex2) AS AnswerLength2,
			A.ValidAns3,A.AnswerStartIndex3,(A.AnswerEndIndex3-A.AnswerStartIndex3) AS AnswerLength3,
			(A.ValidAns1+A.ValidAns2+A.ValidAns3) AS [Ans_Occ_Count],
			CASE WHEN CHARINDEX('-',A.MsgName) <> 0 THEN 'S' WHEN CHARINDEX('$',A.MsgName) <> 0 THEN 'N' 
			WHEN CHARINDEX('@',A.MsgName) <> 0 THEN 'D' ELSE 'S' END AS AnswerType,A.OrganizationId,A.FormMsgId,A.MsgNo FROM 
			(SELECT OrganizationId,FormMsgId,MsgNo,Title,CEILING(LEN(MsgName)/25.00) AS No_Of_Line,
			RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(SUBSTRING(MsgName,1,25),'$',''),'@',''),'-',''))) AS [Line 1],
			RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(SUBSTRING(MsgName,26,25),'$',''),'@',''),'-',''))) AS [Line 2],
			RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(SUBSTRING(MsgName,51,25),'$',''),'@',''),'-',''))) AS [Line 3],MsgName,
			CASE WHEN CHARINDEX('-',REPLACE(REPLACE(SUBSTRING(MsgName,1,25),'$','-'),'@','-'),0) = 0 THEN 0 ELSE 1 END AS ValidAns1,
			CHARINDEX('-',REPLACE(REPLACE(SUBSTRING(MsgName,1,25),'$','-'),'@','-'),0) AS AnswerStartIndex1,
			(LEN(SUBSTRING(MsgName,1,25))-(CHARINDEX('-', REVERSE(REPLACE(REPLACE(SUBSTRING(MsgName,1,25),'$','-'),'@','-')))-2)) AS AnswerEndIndex1,
			CASE WHEN CHARINDEX('-',REPLACE(REPLACE(SUBSTRING(MsgName,26,25),'$','-'),'@','-'),0) = 0 THEN 0 ELSE 1 END AS ValidAns2,
			CHARINDEX('-',REPLACE(REPLACE(SUBSTRING(MsgName,26,25),'$','-'),'@','-'),0) AS AnswerStartIndex2,
			(LEN(SUBSTRING(MsgName,26,25))-(CHARINDEX('-', REVERSE(REPLACE(REPLACE(SUBSTRING(MsgName,26,25),'$','-'),'@','-')))-2)) AS AnswerEndIndex2,
			CASE WHEN CHARINDEX('-',REPLACE(REPLACE(SUBSTRING(MsgName,51,25),'$','-'),'@','-'),0) = 0 THEN 0 ELSE 1 END AS ValidAns3,
			CHARINDEX('-',REPLACE(REPLACE(SUBSTRING(MsgName,51,25),'$','-'),'@','-'),0) AS AnswerStartIndex3,
			(LEN(SUBSTRING(MsgName,51,25))-(CHARINDEX('-', REVERSE(REPLACE(REPLACE(SUBSTRING(MsgName,51,25),'$','-'),'@','-')))-2)) AS AnswerEndIndex3
			FROM rvlfMDTFormMessages) A WHERE A.OrganizationId=@OrgId AND A.FormMsgId=@MsgCode
		END
		ELSE 
		BEGIN
			SELECT CASE WHEN A.No_Of_Line = 0 THEN 1 WHEN A.No_Of_Line>3 THEN 3 ELSE A.No_Of_Line END AS [No_Of_Line],A.Title,
			A.[Line 1],A.[Line 2],A.[Line 3],
			DATALENGTH(A.[Line 1]) AS [Length 1],DATALENGTH(A.[Line 2]) AS [Length 2],DATALENGTH(A.[Line 3]) AS [Length 3],
			CASE WHEN CHARINDEX(A.[Line 1],A.MsgName) <= 0 THEN 1 ELSE CHARINDEX(A.[Line 1],A.MsgName) END AS Pos_Line1,
			CASE WHEN (CHARINDEX(A.[Line 2],A.MsgName) - 30) <= 0 THEN 1 ELSE (CHARINDEX(A.[Line 2],A.MsgName) - 30) END AS Pos_Line2,
			CASE WHEN (CHARINDEX(A.[Line 3],A.MsgName) - 60) <= 0 THEN 1 ELSE (CHARINDEX(A.[Line 3],A.MsgName) - 60) END AS Pos_Line3,A.MsgName,
			A.ValidAns1,A.AnswerStartIndex1,(A.AnswerEndIndex1-A.AnswerStartIndex1) AS AnswerLength1,
			A.ValidAns2,A.AnswerStartIndex2,(A.AnswerEndIndex2-A.AnswerStartIndex2) AS AnswerLength2,
			A.ValidAns3,A.AnswerStartIndex3,(A.AnswerEndIndex3-A.AnswerStartIndex3) AS AnswerLength3,
			(A.ValidAns1+A.ValidAns2+A.ValidAns3) AS [Ans_Occ_Count],
			CASE WHEN CHARINDEX('-',A.MsgName) <> 0 THEN 'S' WHEN CHARINDEX('$',A.MsgName) <> 0 THEN 'N' 
			WHEN CHARINDEX('@',A.MsgName) <> 0 THEN 'D' ELSE 'S' END AS AnswerType,A.OrganizationId,A.FormMsgId,A.MsgNo FROM 
			(SELECT OrganizationId,FormMsgId,MsgNo,Title,CEILING(LEN(MsgName)/30.00) AS No_Of_Line,
			RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(SUBSTRING(MsgName,1,30),'$',''),'@',''),'-',''))) AS [Line 1],
			RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(SUBSTRING(MsgName,30,30),'$',''),'@',''),'-',''))) AS [Line 2],
			RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(SUBSTRING(MsgName,61,30),'$',''),'@',''),'-',''))) AS [Line 3],MsgName,
			CASE WHEN CHARINDEX('-',REPLACE(REPLACE(SUBSTRING(MsgName,1,30),'$','-'),'@','-'),0) = 0 THEN 0 ELSE 1 END AS ValidAns1,
			CHARINDEX('-',REPLACE(REPLACE(SUBSTRING(MsgName,1,30),'$','-'),'@','-'),0) AS AnswerStartIndex1,
			(30-(CHARINDEX('-', REVERSE(REPLACE(REPLACE(SUBSTRING(MsgName,1,30),'$','-'),'@','-')))-2)) AS AnswerEndIndex1,
			CASE WHEN CHARINDEX('-',REPLACE(REPLACE(SUBSTRING(MsgName,31,30),'$','-'),'@','-'),0) = 0 THEN 0 ELSE 1 END AS ValidAns2,
			CHARINDEX('-',REPLACE(REPLACE(SUBSTRING(MsgName,31,30),'$','-'),'@','-'),0) AS AnswerStartIndex2,
			(30-(CHARINDEX('-', REVERSE(REPLACE(REPLACE(SUBSTRING(MsgName,31,30),'$','-'),'@','-')))-2)) AS AnswerEndIndex2,
			CASE WHEN CHARINDEX('-',REPLACE(REPLACE(SUBSTRING(MsgName,61,30),'$','-'),'@','-'),0) = 0 THEN 0 ELSE 1 END AS ValidAns3,
			CHARINDEX('-',REPLACE(REPLACE(SUBSTRING(MsgName,61,30),'$','-'),'@','-'),0) AS AnswerStartIndex3,
			(30-(CHARINDEX('-', REVERSE(REPLACE(REPLACE(SUBSTRING(MsgName,61,30),'$','-'),'@','-')))-2)) AS AnswerEndIndex3
			FROM rvlfMDTFormMessages) A WHERE A.OrganizationId=@OrgId AND A.FormMsgId=@MsgCode	
		END
	END
	ELSE IF @Operation = 6 --Assign forms to vehicles
	BEGIN
		INSERT INTO rvlfMDTFormAssigned(MsgNo,VehicleId) VALUES(@MsgCode,@vehID)
		SELECT CASE WHEN @@ROWCOUNT > 0 THEN 'Success' ELSE 'Failure' END 
	END
	ELSE IF @Operation =7 --Delete a single assigned forms
	BEGIN
		DELETE rvlfMDTFormAssigned WHERE VehicleId=@vehID AND MsgNo=@MsgCode
		SELECT CASE WHEN @@ROWCOUNT > 0 THEN 'Success' ELSE 'Failure' END 
	END
	ELSE IF @Operation =8 --Update a single message
	BEGIN
		UPDATE rvlfMDTFormMessages SET Title=@Title,MsgName=@MsgName WHERE MsgNo=@MsgCode
		SELECT CASE WHEN @@ROWCOUNT > 0 THEN 'Success' ELSE 'Failure' END 
	END
	ELSE IF @Operation =9 --Get a single message
	BEGIN
		SELECT Title,MsgName FROM rvlfMDTFormMessages WHERE MsgNo=@MsgCode
	END
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAndEditAndDelteRouteInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveAndEditAndDelteRouteInfo]          
 @bitIsDelete bit=null,          
 @sintRouteId smallint = Null,          
 @vcRouteName varchar(20)=null,          
 @vcRouteDesc varchar(250)=null,          
 @vcLanadmaekIds varchar(MAX)=null,          
 @vcSeqNos varchar(MAX)=null,            
 @bigOrganizationID bigint = null,          
 @vcDurations varchar(100)=null,        
 @vcTravelDuration varchar(20)=null,        
 @vcTravelDistance varchar(20)=null          
AS          
/****************************************************************************************************************/          
-- Name  : [rvlf_sp_SaveAndEditAndDelteRouteInfo]          
-- Description : To save,edit and delete the route details          
-- Author  : V.Narayanasamy          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : 26-Sep-2010 VN Created Intial Version           
--   : 27-Jan-2012 Vijay Added Travel duration and Travel distance to the table and in insert and update query.        
/****************************************************************************************************************/          
BEGIN          
          
           
 IF(@bitIsDelete=1)          
  BEGIN           
   DELETE rvlfRouteMaster WHERE RouteID=@sintRouteId AND OrgID=@bigOrganizationID           
   DELETE rvlfRouteDetails WHERE RouteID=@sintRouteId           
  END          
 ELSE          
  BEGIN          
   DECLARE @TBL TABLE          
(          
 LAND VARCHAR(5),          
 SEQNO VARCHAR(5),          
 DURATION VARCHAR(5)          
           
)          
DECLARE @SEQ TABLE          
( Id int identity,          
 SEQNO VARCHAR(5)          
)          
DECLARE @DUR TABLE          
(           
 Id int identity,          
 DURATION VARCHAR(5)           
)          
INSERT INTO @TBL (LAND)          
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcLanadmaekIds,',')          
INSERT INTO @SEQ (SEQNO)          
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcSeqNos,',')          
INSERT INTO @DUR (DURATION)          
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcDurations,',')          
          
DECLARE @INC INT=(SELECT COUNT(*)  FROM @TBL)          
Print @INC          
DECLARE @I INT=1          
WHILE @I< @INC+1          
 BEGIN          
            
  Update top (1) @TBL Set SEQNO=(Select SEQNO from @SEQ where Id=@I)   where SEQNO is null          
  Update top (1) @TBL Set DURATION =(Select DURATION  from @DUR where Id=@I)   where DURATION is null          
  Set @I=@I+1          
 END          
   IF(@sintRouteId>0)          
    BEGIN          
     UPDATE rvlfRouteMaster SET RouteName=@vcRouteName,RouteDescription=@vcRouteDesc,TravelDuration = @vcTravelDuration,TravelDistance = @vcTravelDistance        
      WHERE RouteID=@sintRouteId AND OrgID=@bigOrganizationID           
                
     DELETE rvlfRouteDetails WHERE RouteID=@sintRouteId           
               
     INSERT INTO rvlfRouteDetails(RouteID,LndID,SeqID,duration)          
      SELECT @sintRouteId,LAND,SEQNO,DURATION from @TBL           
    END           
   ELSE          
    BEGIN    
     declare @GRouteId int  
    select @GRouteId= MAX(GrouteId) from rvlfRouteMaster where OrgID=@bigOrganizationID  
             
     INSERT INTO rvlfRouteMaster(RouteName,RouteDescription,TravelDuration,TravelDistance,OrgID,GrouteId)      
      VALUES(@vcRouteName,@vcRouteDesc,@vcTravelDuration,@vcTravelDistance,@bigOrganizationID,(ISNULL(@GRouteId,0)+1))      
     declare @rouid smallint= @@IDENTITY                    
     INSERT INTO rvlfRouteDetails(RouteID,LndID,SeqID,duration)          
      SELECT @rouid,LAND,SEQNO,DURATION from @TBL           
    END          
  END          
END		

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAndEditAndDelteRouteInfo_WithDistnce]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[rvlf_sp_SaveAndEditAndDelteRouteInfo_WithDistnce]              
 @bitIsDelete bit=null,              
 @sintRouteId smallint = Null,              
 @vcRouteName varchar(30)=null,              
 @vcRouteDesc varchar(250)=null,              
 @vcLanadmaekIds varchar(1000)=null,              
 @vcSeqNos varchar(100)=null,                
 @bigOrganizationID bigint = null,              
 @vcDurations varchar(1000)=null,            
 @vcDurationsec varchar(1000)=null,            
 @vcTravelDuration varchar(20)=null,            
 @vcTravelDistance varchar(20)=null,              
 @vcDistance varchar(1000)=null ,        
 @vcTrafficDuration varchar(1000) = null,         
 @vcHaultTime varchar(1000) = null,         
 @vcBufferTime varchar(1000) = null,        
 @bitIsCircularTrip bit = null
AS              
/****************************************************************************************************************/              
-- Name  : [rvlf_sp_SaveAndEditAndDelteRouteInfo_WithDistnce_Test]              
-- Description : To save,edit and delete the route details              
-- Author  : V.Narayanasamy              
-- Company  : Angler Technologies              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
--    : 26-Sep-2010 VN Created Intial Version               
--   : 27-Jan-2012 Vijay Added Travel duration and Travel distance to the table and in insert and update query.            
--  : Added Individual Distance and Duration in Table        
/****************************************************************************************************************/              
BEGIN              
              
               
 IF(@bitIsDelete=1)              
  BEGIN               
   DELETE rvlfRouteMaster WHERE RouteID=@sintRouteId AND OrgID=@bigOrganizationID               
   DELETE rvlfRouteDetails WHERE RouteID=@sintRouteId               
  END              
 ELSE              
  BEGIN              
   DECLARE @TBL TABLE              
(              
 LAND VARCHAR(5),              
 SEQNO VARCHAR(5),              
 DURATION VARCHAR(50),        
 DURATIONSEC VARCHAR(50),        
 DISTANCE VARCHAR(50),        
 TRAFFICDURATION VARCHAR(50),      
 BuffDURATION VARCHAR(50),      
 HaltDURATION VARCHAR(50)      
)              
DECLARE @SEQ TABLE              
( Id int identity,              
 SEQNO VARCHAR(5)              
)              
DECLARE @DUR TABLE              
(               
 Id int identity,              
 DURATION VARCHAR(50)               
)              
DECLARE @DURSec TABLE              
(               
 Id int identity,              
 DURATION VARCHAR(50)               
)      
DECLARE @DIS TABLE              
(               
 Id int identity,              
 DISTANCE VARCHAR(50)               
)          
        
  DECLARE @Buff TABLE              
(               
 Id int identity,              
 DURATION VARCHAR(50)               
)              
        
DECLARE @Halt TABLE              
(               
 Id int identity,              
 DURATION VARCHAR(50)               
)          
      
--DECLARE @TRAFFICDIS TABLE              
--(               
-- Id int identity,              
-- TRAFFICDURATION VARCHAR(50)               
--)          
        
        
INSERT INTO @TBL (LAND)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcLanadmaekIds,',')              
INSERT INTO @SEQ (SEQNO)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcSeqNos,',')              
INSERT INTO @DUR (DURATION)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcDurations,',')     
INSERT INTO @DURSec (DURATION)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcDurationsec,',')             
INSERT INTO @DIS (DISTANCE)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcDistance,',')              
INSERT INTO @Buff (DURATION)      
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcBufferTime,',')              
INSERT INTO @Halt (DURATION)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcHaultTime,',')              
--INSERT INTO @TRAFFICDIS (TRAFFICDURATION)              
--SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcTrafficDuration,',')          
              
DECLARE @INC INT=(SELECT COUNT(*)  FROM @TBL)              
Print @INC              
DECLARE @I INT=1              
WHILE @I< @INC+1              
 BEGIN              
                
  Update top (1) @TBL Set SEQNO=(Select SEQNO from @SEQ where Id=@I)   where SEQNO is null              
  Update top (1) @TBL Set DURATION =(Select DURATION  from @DUR where Id=@I)   where DURATION is null        
  Update top (1) @TBL Set DURATIONSEC =(Select DURATION  from @DURSec where Id=@I)   where DURATIONSEC is null        
  update top (1) @TBL set DISTANCE =(Select DISTANCE  from @DIS where Id=@I)   where DISTANCE is null        
  Update top (1) @TBL Set HaltDURATION =(Select DURATION  from @Halt where Id=@I)   where HaltDURATION is null      
  Update top (1) @TBL Set BuffDURATION =(Select DURATION  from @Buff where Id=@I)   where BuffDURATION is null      
--  update top (1) @TBL set TRAFFICDURATION =(Select TRAFFICDURATION  from @TRAFFICDIS where Id=@I)   where TRAFFICDURATION is null        
  Set @I=@I+1              
 END              
   IF(@sintRouteId>0)              
    BEGIN              
     UPDATE rvlfRouteMaster SET RouteName=@vcRouteName,RouteDescription=@vcRouteDesc,TravelDuration = @vcTravelDuration,        
     TravelDistance = @vcTravelDistance,TrafficDuration = @vcTrafficDuration, IsCircularTrip = @bitIsCircularTrip             
      WHERE RouteID=@sintRouteId AND OrgID=@bigOrganizationID               
                    
     DELETE rvlfRouteDetails WHERE RouteID=@sintRouteId               
                   
     INSERT INTO rvlfRouteDetails(RouteID,LndID,SeqID,duration,Distance,HaltTime,BufferTime,DurationSec)              
      SELECT @sintRouteId,LAND,SEQNO,DURATION,DISTANCE,HaltDURATION,BuffDURATION,DURATIONSEC from @TBL               
    END               
   ELSE              
    BEGIN               
    declare @GRouteId int          
    select @GRouteId= MAX(GrouteId) from rvlfRouteMaster where OrgID=@bigOrganizationID          
                    
     INSERT INTO rvlfRouteMaster(RouteName,RouteDescription,TravelDuration,TravelDistance,OrgID,GrouteId,TrafficDuration,IsCircularTrip)              
      VALUES(@vcRouteName,@vcRouteDesc,@vcTravelDuration,@vcTravelDistance,@bigOrganizationID,(ISNULL(@GRouteId,0)+1),@vcTrafficDuration,@bitIsCircularTrip)              
     declare @rouid smallint= @@IDENTITY                        
     INSERT INTO rvlfRouteDetails(RouteID,LndID,SeqID,duration,Distance,HaltTime,BufferTime,DurationSec)           
      SELECT @rouid,LAND,SEQNO,DURATION,DISTANCE,HaltDURATION,BuffDURATION,DURATIONSEC from @TBL               
    END    
  END    
END 



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAndEditAndDelteRouteInfo_WithDistnce_old]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
 CREATE procedure [dbo].[rvlf_sp_SaveAndEditAndDelteRouteInfo_WithDistnce_old]          
 @bitIsDelete bit=null,          
 @sintRouteId smallint = Null,          
 @vcRouteName varchar(30)=null,          
 @vcRouteDesc varchar(250)=null,          
 @vcLanadmaekIds varchar(100)=null,          
 @vcSeqNos varchar(100)=null,            
 @bigOrganizationID bigint = null,          
 @vcDurations varchar(100)=null,        
 @vcTravelDuration varchar(20)=null,        
 @vcTravelDistance varchar(20)=null,          
 @vcDistance varchar(100)=null ,    
 @vcTrafficDuration varchar(100) = null     
AS          
/****************************************************************************************************************/          
-- Name  : [rvlf_sp_SaveAndEditAndDelteRouteInfo_WithDistnce_Test]          
-- Description : To save,edit and delete the route details          
-- Author  : V.Narayanasamy          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : 26-Sep-2010 VN Created Intial Version           
--   : 27-Jan-2012 Vijay Added Travel duration and Travel distance to the table and in insert and update query.        
--  : Added Individual Distance and Duration in Table    
/****************************************************************************************************************/          
BEGIN          
          
           
 IF(@bitIsDelete=1)          
  BEGIN           
   DELETE rvlfRouteMaster WHERE RouteID=@sintRouteId AND OrgID=@bigOrganizationID           
   DELETE rvlfRouteDetails WHERE RouteID=@sintRouteId           
  END          
 ELSE          
  BEGIN          
   DECLARE @TBL TABLE          
(          
 LAND VARCHAR(5),          
 SEQNO VARCHAR(5),          
 DURATION VARCHAR(50),    
 DISTANCE VARCHAR(50),    
 TRAFFICDURATION VARCHAR(50)             
)          
DECLARE @SEQ TABLE          
( Id int identity,          
 SEQNO VARCHAR(5)          
)          
DECLARE @DUR TABLE          
(           
 Id int identity,          
 DURATION VARCHAR(50)           
)          
    
DECLARE @DIS TABLE          
(           
 Id int identity,          
 DISTANCE VARCHAR(50)           
)      
    
    
--DECLARE @TRAFFICDIS TABLE          
--(           
-- Id int identity,          
-- TRAFFICDURATION VARCHAR(50)           
--)      
    
    
INSERT INTO @TBL (LAND)          
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcLanadmaekIds,',')          
INSERT INTO @SEQ (SEQNO)          
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcSeqNos,',')          
INSERT INTO @DUR (DURATION)          
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcDurations,',')          
INSERT INTO @DIS (DISTANCE)          
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcDistance,',')          
--INSERT INTO @TRAFFICDIS (TRAFFICDURATION)          
--SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcTrafficDuration,',')      
          
DECLARE @INC INT=(SELECT COUNT(*)  FROM @TBL)          
Print @INC          
DECLARE @I INT=1          
WHILE @I< @INC+1          
 BEGIN          
            
  Update top (1) @TBL Set SEQNO=(Select SEQNO from @SEQ where Id=@I)   where SEQNO is null          
  Update top (1) @TBL Set DURATION =(Select DURATION  from @DUR where Id=@I)   where DURATION is null    
  update top (1) @TBL set DISTANCE =(Select DISTANCE  from @DIS where Id=@I)   where DISTANCE is null    
--  update top (1) @TBL set TRAFFICDURATION =(Select TRAFFICDURATION  from @TRAFFICDIS where Id=@I)   where TRAFFICDURATION is null    
  Set @I=@I+1          
 END          
   IF(@sintRouteId>0)          
    BEGIN          
     UPDATE rvlfRouteMaster SET RouteName=@vcRouteName,RouteDescription=@vcRouteDesc,TravelDuration = @vcTravelDuration,    
     TravelDistance = @vcTravelDistance,TrafficDuration = @vcTrafficDuration        
      WHERE RouteID=@sintRouteId AND OrgID=@bigOrganizationID           
                
     DELETE rvlfRouteDetails WHERE RouteID=@sintRouteId           
               
     INSERT INTO rvlfRouteDetails(RouteID,LndID,SeqID,duration,Distance)          
      SELECT @sintRouteId,LAND,SEQNO,DURATION,DISTANCE from @TBL           
    END           
   ELSE          
    BEGIN           
    declare @GRouteId int      
    select @GRouteId= MAX(GrouteId) from rvlfRouteMaster where OrgID=@bigOrganizationID      
                
     INSERT INTO rvlfRouteMaster(RouteName,RouteDescription,TravelDuration,TravelDistance,OrgID,GrouteId,TrafficDuration)          
      VALUES(@vcRouteName,@vcRouteDesc,@vcTravelDuration,@vcTravelDistance,@bigOrganizationID,(ISNULL(@GRouteId,0)+1),@vcTrafficDuration)          
     declare @rouid smallint= @@IDENTITY                    
     INSERT INTO rvlfRouteDetails(RouteID,LndID,SeqID,duration,Distance)          
      SELECT @rouid,LAND,SEQNO,DURATION,DISTANCE from @TBL           
    END          
  END          
END          
      
      
      
      
      
      

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAndEditAndDelteRouteInfo_WithDistnce_Test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[rvlf_sp_SaveAndEditAndDelteRouteInfo_WithDistnce_Test]              
 @bitIsDelete bit=null,              
 @sintRouteId smallint = Null,              
 @vcRouteName varchar(30)=null,              
 @vcRouteDesc varchar(250)=null,              
 @vcLanadmaekIds varchar(1000)=null,              
 @vcSeqNos varchar(100)=null,                
 @bigOrganizationID bigint = null,              
 @vcDurations varchar(1000)=null,            
 @vcDurationsec varchar(1000)=null,            
 @vcTravelDuration varchar(20)=null,            
 @vcTravelDistance varchar(20)=null,              
 @vcDistance varchar(1000)=null ,        
 @vcTrafficDuration varchar(1000) = null,         
 @vcHaultTime varchar(1000) = null,         
 @vcBufferTime varchar(1000) = null,        
 @bitIsCircularTrip bit = null
AS              
/****************************************************************************************************************/              
-- Name  : [rvlf_sp_SaveAndEditAndDelteRouteInfo_WithDistnce_Test]              
-- Description : To save,edit and delete the route details              
-- Author  : V.Narayanasamy              
-- Company  : Angler Technologies              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
--    : 26-Sep-2010 VN Created Intial Version               
--   : 27-Jan-2012 Vijay Added Travel duration and Travel distance to the table and in insert and update query.            
--  : Added Individual Distance and Duration in Table        
/****************************************************************************************************************/              
BEGIN              
              
               
 IF(@bitIsDelete=1)              
  BEGIN               
   DELETE rvlfRouteMaster WHERE RouteID=@sintRouteId AND OrgID=@bigOrganizationID               
   DELETE rvlfRouteDetails WHERE RouteID=@sintRouteId               
  END              
 ELSE              
  BEGIN              
   DECLARE @TBL TABLE              
(              
 LAND VARCHAR(5),              
 SEQNO VARCHAR(5),              
 DURATION VARCHAR(50),        
 DURATIONSEC VARCHAR(50),        
 DISTANCE VARCHAR(50),        
 TRAFFICDURATION VARCHAR(50),      
 BuffDURATION VARCHAR(50),      
 HaltDURATION VARCHAR(50)      
)              
DECLARE @SEQ TABLE              
( Id int identity,              
 SEQNO VARCHAR(5)              
)              
DECLARE @DUR TABLE              
(               
 Id int identity,              
 DURATION VARCHAR(50)               
)              
DECLARE @DURSec TABLE              
(               
 Id int identity,              
 DURATION VARCHAR(50)               
)      
DECLARE @DIS TABLE              
(               
 Id int identity,              
 DISTANCE VARCHAR(50)               
)          
        
  DECLARE @Buff TABLE              
(               
 Id int identity,              
 DURATION VARCHAR(50)               
)              
        
DECLARE @Halt TABLE              
(               
 Id int identity,              
 DURATION VARCHAR(50)               
)          
      
--DECLARE @TRAFFICDIS TABLE              
--(               
-- Id int identity,              
-- TRAFFICDURATION VARCHAR(50)               
--)          
        
        
INSERT INTO @TBL (LAND)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcLanadmaekIds,',')              
INSERT INTO @SEQ (SEQNO)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcSeqNos,',')              
INSERT INTO @DUR (DURATION)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcDurations,',')     
INSERT INTO @DURSec (DURATION)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcDurationsec,',')             
INSERT INTO @DIS (DISTANCE)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcDistance,',')              
INSERT INTO @Buff (DURATION)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcBufferTime,',')              
INSERT INTO @Halt (DURATION)              
SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcHaultTime,',')              
--INSERT INTO @TRAFFICDIS (TRAFFICDURATION)              
--SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcTrafficDuration,',')          
              
DECLARE @INC INT=(SELECT COUNT(*)  FROM @TBL)              
Print @INC              
DECLARE @I INT=1              
WHILE @I< @INC+1              
 BEGIN              
                
  Update top (1) @TBL Set SEQNO=(Select SEQNO from @SEQ where Id=@I)   where SEQNO is null              
  Update top (1) @TBL Set DURATION =(Select DURATION  from @DUR where Id=@I)   where DURATION is null        
  Update top (1) @TBL Set DURATIONSEC =(Select DURATION  from @DURSec where Id=@I)   where DURATIONSEC is null        
  update top (1) @TBL set DISTANCE =(Select DISTANCE  from @DIS where Id=@I)   where DISTANCE is null        
  Update top (1) @TBL Set HaltDURATION =(Select DURATION  from @Halt where Id=@I)   where HaltDURATION is null      
  Update top (1) @TBL Set BuffDURATION =(Select DURATION  from @Buff where Id=@I)   where BuffDURATION is null      
--  update top (1) @TBL set TRAFFICDURATION =(Select TRAFFICDURATION  from @TRAFFICDIS where Id=@I)   where TRAFFICDURATION is null        
  Set @I=@I+1              
 END              
   IF(@sintRouteId>0)              
    BEGIN              
     UPDATE rvlfRouteMaster SET RouteName=@vcRouteName,RouteDescription=@vcRouteDesc,TravelDuration = @vcTravelDuration,        
     TravelDistance = @vcTravelDistance,TrafficDuration = @vcTrafficDuration, IsCircularTrip = @bitIsCircularTrip             
      WHERE RouteID=@sintRouteId AND OrgID=@bigOrganizationID               
                    
     DELETE rvlfRouteDetails WHERE RouteID=@sintRouteId               
                   
     INSERT INTO rvlfRouteDetails(RouteID,LndID,SeqID,duration,Distance,HaltTime,BufferTime,DurationSec)              
      SELECT @sintRouteId,LAND,SEQNO,DURATION,DISTANCE,HaltDURATION,BuffDURATION,DURATIONSEC from @TBL               
    END               
   ELSE              
    BEGIN               
    declare @GRouteId int          
    select @GRouteId= MAX(GrouteId) from rvlfRouteMaster where OrgID=@bigOrganizationID          
                    
     INSERT INTO rvlfRouteMaster(RouteName,RouteDescription,TravelDuration,TravelDistance,OrgID,GrouteId,TrafficDuration,IsCircularTrip)              
      VALUES(@vcRouteName,@vcRouteDesc,@vcTravelDuration,@vcTravelDistance,@bigOrganizationID,(ISNULL(@GRouteId,0)+1),@vcTrafficDuration,@bitIsCircularTrip)              
     declare @rouid smallint= @@IDENTITY                        
     INSERT INTO rvlfRouteDetails(RouteID,LndID,SeqID,duration,Distance,HaltTime,BufferTime,DurationSec)           
      SELECT @rouid,LAND,SEQNO,DURATION,DISTANCE,HaltDURATION,BuffDURATION,DURATIONSEC from @TBL               
    END    
  END    
END 

 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAndUpdateAndDeleteDriverGroups]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveAndUpdateAndDeleteDriverGroups]
	@bitIsDelete bit=null,
	@bigDriverGroupId bigint=null,
	@vcGroupName varchar(20)=null,
	@vcGroupDesc varchar(250)=null,
	@bigUserId	 bigint=null,
	@bigOrganizationId bigint=null		
AS
/****************************************************************************************/
--	Name		  : rvlf_sp_SaveAndUpdateAndDeleteDriverGroups
--	Description	  :	To save,update and delete the driver group details
--	Author		  :	Narayanasamy.V
--	Created Date  : 25-Sep-2010
--  Modified Date :
/***************************************************************************************/
BEGIN
	SET NOCOUNT ON 
	
	IF(@bitIsDelete =0)
		BEGIN
			IF(@bigDriverGroupId >0)
				BEGIN
					UPDATE RVLFDRIVERGROUPMASTER SET DRIVERGROUPNAME=@vcGroupName,DRIVERGROUPDESC=@vcGroupDesc,
							MODIFIEDBY=@bigUserId,MODIFIEDDATE=GETDATE()
						WHERE DRIVERGROUPID=@bigDriverGroupId 
							AND ORGANIZATIONID=@bigOrganizationId						
				END
			ELSE
				BEGIN
					INSERT INTO RVLFDRIVERGROUPMASTER (DRIVERGROUPNAME,DRIVERGROUPDESC,CREATEDBY,CREATEDDATE,ORGANIZATIONID)
						VALUES(@vcGroupName,@vcGroupDesc,@bigUserId,GETDATE(),@bigOrganizationId) 
				END
		END
	ELSE
		BEGIN
			DELETE FROM RVLFDRIVERGROUPMASTER 
				WHERE DRIVERGROUPID=@bigDriverGroupId 
					AND ORGANIZATIONID=@bigOrganizationId
		END
	
		
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAndUpdateAndDeleteNews]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveAndUpdateAndDeleteNews]    
 @bitIsDelete bit=null,    
 @bigNewsId bigint=null,    
 @vcNewsName varchar(50)=null,    
 @vcNewsDesc varchar(500)=null,    
 @vcType varchar(10)=null,    
 @vcNavigateURL varchar(250)=null,    
 @dtPublishDate dateTime =null,    
 @dtExpiryDate dateTime=null,    
 @bigOrganizationId bigint=null,    
 @bigUserId  bigint=null,    
 @vcAuthorName NVARCHAR(250) = NULL,          
 @vcImageName VARCHAR(250) = NULL,  
 @vcReleasePDF varchar(1000) = null,
 @bitIsPushNotification bit=null
AS    
/****************************************************************************************/    
-- Name    : rvlf_sp_SaveAndUpdateAndDeleteNews 0,1,'Award for Trinetra @ CeBIT Australia','Award for Trinetra @ CeBIT Australia 2010','Linkable','http://www.trinetrawireless.com/news-events.html#',1,1    
-- Description   : To save,update and delete the News details    
-- Author    : Jeyanthi.S    
-- Created Date  : 19-Oct-2010    
--  Modified Date :    
/***************************************************************************************/    
BEGIN    
 SET NOCOUNT ON     
     
 IF(@bitIsDelete = 0)    
  BEGIN     
   IF(@bigNewsId > 0)    
    BEGIN    
     UPDATE rvlfNews SET NewsName=@vcNewsName,NewsDescription=@vcNewsDesc,    
      Type=@vcType, NavigateURL=@vcNavigateURL,PublishDate=@dtPublishDate,    
      ExpiryDate =@dtExpiryDate,ModifiedBy=@bigUserId,ModifiedDate=GETDATE(),    
      authorname = @vcAuthorName,ImageName = @vcImageName,ReleasePDFLink=@vcReleasePDF,
      IsPushNotification= @bitIsPushNotification               
      WHERE newsid=@bigNewsId     
       --AND OrganizationId=@bigOrganizationId          
    END    
   ELSE    
    BEGIN    
     INSERT INTO rvlfNews (NewsName,NewsDescription,Type,NavigateURL,PublishDate,ExpiryDate,OrganizationId,CreatedBy,CreatedDate,authorname,ImageName,ReleasePDFLink,IsPushNotification)    
      VALUES(@vcNewsName,@vcNewsDesc,@vcType,@vcNavigateURL,@dtPublishDate,@dtExpiryDate,@bigOrganizationId,@bigUserId,GETDATE(),@vcAuthorName,@vcImageName,@vcReleasePDF,@bitIsPushNotification)    
    END    
  END    
 ELSE    
  BEGIN    
   DELETE FROM rvlfNews     
    WHERE NewsID=@bigNewsId     
     --AND OrganizationId=@bigOrganizationId    
  END    
      
 SET NOCOUNT OFF    
END    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAndUpdateAndDeleteSchedulingOfCommands]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_SaveAndUpdateAndDeleteSchedulingOfCommands]
 @bitIsDelete bit=null,        
 @bigSchedulingId bigint=null,       
 @vcCommandCode varchar(3)=null,        
 @vcPacketInfo varchar(500)=null,        
 @dtEffectiveFrom datetime=null,        
 @dtEffectiveTo datetime=null,        
 @tintExecutionType tinyint=null,        
 @tintNoofRetries tinyint=null,        
 @bigUserId bigint=null,        
 @bigOrganizationId bigint=null,        
 @bigVehicleId bigint=null,        
 @vcExecutionOn varchar(50)=null,        
 @bigFleetId bigint=null,        
 @bigBoxid int =null,        
 @VIcurveValue  int =null,
 @Percent int =null,
 @Count int =null,
 @ControllerID int =null
AS        
/****************************************************************************************/        
-- Name    : [rvlf_sp_SaveAndUpdateAndDeleteSchedulingOfCommands]0,0,'H','IP=106.208.179.246;Port=28800;Message=H;DeviceID=999984;Param=20,<values>;DCLID=Angler90;UserID=292',
--'05/09/2017 12:55:11 PM','05/10/2017 12:55:11 PM',0,3,292,86,688,'any message in',null,null,110,10,2        
-- Description   : To save,update and delete the scheduling of commands        
-- Author    : Narayanasamy.V        
-- Created Date  : 13-Dec-2010        
--  Modified Date :        
/***************************************************************************************/        
        
BEGIN        
 SET NOCOUNT ON 
 --insert into MyTestTable values (
 -- isnull(cast(@bitIsDelete as varchar(100)),'@bitIsDelete') + ' '+
 --isnull(cast(@bigSchedulingId as varchar(100)),'@bigSchedulingId') + ' '+
 --isnull(@vcCommandCode,'@@vcCommandCode') + ' '+
 --isnull(@vcPacketInfo,'@@vcPacketInfo') + ' '+
 --isnull(cast(@dtEffectiveFrom as varchar(100)),'@@dtEffectiveFrom') + ' '+
 --isnull(cast(@dtEffectiveTo as varchar(100)),'@@dtEffectiveTo') + ' '+
 --isnull(cast(@tintExecutionType as varchar(100)),'@@tintExecutionType') + ' '+
 --isnull(cast(@tintNoofRetries as varchar(100)),'@@tintNoofRetries') + ' '+
 --isnull(cast(@bigUserId  as varchar(100)),'@@bigUserId') + ' '+
 --isnull(cast(@bigOrganizationId as varchar(100)),'@@bigOrganizationId') + ' '+
 --isnull(cast(@bigVehicleId as varchar(100)),'@@bigVehicleId') + ' '+
 --isnull(@vcExecutionOn ,'@@vcExecutionOn')+ ' '+
 --isnull(cast(@bigFleetId as varchar(100)),'@@bigFleetId') + ' '+
 --isnull(cast(@bigBoxid as varchar(100)),'@@bigBoxid') + ' '+
 --isnull(cast(@VIcurveValue as varchar(100)),'@@VIcurveValue') + ' '+
 --isnull(cast(@Percent as varchar(100)) ,'@Percent')+ ' '+
 --isnull(cast(@Count as varchar(100)),' @Count'),@dtEffectiveFrom,@dtEffectiveTo )
       
       declare @PercentValue int =(@VIcurveValue * @percent/CAST(100 AS DECIMAL (9,2)))
	   declare @VI_ID bigint =null
        --GET THE COMMAND CODE AND BOXID        
   DECLARE @tintCommandid tinyint=null,@intBoxid int=null        
   SELECT @tintCommandid=BoxCmdOutTypeId FROM rvlfBoxCmdOutType WHERE CAST(BoxCmdOutTypeCode AS VARBINARY)=CAST(@vcCommandCode AS VARBINARY)        
   SELECT @bigBoxid = CASE WHEN @bigBoxid = '' THEN NULL ELSE @bigBoxid END        
   IF @bigBoxid IS NOT NULL AND @bigVehicleId IS NULL         
    BEGIN        
     SET @intBoxid=CAST(@bigBoxid AS INT)        
     SET @bigVehicleId = null         
    END        
   ELSE IF(@bigVehicleId IS NULL AND @bigVehicleId='')        
    BEGIN            
     SET @intBoxid=@bigBoxid        
     --SET @bigVehicleId=2        
    END        
   ELSE            
    SELECT @intBoxid =BoxId FROM rvlfVehicleAssignment WHERE VehicleId =@bigVehicleId 
      

 IF(@bitIsDelete =0)        
  BEGIN                  
	DECLARE @HoursToBeAdded INT = 0                            
	DECLARE @MinsToBeAdded INT = 0                      
          
   IF(@bigSchedulingId >0)
    BEGIN        
     UPDATE rvlfScheduleOfCommandsMaster SET       
       PacketInfo=   @vcPacketInfo ,        
       EffectiveFrom=@dtEffectiveFrom,EffectiveTo=@dtEffectiveTo,Frequency=@tintExecutionType,        
       [No.ofRetries]=@tintNoofRetries,UserId=@bigUserId,OrganizationId=@bigOrganizationId,        
       CreatedDate=GETDATE(),NextExecutionOn=null,        
       ExecutionOn=@vcExecutionOn,BoxCmdOutTypeId= @tintCommandid,Boxid=@intBoxid          
      WHERE ScheduleId=@bigSchedulingId AND ORGANIZATIONID=@bigOrganizationId              
    END        
   ELSE        
    BEGIN        
     IF(@bigVehicleId =0)        
      BEGIN  
	  print 0           
		INSERT INTO rvlfScheduleOfCommandsMaster (PacketInfo,EffectiveFrom,        
         EffectiveTo,Frequency,[No.ofRetries],UserId,OrganizationId,CreatedDate,NextExecutionOn,Executionon,BoxCmdOutTypeId,Boxid,ControllerId)        
       SELECT CASE WHEN @tintCommandid = 11 AND CHARINDEX('SpeedThreshold',@vcPacketInfo,0) = 0 THEN       
        REPLACE(REPLACE(@vcPacketInfo,SUBSTRING (@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1),        
        CHARINDEX(';',@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1)) - (CHARINDEX('DeviceID=',@vcPacketInfo,1))),'DeviceID='+CAST(va.BoxId as varchar)),';DCLID=',',SpeedThreshold:255;DCLID=')  
		ELSE  REPLACE(@vcPacketInfo,SUBSTRING (@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1),        
        CHARINDEX(';',@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1)) - (CHARINDEX('DeviceID=',@vcPacketInfo,1))),'DeviceID='+CAST(va.BoxId as varchar))      
        END,        
        @dtEffectiveFrom,@dtEffectiveTo,@tintExecutionType,@tintNoofRetries,@bigUserId,        
        @bigOrganizationId,GETDATE(),null,@vcExecutionOn,@tintCommandid,VA.BoxId ,@ControllerID         
        FROM rvlfFleetVehicles FV INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=FV.VehicleId           
        WHERE FV.FleetId=@bigFleetId         
                
       --INSERT THE SCHEDULES IN THE LOG TABLE                
       DECLARE @intTotVeh INT=(SELECT COUNT(VA.BoxId) FROM rvlfFleetVehicles FV         
         INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=FV.VehicleId           
        WHERE FV.FleetId=@bigFleetId)        
       INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)        
        SELECT TOP (@intTotVeh) ScheduleId,NULL,0 FROM rvlfScheduleOfCommandsMaster         
         WHERE Boxid NOT IN(SELECT DISTINCT BoxId FROM rvlfMsgOutHst         
          WHERE BoxId IN(SELECT VA.BoxId FROM rvlfFleetVehicles FV         
           INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=FV.VehicleId           
          WHERE FV.FleetId=@bigFleetId)         
           AND CONVERT(DATE,GETUTCDATE())=CONVERT(DATE,SentDateTime)         
           AND Acknowledged IS NULL AND BoxCmdOutTypeId !=21)         
           ORDER BY ScheduleId DESC                         
      END        
     ELSE        
      BEGIN        
        if not exists(select a.ScheduleId from rvlfScheduleOfCommandsMaster a left join rvlfSchedulingOfCommandsLog b on a.ScheduleId=b.ScheduleId
		where (effectivefrom between @dtEffectiveFrom and @dtEffectiveTo or effectiveto between @dtEffectiveFrom and @dtEffectiveTo) and b.ResponseMsg!='Expired' 
		and BoxCmdOutTypeId=@tintCommandid and Boxid=@intBoxid and b.ResponseMsg!='Success' and @tintCommandid=22) --check duplicate schedules for ota 02-may-16
	Begin    
	if( @tintCommandid !=10)
	begin  
       INSERT INTO rvlfScheduleOfCommandsMaster (PacketInfo,EffectiveFrom, EffectiveTo,Frequency,[No.ofRetries],UserId,OrganizationId,CreatedDate,        
         NextExecutionOn,Executionon,BoxCmdOutTypeId,Boxid,ControllerId) 
        VALUES(
		  REPLACE(@vcPacketInfo,SUBSTRING (@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1),        
        CHARINDEX(';',@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1)) - (CHARINDEX('DeviceID=',@vcPacketInfo,1))),'DeviceID='+CAST(@intBoxid as varchar)),
		          @dtEffectiveFrom,@dtEffectiveTo, @tintExecutionType,@tintNoofRetries,@bigUserId,@bigOrganizationId,GETDATE(), null,@vcExecutionOn,@tintCommandid,@intBoxid,@ControllerID)
       ----INSERT THE SCHEDULES IN THE LOG TABLE           
       --DECLARE @bigScheduleId bigint =@@IDENTITY         
       --INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)        
       -- SELECT ScheduleId,NULL,0 FROM rvlfScheduleOfCommandsMaster         
       --  WHERE ScheduleId=@bigScheduleId AND Boxid NOT IN(SELECT BoxId FROM rvlfMsgOutHst         
       --   WHERE BoxId IN(@intBoxid) AND CONVERT(DATE,GETUTCDATE())=CONVERT(DATE,SentDateTime)         
       --    AND Acknowledged IS NULL AND BoxCmdOutTypeId !=21)     
               
 --if(@tintCommandid!=94)          
 --     begin       
       --INSERT THE SCHEDULES IN THE LOG TABLE                     
       DECLARE @bigScheduleId bigint =@@IDENTITY                   
       INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)                  
        SELECT ScheduleId,NULL,0 FROM rvlfScheduleOfCommandsMaster                   
         WHERE ScheduleId=@bigScheduleId AND Boxid NOT IN(SELECT BoxId FROM rvlfMsgOutHst                   
          WHERE BoxId IN(@intBoxid) AND CONVERT(DATE,GETUTCDATE())=CONVERT(DATE,SentDateTime)                   
           AND Acknowledged IS NULL AND BoxCmdOutTypeId !=21)                  
       End   
	   else -- VI Curve
	   begin
	   set @VI_ID = (select max(VI_ID) from rvlfScheduleOfCommandsMaster where BoxCmdOutTypeId=10)
	   declare @sno tinyint=@Count
	   declare @values varchar(100)=null 
	   While (@Count>0)
        BEGIN 				
		SET @values = cast(@VIcurveValue as varchar(4)) +','+cast(ISNULL(@VI_ID+1,1) as varchar(20))+','+cast(@sno as varchar(2))+','+cast((@sno-@Count+1) as varchar(2))
	    
			INSERT INTO rvlfScheduleOfCommandsMaster (PacketInfo,EffectiveFrom, EffectiveTo,Frequency,[No.ofRetries],UserId,OrganizationId,CreatedDate,        
			NextExecutionOn,Executionon,BoxCmdOutTypeId,Boxid,VI_ID,ControllerId) 
			VALUES(REPLACE(@vcPacketInfo,'<values>',@values),@dtEffectiveFrom,@dtEffectiveTo,        
			@tintExecutionType,@tintNoofRetries,@bigUserId,@bigOrganizationId,GETDATE(),null,@vcExecutionOn,@tintCommandid,@intBoxid,ISNULL(@VI_ID+1,1),@ControllerID)		  
		  
		SET @VIcurveValue= @VIcurveValue+@PercentValue 
        SET @count=@count-1
        END
	   end   
      END
	  else 
	  begin	    
	  RAISERROR ('Already another OTA has been scheduled for this device between same duration',16,1)	  
	  end  
      END               
    END        
  END        
 ELSE        
  BEGIN        
   DELETE FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId=@bigSchedulingId               
   DELETE FROM rvlfScheduleOfCommandsMaster WHERE ScheduleId=@bigSchedulingId AND ORGANIZATIONID=@bigOrganizationId   
  END              
 SET NOCOUNT OFF        
END        
 



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAndUpdateAndDeleteSchedulingOfCommands_bkp]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveAndUpdateAndDeleteSchedulingOfCommands_bkp]        
 @bitIsDelete bit=null,        
 @bigSchedulingId bigint=null,        
 @vcCommandCode varchar(3)=null,        
 @vcPacketInfo varchar(500)=null,        
 @dtEffectiveFrom datetime=null,        
 @dtEffectiveTo datetime=null,        
 @tintExecutionType tinyint=null,        
 @tintNoofRetries tinyint=null,        
 @bigUserId bigint=null,        
 @bigOrganizationId bigint=null,        
 @bigVehicleId bigint=null,        
 @vcExecutionOn varchar(50)=null,        
 @bigFleetId bigint=null,        
 @bigBoxid int =null        
         
AS        
/****************************************************************************************/        
-- Name    : [rvlf_sp_SaveAndUpdateAndDeleteSchedulingOfCommands]0,0,'?','IP=49.137.68.231;Port=4038;Message=?;DeviceID=999888;DCLID=Angler90;UserID=62','10/29/2011 9:28:11 AM','10/30/2011 9:28:11 AM',0,3,62,6,0,'any message in',8,''        
-- Description   : To save,update and delete the scheduling of commands        
-- Author    : Narayanasamy.V        
-- Created Date  : 13-Dec-2010        
--  Modified Date :        
/***************************************************************************************/        
        
BEGIN        
 SET NOCOUNT ON         
       
        --GET THE COMMAND CODE AND BOXID        
   DECLARE @tintCommandid tinyint=null,@intBoxid int=null        
   SELECT @tintCommandid=BoxCmdOutTypeId FROM rvlfBoxCmdOutType WHERE CAST(BoxCmdOutTypeCode AS VARBINARY)=CAST(@vcCommandCode AS VARBINARY)        
   SELECT @bigBoxid = CASE WHEN @bigBoxid = '' THEN NULL ELSE @bigBoxid END        
   IF @bigBoxid IS NOT NULL AND @bigVehicleId IS NULL         
    BEGIN        
     SET @intBoxid=CAST(@bigBoxid AS INT)        
     SET @bigVehicleId = null         
    END        
   ELSE IF(@bigVehicleId IS NULL AND @bigVehicleId='')        
    BEGIN            
     SET @intBoxid=@bigBoxid        
     --SET @bigVehicleId=2        
    END        
   ELSE            
    SELECT @intBoxid =BoxId FROM rvlfVehicleAssignment WHERE VehicleId =@bigVehicleId 
         
 IF(@bitIsDelete =0)        
  BEGIN        
          
      DECLARE @HoursToBeAdded INT = 0                            
 DECLARE @MinsToBeAdded INT = 0                      
   if(@vcCommandCode ='W42')            
   begin            
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded                   
 FROM dbo.rvlfUserPreferences up INNER JOIN dbo.rvlfTimeZones tz                            
 ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigUserId                                    
                          
 SET @dtEffectiveFrom=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEffectiveFrom))                            
 SET @dtEffectiveTo=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEffectiveTo))            
 end      
     
  
               
   --SET @dtEffectiveTo=DATEADD(D,-1,@dtEffectiveTo)        
   IF(@bigSchedulingId >0)        
    BEGIN        
     UPDATE rvlfScheduleOfCommandsMaster SET       
       PacketInfo= CASE WHEN @tintCommandid=11 AND CHARINDEX('SpeedThreshold',@vcPacketInfo,0) = 0 THEN       
       REPLACE(@vcPacketInfo,';DCLID=',',SpeedThreshold:255;DCLID=') ELSE @vcPacketInfo END,        
       EffectiveFrom=@dtEffectiveFrom,EffectiveTo=@dtEffectiveTo,Frequency=@tintExecutionType,        
       [No.ofRetries]=@tintNoofRetries,UserId=@bigUserId,OrganizationId=@bigOrganizationId,        
       CreatedDate=GETDATE(),NextExecutionOn=null,        
       ExecutionOn=@vcExecutionOn,BoxCmdOutTypeId= @tintCommandid,Boxid=@intBoxid          
      WHERE ScheduleId=@bigSchedulingId AND ORGANIZATIONID=@bigOrganizationId              
    END        
   ELSE        
    BEGIN        
     IF(@bigVehicleId =0)        
      BEGIN             
 INSERT INTO rvlfScheduleOfCommandsMaster (PacketInfo,EffectiveFrom,        
         EffectiveTo,Frequency,[No.ofRetries],UserId,OrganizationId,CreatedDate,                 NextExecutionOn,Executionon,BoxCmdOutTypeId,Boxid)        
       SELECT        
        CASE WHEN @tintCommandid = 11 AND CHARINDEX('SpeedThreshold',@vcPacketInfo,0) = 0 THEN       
        REPLACE(REPLACE(@vcPacketInfo,SUBSTRING (@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1),        
        CHARINDEX(';',@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1)) - (CHARINDEX('DeviceID=',@vcPacketInfo,1))),'DeviceID='+CAST(va.BoxId as varchar)),      
        ';DCLID=',',SpeedThreshold:255;DCLID=')  ELSE  REPLACE(@vcPacketInfo,SUBSTRING (@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1),        
        CHARINDEX(';',@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1)) - (CHARINDEX('DeviceID=',@vcPacketInfo,1))),'DeviceID='+CAST(va.BoxId as varchar))      
        END,        
        @dtEffectiveFrom,@dtEffectiveTo,@tintExecutionType,@tintNoofRetries,@bigUserId,        
        @bigOrganizationId,GETDATE(),null,@vcExecutionOn,@tintCommandid,VA.BoxId          
        FROM rvlfFleetVehicles FV INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=FV.VehicleId           
        WHERE FV.FleetId=@bigFleetId         
                
       --INSERT THE SCHEDULES IN THE LOG TABLE                
       DECLARE @intTotVeh INT=(SELECT COUNT(VA.BoxId) FROM rvlfFleetVehicles FV         
         INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=FV.VehicleId           
        WHERE FV.FleetId=@bigFleetId)        
       INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)        
        SELECT TOP (@intTotVeh) ScheduleId,NULL,0 FROM rvlfScheduleOfCommandsMaster         
         WHERE Boxid NOT IN(SELECT DISTINCT BoxId FROM rvlfMsgOutHst         
          WHERE BoxId IN(SELECT VA.BoxId FROM rvlfFleetVehicles FV         
           INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=FV.VehicleId           
          WHERE FV.FleetId=@bigFleetId)         
           AND CONVERT(DATE,GETUTCDATE())=CONVERT(DATE,SentDateTime)         
           AND Acknowledged IS NULL AND BoxCmdOutTypeId !=21)         
           ORDER BY ScheduleId DESC              
                
                        
      END        
     ELSE        
      BEGIN        
        if not exists(select a.ScheduleId from rvlfScheduleOfCommandsMaster a left join rvlfSchedulingOfCommandsLog b on a.ScheduleId=b.ScheduleId
		where (effectivefrom between @dtEffectiveFrom and @dtEffectiveTo or effectiveto between @dtEffectiveFrom and @dtEffectiveTo) and b.ResponseMsg!='Expired' 
		and BoxCmdOutTypeId=@tintCommandid and Boxid=@intBoxid and b.ResponseMsg!='Success' and @tintCommandid=22) --check duplicate schedules for ota 02-may-16
	Begin        
       INSERT INTO rvlfScheduleOfCommandsMaster (PacketInfo,EffectiveFrom,        
         EffectiveTo,Frequency,[No.ofRetries],UserId,OrganizationId,CreatedDate,        
         NextExecutionOn,Executionon,BoxCmdOutTypeId,Boxid)        
        VALUES(      
        CASE WHEN @tintCommandid = 11 AND CHARINDEX('SpeedThreshold',@vcPacketInfo,0) = 0 THEN       
        REPLACE(REPLACE(@vcPacketInfo,SUBSTRING (@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1),        
        CHARINDEX(';',@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1)) - (CHARINDEX('DeviceID=',@vcPacketInfo,1))),'DeviceID='+CAST(@intBoxid as varchar)),      
        ';DCLID=',',SpeedThreshold:255;DCLID=')  ELSE  REPLACE(@vcPacketInfo,SUBSTRING (@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1),        
        CHARINDEX(';',@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1)) - (CHARINDEX('DeviceID=',@vcPacketInfo,1))),'DeviceID='+CAST(@intBoxid as varchar))      
        END,      
        --REPLACE(@vcPacketInfo,SUBSTRING (@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1),        
        --CHARINDEX(';',@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1)) - (CHARINDEX('DeviceID=',@vcPacketInfo,1))),'DeviceID='+CAST(@intBoxid as varchar)),      
         @dtEffectiveFrom,@dtEffectiveTo,        
         @tintExecutionType,@tintNoofRetries,@bigUserId,@bigOrganizationId,GETDATE(),        
         null,@vcExecutionOn,@tintCommandid,@intBoxid)          
       ----INSERT THE SCHEDULES IN THE LOG TABLE           
       --DECLARE @bigScheduleId bigint =@@IDENTITY         
       --INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)        
       -- SELECT ScheduleId,NULL,0 FROM rvlfScheduleOfCommandsMaster         
       --  WHERE ScheduleId=@bigScheduleId AND Boxid NOT IN(SELECT BoxId FROM rvlfMsgOutHst         
       --   WHERE BoxId IN(@intBoxid) AND CONVERT(DATE,GETUTCDATE())=CONVERT(DATE,SentDateTime)         
       --    AND Acknowledged IS NULL AND BoxCmdOutTypeId !=21)     
               
 if(@tintCommandid!=94)          
      begin       
       --INSERT THE SCHEDULES IN THE LOG TABLE                     
       DECLARE @bigScheduleId bigint =@@IDENTITY                   
       INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)                  
        SELECT ScheduleId,NULL,0 FROM rvlfScheduleOfCommandsMaster                   
         WHERE ScheduleId=@bigScheduleId AND Boxid NOT IN(SELECT BoxId FROM rvlfMsgOutHst                   
          WHERE BoxId IN(@intBoxid) AND CONVERT(DATE,GETUTCDATE())=CONVERT(DATE,SentDateTime)                   
           AND Acknowledged IS NULL AND BoxCmdOutTypeId !=21)                  
      End      
      END
	  else 
	  begin	    
	  RAISERROR ('Already another OTA has been scheduled for this device between same duration',16,1)	  
	  end  
      END               
    END        
  END        
 ELSE        
  BEGIN        
   DELETE FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId=@bigSchedulingId               
   DELETE FROM rvlfScheduleOfCommandsMaster WHERE ScheduleId=@bigSchedulingId AND ORGANIZATIONID=@bigOrganizationId        
       
   IF(@vcCommandCode='W42' and (@bigSchedulingId is null or @bigSchedulingId = 0))         
     BEGIN  
	 IF exists (select rva.AssignmentId from rvlfRouteVehicleAssignment rva inner join rvlfScheduleOfCommandsMaster SCM on rva.ScheduleId=SCM.ScheduleId
inner join rvlfSchedulingOfCommandsLog SCL on rva.ScheduleId=scl.ScheduleId where rva.Isdelete is null and scm.Isdelete is null and scm.boxid=@intBoxid
and rva.ToDateTime >GETUTCDATE())
	 Begin    
        INSERT INTO rvlfScheduleOfCommandsMaster (PacketInfo,EffectiveFrom,                  
         EffectiveTo,Frequency,[No.ofRetries],UserId,OrganizationId,CreatedDate,                  
         NextExecutionOn,Executionon,BoxCmdOutTypeId,Boxid)                  
        VALUES(REPLACE(@vcPacketInfo,SUBSTRING (@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1),                  
        CHARINDEX(';',@vcPacketInfo,CHARINDEX('DeviceID=',@vcPacketInfo,1)) - (CHARINDEX('DeviceID=',@vcPacketInfo,1))),'DeviceID='+CAST(@intBoxid as varchar)),@dtEffectiveFrom,@dtEffectiveTo,      
         @tintExecutionType,@tintNoofRetries,@bigUserId,@bigOrganizationId,GETDATE(),      
         null,@vcExecutionOn,@tintCommandid,@intBoxid)      
            
       --INSERT THE SCHEDULES IN THE LOG TABLE      
       DECLARE @bigScheduleId1 bigint =@@IDENTITY       
       INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)      
        SELECT ScheduleId,NULL,0 FROM rvlfScheduleOfCommandsMaster      
         WHERE ScheduleId=@bigScheduleId1 AND Boxid NOT IN(SELECT BoxId FROM rvlfMsgOutHst                   
          WHERE BoxId IN(@intBoxid) AND CONVERT(DATE,GETUTCDATE())=CONVERT(DATE,SentDateTime)
           AND Acknowledged IS NULL AND BoxCmdOutTypeId !=21)      
     End      
     END   
  END              
 SET NOCOUNT OFF        
END   
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAndUpdateAndDeleteTips]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveAndUpdateAndDeleteTips]
	@bitIsDelete bit=null,
	@bigTipsId bigint=null,
	@vcTipsName varchar(50)=null,
	@vcTipsDesc varchar(500)=null,
	@vcType varchar(10)='Tips',
	@bigOrganizationId bigint=null,
	@bigUserId	 bigint=null			
AS
/****************************************************************************************/
--	Name		  : rvlf_sp_SaveAndUpdateAndDeleteTips 0,1,'Award for Trinetra @ CeBIT Australia','Award for Trinetra @ CeBIT Australia 2010','Linkable','http://www.trinetrawireless.com/news-events.html#',1,1
--	Description	  :	To save,update and delete the News details
--	Author		  :	Jeyanthi.S
--	Created Date  : 19-Oct-2010
--  Modified Date :
/***************************************************************************************/
BEGIN
	SET NOCOUNT ON 
	
	IF(@bitIsDelete = 0)
		BEGIN	
			IF(@bigTipsId > 0)
				BEGIN
					UPDATE rvlfNews SET NewsName=@vcTipsName,NewsDescription=@vcTipsDesc,
						Type=@vcType,ModifiedBy=@bigUserId,ModifiedDate=GETDATE()
						WHERE newsid=@bigTipsId 
							--AND OrganizationId=@bigOrganizationId						
				END
			ELSE
				BEGIN
					INSERT INTO rvlfNews (NewsName,NewsDescription,Type,OrganizationId,CreatedBy,CreatedDate)
						VALUES(@vcTipsName,@vcTipsDesc,@vcType,@bigOrganizationId,@bigUserId,GETDATE())
				END
		END
	ELSE
		BEGIN
			DELETE FROM rvlfNews 
				WHERE NewsID=@bigTipsId 
					--AND OrganizationId=@bigOrganizationId
		END
		
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAndUpdateEmployee]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[rvlf_sp_SaveAndUpdateEmployee]
	@EmployeeId bigint=null,
	@titleId bigint=null,
	@firstName varchar(50)=null,
	@lastName varchar(50)=null,
	@age datetime=null,
	@sex bit=null,
	@mobileNumber varchar(15)=null,
	@phoneNumber varchar(15)=null,
	@address varchar(200)=null,
	@nearestLandmark bigint=null,
	@latitude numeric(10,6)=null,
	@longitude numeric(10,6)=null,
	@dateOfJoin datetime=null,
	@avilable bit=null,
	@divisionId bigint=null,
	@departmentId bigint=null,
	@shiftId bigint=null,
	@emailId varchar(200)=null,
	@reportTo bigint=null,
	@contactName varchar(50)=null,
	@contactName1 varchar(50)=null,
	@contactPhoneNo varchar(15)=null,
	@contactPhoneNo1 varchar(15)=null,
	@contactRelation varchar(50)=null,
	@contactRelation1 varchar(50)=null,
	@contactMobileNo varchar(15)=null,
	@contactMobileNo1 varchar(15)=null,
	@displayName varchar(20)=null,
	@userName varchar(50)=null,
	@password varchar(100)=null,
	@biguserGroupId bigint=null,
	@cubicleNumber varchar(20)=null,
	@extentionNumber varchar(10)=null,
	@building varchar(20)=null,
	@createdOn datetime=null,
	@bigcreatedBy bigint=null,
	@bigZoneId	bigint=null,
	@bigOfficeAddress bigint=null,
	@bigLocality bigint=null,
	@vcLocalityName varchar(100)=null,
	@loclatitude numeric(10,6)=null,
	@loclongitude numeric(10,6)=null,
	@vcEmployeeCode varchar(10)=null
	
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_SaveAndUpdateEmployee]
--	Description	:	To insert Employee details.
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	05-Nov-2009	VN	Created Intial Version 
--				:	07-Dec-2009 VN add username,password fields.
--				:	19-Mar-10 Add the locality details 
/******************************************************************************/

BEGIN	
	--IF(@latitude IS NULL)
	--	BEGIN
	--		SELECT TOP 1 @latitude=Latitude,@longitude=Longitude,@bigLocality=LocalityId FROM rvlfEmployee WHERE StreetAddress LIKE @address 
	--	END
	--ELSE IF(@vcLocalityName IS NULL)
	--	BEGIN
	--		SET @vcLocalityName='UnKown'
	--		SET @loclatitude=NULL
	--		SET @loclongitude=NULL
			
	--	END
	--IF EXISTS(SELECT LocalityId FROM rvlfLocalityMaster WHERE LocalityName=@vcLocalityName)
	--	BEGIN
	--		SELECT @bigLocality=LocalityId FROM rvlfLocalityMaster WHERE LocalityName=@vcLocalityName 
	--	END
	--ELSE
	--	BEGIN			
	--		INSERT INTO rvlfLocalityMaster(LocalityName,BranchId,Allocated,Latitude,Longitude)
	--			VALUES(@vcLocalityName,@bigOfficeAddress,0,@loclatitude,@loclongitude)
	--		SET @bigLocality=@@IDENTITY  
	--	END
	IF(@EmployeeId>0)
		BEGIN		
			UPDATE rvlfEmployee SET Title=@titleId,FirstName=@firstName,LastName=@lastName,DateOfBirth=@age,Sex=@sex,EmailId=@emailId,
									StreetAddress=@address,MobileNo=@mobileNumber,PhoneNo=@phoneNumber,
									FirstContactName=@contactName,FirstContactRelation=@contactRelation,
									FirstContactMobileNo=@contactMobileNo,FirstContactPhoneNo=@contactPhoneNo,
									SecondContactName=@contactName1,SecondContactRelation=@contactRelation1,
									SecondContactMobileNo=@contactMobileNo1,SecondContactPhoneNo=@contactPhoneNo1,
									ReportTo=@reportTo,DateOfJoin=@dateOfJoin,Available=@avilable,
									DivisionID=@divisionId,DepartmentID=@departmentId,ShiftID=@shiftId,
									NearestLandMark=@nearestLandmark,Latitude=@latitude,Longitude=@longitude,
									CubicleNumber=@cubicleNumber,ExtentionNumber=@extentionNumber,Building=@building,
									ModifiedOn=@createdOn,ModifiedBy=@bigcreatedBy,zoneId=@bigZoneId,
									OrgId=@bigOfficeAddress,LocalityId=@bigLocality,usergroup=@biguserGroupId,
									Employeecode=@vcEmployeeCode 
									       
									
								WHERE EmployeeID=@EmployeeId 			
		END
	ELSE
		BEGIN
	
			INSERT INTO rvlfEmployee(Title,FirstName,LastName,DateOfBirth,Sex,EmailId,StreetAddress,MobileNo,PhoneNo,FirstContactName,
									 FirstContactRelation,FirstContactMobileNo,FirstContactPhoneNo,SecondContactName,
									 SecondContactRelation,SecondContactMobileNo,SecondContactPhoneNo,ReportTo,DateOfJoin,
									 Available,DivisionID,DepartmentID,ShiftID,NearestLandMark,Latitude,Longitude,DisplayName,
									 UserName,[password],CubicleNumber,ExtentionNumber,Building,CreatedOn,CreatedBy,
									 zoneId,OrgId,LocalityId,isdeleted,usergroup,Employeecode)
							  VALUES(@titleId,@firstName,@lastName,@age,@sex,@emailId,@address,@mobileNumber,@phoneNumber,
									 @contactName,@contactRelation,@contactMobileNo,@contactPhoneNo,@contactName1,
									 @contactRelation1,@contactMobileNo1,@contactPhoneNo1,@reportTo,@dateOfJoin,@avilable,
									 @divisionId,@departmentId,@shiftId,@nearestLandmark,@latitude,@longitude,@displayName,
									 @userName,@password,@cubicleNumber,@extentionNumber,@building,@createdOn,
									 @bigcreatedBy,@bigZoneId,@bigOfficeAddress,@bigLocality,0,@biguserGroupId,@vcEmployeeCode)
		END
END 
	

GO
/****** Object:  StoredProcedure [dbo].[rvlf_Sp_SaveandupdateGatewayID]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Asanraj N
-- Create date: 12-Feb-2021
-- Description: Save, Update, Delet Gateway ID
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_Sp_SaveandupdateGatewayID]
	@GatewayMasterId bigint =NULL,
	@GatewayId varchar(50) = NULL,
	@GatewayPassword varchar(50)= NULL,
	@OrganizationId bigint = NULL,
	@UserId bigint =NULL,
	@Operation char=NULL 	
AS
BEGIN	
	SET NOCOUNT ON;

	IF(@Operation ='I')
	BEGIN
	  INSERT INTO rvlfGatewayMaster(GatewayId,GatewayPassword,OrganizationId,CreatedDate,CreatedBy,IsDeleted)
	  VALUES(@GatewayId,@GatewayPassword,@OrganizationId,GETDATE(),@UserId,0)
	END
	IF(@Operation ='U')
	BEGIN
	  Update rvlfGatewayMaster SET 
	    GatewayId =@GatewayId,
		GatewayPassword =@GatewayPassword,
		ModifiedDate = GETDATE(),
        ModifiedBy=@UserId		
     WHERE GatewayMasterId = @GatewayMasterId	
	END
	IF(@Operation = 'D')
	BEGIN
	   Update rvlfGatewayMaster SET IsDeleted=1 WHERE GatewayMasterId = @GatewayMasterId	
	END
	IF(@Operation ='S')
	BEGIN
	   SELECT G.*,	CASE WHEN EXISTS(SELECT m.CustomerId FROM rvlfMAKDevices m WHERE m.CustomerId =G.GatewayMasterId)
	THEN 1 ELSE 0 END AssignedStatus FROM rvlfGatewayMaster G where OrganizationId=@OrganizationId and IsDeleted=0 and 
	   (@GatewayMasterId = '0' or @GatewayMasterId ='' or GatewayMasterId=@GatewayMasterId)
	END
	IF(@Operation ='E')
	BEGIN
	   SELECT ISNULL(COUNT(*),0) AS Result FROM rvlfGatewayMaster WHERE GatewayId = @GatewayId  
   AND (@GatewayMasterId IS NULL OR @GatewayMasterId='' OR GatewayMasterId <> @GatewayMasterId) AND OrganizationId = @OrganizationId 
	END
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAssignedUsers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveAssignedUsers]   
/******************************************************  
Stored Procedure Name : rvlf_sp_SaveAssignedUsers  
Purpose     : Save assigned users to a fleet  
Created by    : Uma  
Created date   : 11-Jul-09  
Updated by    :   
Updated date   :   
*******************************************************/  
  
@FleetId  bigint  = Null,  
@UserId  bigint  = Null,  
@AssignedBy  bigint  = Null  
  
AS  
  
BEGIN   
  
 IF (@FleetId > 0)  
 BEGIN  
  
  INSERT INTO rvlfFleetUsers  
   (FleetId,  
   UserId,     
   AssignedBy)  
   VALUES  
   (@FleetId,  
   @UserId,  
   @AssignedBy)  
    
 END  
  
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveAssignedVehicles]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveAssignedVehicles] 
/******************************************************
Stored Procedure Name	: rvlf_sp_SaveAssignedVehicles
Purpose					: Save assigned vehicles to a fleet
Created by				: Uma
Created date			: 10-Jul-09
Updated by				: 
Updated date			: 
*******************************************************/

@FleetId		bigint		= Null,
@VehicleId		bigint		= Null,
@IsActive		bit			= Null,
@AssignedBy		bigint		= Null

AS

BEGIN	

	IF (@FleetId > 0)
	BEGIN

		INSERT INTO rvlfFleetVehicles
			(FleetId,
			VehicleId,
			IsActive,
			AssignedBy)
			VALUES
			(@FleetId,
			@VehicleId,
			@IsActive,
			@AssignedBy)
		
	END

END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveBoxDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveBoxDetails]
(
    @vcType varchar(2),
	@intBoxId int,
	@bigFwId bigint = null,
	@intBoxProtocolTypeId int = null,
	@tiCommModeId tinyint = null,
	@vcSensorIds varchar(Max) = null,
	@vcOutputIds varchar(Max) = null
)

AS

/********************************************************************************************/
--	Name		:	rvlf_sp_SaveDeviceDetails
--	Description	:	To Add and Edit the Box Details
--	Author		:	L. Kumuthini
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	13-Nov-2009		Created Intial Version 
--              :   19-N0v-2009     Updated  by Kumuthini for including Firmware Version
/********************************************************************************************/

BEGIN
SET NOCOUNT ON 
 
  IF(@vcType = 'I') -- If Type is Insert
  BEGIN
      
	  INSERT INTO rvlfBoxSettings(BoxId, BoxProtocolTypeId, CommModeId, FwID)
		VALUES(@intBoxId, @intBoxProtocolTypeId, @tiCommModeId, @bigFwId)
  
  END
  ELSE IF(@vcType = 'U') -- If Type is Update
  BEGIN
  
	  UPDATE rvlfBoxSettings SET BoxProtocolTypeId = @intBoxProtocolTypeId, CommModeId = @tiCommModeId, FwID = @bigFwId
	  WHERE BoxId = @intBoxId
  
  END
  ELSE IF(@vcType = 'AS') -- If Type is Assign Sensors
  BEGIN
	   
	  -- Assign the Sensors to the Device	
	  INSERT INTO rvlfBoxSensorsCfg(BoxId, SensorId, AlarmLevelOn, AlarmLevelOff, ActionOn, ActionOff, SensorName)
				 (SELECT @intBoxId, SensorId, DefaultAlarmLevelOn, DefaultAlarmLevelOff, ActionOn, ActionOff, SensorName FROM rvlfSensor 
						WHERE SensorId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcSensorIds,',')))
					
  END
  ELSE IF(@vcType = 'US') -- If Type is Unassign Sensors
  BEGIN
  
       -- UnAssign the Sensors to the Device	
	   DELETE FROM rvlfBoxSensorsCfg WHERE BoxId = @intBoxId AND SensorId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcSensorIds,','))
  
  END
  ELSE IF(@vcType = 'AO') -- If Type is Assign Outputs
  BEGIN
	   
	  -- Assign the Outputs to the Device	
	  INSERT INTO rvlfBoxOutputsCfg(BoxId, OutputId, OutputName, ActionOn, ActionOff)
			 (SELECT @intBoxId, OutputId, OutputName,  
			        SUBSTRING(OutputAction ,1, CHARINDEX('/',OutputAction,1)-1),
			        SUBSTRING(OutputAction ,CHARINDEX('/',OutputAction,1)+1, LEN(OutputAction))
			        FROM rvlfOutput 
					WHERE OutputId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcOutputIds,',')))
					
  END
  ELSE IF(@vcType = 'UO') -- If Type is Unassign Outputs
  BEGIN
  
       -- UnAssign the Outputs to the Device	
	   DELETE FROM rvlfBoxOutputsCfg WHERE BoxId = @intBoxId AND OutputId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcOutputIds,','))
  
  END

	
SET NOCOUNT OFF
END





GO
/****** Object:  StoredProcedure [dbo].[rvlf_Sp_SaveBoxidRange]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_Sp_SaveBoxidRange](
@BoxId varchar(15) = NULL,
@UserId Bigint = NULL
)
AS
BEGIN
 
 INSERT INTO rvlfParamRange(Boxid,T1_Min,T1_Max,T2_Min,T2_Max,T3_Min,T3_Max,T4_Min,T4_Max,T5_Min,T5_Max,P1_Min,P1_Max,P2_Min,P2_Max,P3_Min,P3_Max,P4_Min
,P4_Max,P5_Min,P5_Max,DPs_Min,DPs_Max,DPp_Min,DPp_Max,DPp1_Min,DPp1_Max,V1_Min,V1_Max,V2_Min,V2_Max,C1_Min,C1_Max,C2_Min,C2_Max,RC1,RC2,IsActive,CreatedDate
,CreatedBy,C3_Min,C3_Max,RC3,C4_Min,C4_Max,RC4,C5_Min,C5_Max,RC5,C6_Min,C6_Max,RC6,C7_Min,C7_Max,RC7,C8_Min,C8_Max,RC8,C9_Min,C9_Max,RC9
,C10_Min,C10_Max,RC10,C11_Min,C11_Max,RC11,C12_Min,C12_Max,RC12,C13_Min,C13_Max,RC13,C14_Min,C14_Max,RC14,C15_Min,C15_Max,RC15,C16_Min,C16_Max,RC16,C17_Min,C17_Max,RC17
,C18_Min,C18_Max,RC18,C19_Min,C19_Max,RC19,P6_Min,P6_Max,P7_Min,P7_Max,P8_Min,P8_Max,P9_Min,P9_Max,P10_Min,P10_Max,P11_Min,P11_Max) values(@BoxId,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 0,0,0,0,0,0,1,GETDATE(),@UserId,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) 
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveBoxMsgSeverity]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveBoxMsgSeverity]
    @bigFleetID int = null,  
	@intBoxID int,
	@tiBoxMsgInTypeID tinyint,
	@siAlarmLevelID tinyint = 0,
	@bitIsDelete bit = 0,
	@bigOrgID int = null
AS
/******************************************************************************/
--	Name		:	rvlf_sp_SaveBoxMsgSeverity
--	Description	:	To insert / update the messages that is sent to the device
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	25-Jul-2009	MJJC	Created Intial Version 
--				:	24-Jan-2012 Sakthi save setting to all vehicles at a time
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
		 
	BEGIN TRAN MessageOutTransaction
	BEGIN TRY
	IF @intBoxID = 0 AND @bigFleetID IS NOT NULL
	BEGIN
		--Check whether the message severity is exists then delete and insert
		DELETE msg FROM rvlfBoxMsgSeverity msg INNER JOIN rvlfVehicleAssignment va ON msg.BoxId=va.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId=v.VehicleId
		INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=v.VehicleId
		INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId WHERE f.FleetId=@bigFleetID AND msg.BoxMsgInTypeId=@tiBoxMsgInTypeID
		
		INSERT INTO rvlfBoxMsgSeverity (BoxId, BoxMsgInTypeId, AlarmLevelID)   
		(SELECT va.BoxId, @tiBoxMsgInTypeID, @siAlarmLevelID FROM rvlfVehicleAssignment va INNER JOIN rvlfVehicle v ON va.VehicleId=v.VehicleId
		INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=v.VehicleId
		INNER JOIN rvlfFleet f ON f.FleetId=fv.FleetId WHERE f.FleetId=@bigFleetID)
	END
	ELSE
	BEGIN
		-- Checks whether the message severity is exists then updates else inserts
		IF EXISTS(SELECT * FROM rvlfBoxMsgSeverity WHERE BoxId=@intBoxID AND BoxMsgInTypeId = @tiBoxMsgInTypeID)
		BEGIN
			IF @bitIsDelete = 1
			BEGIN
				DELETE FROM rvlfBoxMsgSeverity WHERE BoxId=@intBoxID AND BoxMsgInTypeId = @tiBoxMsgInTypeID
			END
			ELSE
			BEGIN
				UPDATE rvlfBoxMsgSeverity SET AlarmLevelID = @siAlarmLevelID
					WHERE BoxId=@intBoxID AND BoxMsgInTypeId = @tiBoxMsgInTypeID
			END
		END
		ELSE
		BEGIN
			INSERT INTO rvlfBoxMsgSeverity (BoxId, BoxMsgInTypeId, AlarmLevelID) 
				VALUES (@intBoxID, @tiBoxMsgInTypeID, @siAlarmLevelID)
		END
	END	
	COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during processing of message severity : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveBoxOutputs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_SaveBoxOutputs]
	@intBoxID int,
	@tiOutputID tinyint,
	@vcOutputName varchar(20),
	@vcActionOn varchar(15),
	@vcActionOff varchar(15)
	
AS
/******************************************************************************/
--	Name		:	rvlf_sp_SaveBoxOutputs
--	Description	:	To update the required outputs of the devices
--				:	Insert can be used when Desktop version is created
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	30-Nov-2010	LK	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	
	UPDATE rvlfBoxOutputsCfg SET OutputName = @vcOutputName, ActionOn = @vcActionOn, ActionOff = @vcActionOff
	WHERE BoxId = @intBoxID AND OutputId = @tiOutputID
	
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveBoxSensorSeverity]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveBoxSensorSeverity]
	@intBoxID int,
	@siSensorID tinyint,
	@vcSensorName varchar(20) = null,
	@siAlarmLevelOffID tinyint = 0,
	@siAlarmLevelONID tinyint = 0,
	@vcActionOn varchar(15) = null,
	@vcActionOff varchar(15) = null,
	@bitIsDelete bit = 0
AS
/******************************************************************************/
--	Name		:	rvlf_sp_SaveBoxSensorSeverity
--	Description	:	To insert / update the messages that is sent to the device
--				:	Insert can be used when Desktop version is created
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	27-Jul-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
		 
	BEGIN TRAN MessageOutTransaction
	BEGIN TRY
		-- Checks whether the message severity is exists then updates else inserts
		IF EXISTS(SELECT * FROM rvlfBoxSensorsCfg WHERE BoxId=@intBoxID AND SensorId = @siSensorID)
		BEGIN
				UPDATE rvlfBoxSensorsCfg SET AlarmLevelOff  = @siAlarmLevelOffID,
					SensorName = CASE WHEN @vcSensorName IS NULL THEN
					rvlfSensor.SensorName ELSE @vcSensorName END,
					AlarmLevelOn = @siAlarmLevelONID, rvlfBoxSensorsCfg.ActionOn = CASE WHEN @vcActionOn IS NULL THEN
					rvlfSensor.ActionOn ELSE @vcActionOn END,
					rvlfBoxSensorsCfg.ActionOff  = CASE WHEN @vcActionOff IS NULL THEN
					rvlfSensor.ActionOff ELSE @vcActionOff END
					FROM rvlfBoxSensorsCfg  INNER JOIN rvlfSensor ON rvlfSensor.SensorId= rvlfBoxSensorsCfg.SensorId
					WHERE BoxId=@intBoxID AND rvlfBoxSensorsCfg.SensorId = @siSensorID
		END
		ELSE
		BEGIN
			INSERT INTO rvlfBoxSensorsCfg 
				(BoxId,SensorId,AlarmLevelOff, AlarmLevelOn , ActionOn, ActionOff, SensorName)
			VALUES 
				(@intBoxID, @siSensorID , @siAlarmLevelOffID , @siAlarmLevelONID , @vcActionOn, @vcActionOff, @vcSensorName)
		END
		COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during insert of the message sent : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveBulkBoxDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveBulkBoxDetails]
(   
	@intNoofVehicles int=Null,
	@bigFwId bigint = null,
	@intBoxProtocolTypeId int = null,
	@tiCommModeId tinyint = null,
	@intSeverityTempID int=Null,
	@intMakeId int=0,
	@intModelId	int=0,
	@bigOrganizationId bigint=Null,
	@bigUserId bigint=Null,
	@isTop int=1
	
) 
AS
/********************************************************************************************/
--	Name		:	rvlf_sp_SaveBulkBoxDetails 3,115,1,1,4,0,0,128,14,1
--	Description	:	To Add and Edit the Box Details
--	Author		:	S. Jeyanthi
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	23-Nov-2009		Created Intial Version 
--				:	26-Oct-2010		Included Severity Functinality 
/********************************************************************************************/

BEGIN
SET NOCOUNT ON 

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;		
DECLARE @intErrorCode int
BEGIN TRAN	
	
	 DECLARE @vcGeneratedDeviceIds 	nvarchar(500)=''
	 DECLARE @index as int=0
	 
	 WHILE @index < @intNoofVehicles
		 BEGIN
			--For checking maximum vehicle count	
			DECLARE @NoOfVehicles bigint= 0
			DECLARE @NoOfVehiclesAvailable bigint=0
			DECLARE @NoOfVehiclesPending bigint=0
		
			SET @NoOfVehicles =(SELECT NoOfVehicles FROM rvlfOrganization WHERE OrganizationId =  @bigOrganizationID)  
			SET @NoOfVehiclesAvailable =(SELECT Count(VehicleId)  FROM rvlfVehicle WHERE OrganizationId =  @bigOrganizationID)  
			SET @NoOfVehiclesPending =ISNULL(@NoOfVehicles,0)-ISNULL(@NoOfVehiclesAvailable,0)
			
			--PRINT 'NoOfVehiclesPending' + Cast(@NoOfVehiclesPending as nvarchar)
			
			IF @NoOfVehiclesPending >0			
			BEGIN
				-- Start Box ID Creation(It will take the deleted IDs or new one)
				DECLARE @intBoxId int		
				EXEC dbo.rvlf_sp_GenerateBulkBoxId @isTop,@intBoxId OUTPUT
				-- End Box ID Creation

				 --Start Device Creation
				 IF NOT EXISTS (SELECT TOP 1 BoxId FROM rvlfBoxSettings WHERE BoxId=@intBoxId)
				 BEGIN
					INSERT INTO rvlfBoxSettings(BoxId, BoxProtocolTypeId, CommModeId, FwID)
					VALUES(@intBoxId, @intBoxProtocolTypeId, @tiCommModeId, @bigFwId) 
				 END
				--End Device Creation
			    
			    
				--Start Vehicle Creation and Default values setting in rvlfMsgInHst,rvlfBoxId and Severity Settings
				DECLARE @vcOrganizationCode varchar(20) =(SELECT OrganizationCode from rvlfOrganization where OrganizationId=@bigOrganizationId)				


				DECLARE @vcVehicleName varchar(20) =@vcOrganizationCode + '_veh_' + (select CAST(COUNT(VehicleId)+1 AS VARCHAR) FROM rvlfVehicle WHERE  OrganizationId=@bigOrganizationId )	    
			   
				DECLARE @bigVehicleId bigint=0
			   
				EXEC rvlf_sp_SaveBulkVehicleInfo @intBoxId,null,1, @vcVehicleName,@intMakeId,@intModelId,@bigUserId,@bigOrganizationId, @bigVehicleId OUTPUT
				--End Vehicle Creation
			    
			 
				--Start Assign Sensor and Outputs to the seveice	    
				DECLARE @vcSensorIds varchar(Max) = null
				DECLARE @vcOutputIds varchar(Max) = null
			    
				IF @intSeverityTempID IS NOT NULL
				BEGIN 
					SELECT @vcSensorIds=SensorIds, @vcOutputIds=OutputIds from rvlfSeverityTemplate where SeverityTempId =@intSeverityTempID  
				END
			    
				IF @vcSensorIds IS NOT NULL
					BEGIN
						-- Assign the Sensors to the Device	
						IF NOT EXISTS (SELECT TOP 1 BoxId FROM rvlfBoxSensorsCfg WHERE BoxId=@intBoxId)
						BEGIN
							INSERT INTO rvlfBoxSensorsCfg(BoxId, SensorId, AlarmLevelOn, AlarmLevelOff, ActionOn, ActionOff, SensorName)
							(SELECT @intBoxId, SensorId, DefaultAlarmLevelOn, DefaultAlarmLevelOff, ActionOn, ActionOff, SensorName FROM rvlfSensor 
							WHERE SensorId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcSensorIds,',')))
						END
						--End Assign Sensors
					END
				
				IF @vcOutputIds IS NOT NULL
					BEGIN
					-- Assign the Outputs to the Device	
					IF NOT EXISTS (SELECT TOP 1 BoxId FROM rvlfBoxOutputsCfg WHERE BoxId=@intBoxId)
					BEGIN
						INSERT INTO rvlfBoxOutputsCfg(BoxId, OutputId)
						(SELECT @intBoxId, OutputId FROM rvlfOutput 
						WHERE OutputId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcOutputIds,',')))
					END
						--END Assign Outputs
					END
			    --End Assign Sensor and Outputs to the seveice
			  
			  --Concatenate the created Device IDs  
			 SET @vcGeneratedDeviceIds += CAST(@intBoxId as nvarchar) + ','
		 END
		    
		    SET @index +=1
		END 	

	
		SELECT REVERSE(STUFF(REVERSE(@vcGeneratedDeviceIds),charindex(',',REVERSE(@vcGeneratedDeviceIds)), 1, '')) DeviceIds
	
		SELECT @intErrorCode=@@ERROR
		IF (@intErrorCode <> 0) GOTO PROBLEM
		
COMMIT TRAN
	
PROBLEM:

	IF (@intErrorCode <> 0) 
	BEGIN
		PRINT 'Unexpected error occurred!'
		ROLLBACK TRAN
	END   	
				
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveBulkVehicleInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveBulkVehicleInfo]     
/************************************************************************************/    
-- Name  : rvlf_sp_SaveBulkVehicleInfo    5,null,1,'ADR_veh_4',1,1,18,86,0
-- Description : To insert the vehicle information    
-- Author  : S. Jeyanthi.    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 23-Oct-2010 SJ Created Intial Version     
--    : 15-Dec-2011 Sakthi Move the created box id to ET database also    
/************************************************************************************/    
 @intBoxId				int      = Null,    
 @bigVehicleId			bigint   = Null,    
 @tiVehicleTypeID		tinyint   = Null,    
 @vcVehicleName			varchar(20)  = Null,    
 @intMakeId				int =0,     
 @intModelId			int =0,    
 @bigProcessedBy		bigint = Null,     
 @bigOrganizationId		bigint,    
 @returnId				bigint OUTPUT    
AS    
BEGIN    
 SET NOCOUNT ON

 SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
 DECLARE @intErrorCode int
 BEGIN TRAN
	 DECLARE @uiLicensePlate uniqueidentifier = NEWID()
	 DECLARE @vcLicensePlate nvarchar(50) = RIGHT(@uiLicensePlate,10)
     
	 DECLARE @bigTimeZoneId bigint = 3
	 DECLARE @bitNotify bit = 0, @bitWarning bit = 0, @bitCritical bit = 1
	 DECLARE @dtProcessedDateTime DateTime = GetDate()
      
	 INSERT INTO rvlfVehicle (LicensePlate, VehicleTypeId, StateProvince, VehicleDescription,MakeId, ModelId,OrganizationId, IconTypeId,    
	 TimeZone, DayLightSaving, Notify, Critical, Warning, AutoAdjustDayLightSaving, CreatedBy, CreatedDateTime,IsEmailSent,IsSMSSent,RptInterval,SpdThreshold)     
	 VALUES (@vcLicensePlate, @tiVehicleTypeID, 'Tamil Nadu', @vcVehicleName,@intMakeId,@intModelId, @bigOrganizationId, 1, @bigTimeZoneId, 0, @bitNotify, 
	 @bitCritical, @bitWarning, 0, @bigProcessedBy, @dtProcessedDateTime, 0,0,'00:10:00',100)    
            
	 SET @bigVehicleId = @@IDENTITY    
            
	 IF @bigVehicleId > 0     
	 BEGIN    
		--EXEC rvlf_sp_Save_notificationsList @tblNotificationsList,4,@bigVehicleId    
             
		-- Insert the created vehicle with its Box Id in the Vehicle Assignment Table    
		INSERT INTO rvlfVehicleAssignment (BoxId, VehicleId, AssingedBy, AssignedDateTime, ServiceID)    
		VALUES (@intBoxId, @bigVehicleId, @bigProcessedBy, @dtProcessedDateTime, 1)    
             
		-- Select the Default Fleet Id for the particular Organization    
             
		DECLARE @bigDefaultFleetId AS BIGINT = 0    
             
		SELECT @bigDefaultFleetId = FleetId FROM rvlfFleet WHERE OrganizationId = @bigOrganizationId AND IsDefault = 1    
             
		-- Assign the created vehicle into default fleet of the particular Organization    
             
		INSERT INTO rvlfFleetVehicles (FleetId, VehicleId, IsActive, AssignedBy, AssignedDate)    
		VALUES (@bigDefaultFleetId, @bigVehicleId, 1 , @bigProcessedBy, @dtProcessedDateTime)    
             
		DECLARE @uiMsgInID uniqueidentifier = NEWID()    
    
		INSERT INTO rvlfMsgInHst (MessageInID, BoxId, OriginDateTime, DateTimeReceived,ServiceID, BoxMsgInTypeId,    
		BoxProtocolTypeId, CommInfo1, CommInfo2, ValidGps, Latitude, Longitude, Speed, Heading, SensorMask, CustomProp,    
		StreetAddress, SequenceNum, IsArmed, NearestLandmark, Priority, IsNotificationSent, LandMarkID ) VALUES     
		( @uiMsgInID , @intBoxID, SYSUTCDATETIME(), SYSUTCDATETIME(),1,1,    
		1,NULL,NULL,1,0.000000,0.000000,0,0,'00000000','Odometer=1;Fuel%=0','N/A',NULL,0,'N/A',0,0,NULL)  
          
		INSERT INTO rvlfBoxId(BoxId,FwChId,BoxArmed,LastValidDateTime,LastLatitude,LastLongitude,LastSpeed,LastStreetAddress,  
		LastCommunicatedDateTime,LastSensorMask,OrganizationId,LastStatusDateTime,NearestLandmark,Heading,MessageInId)  
		VALUES (@intBoxID,NULL,0,SYSUTCDATETIME(),10.997237,76.987802,0,'N/A',    
		DATEADD(MI,3,SYSUTCDATETIME()),'00000000', @bigOrganizationID, DATEADD(MI,1,SYSUTCDATETIME()),    
		'N/A', 0, @uiMsgInID)        

		--INSERT INTO rvlfBoxId VALUES (@intBoxID,NULL,0,SYSUTCDATETIME(),10.997237,76.987802,0,'N/A',    
		-- DATEADD(MI,3,SYSUTCDATETIME()),'00000000', @bigOrganizationID, DATEADD(MI,1,SYSUTCDATETIME()),    
		-- 'N/A', 0, @uiMsgInID)    
         
		--Insert new box id to ET Database    
		--INSERT INTO TRINETRA_ET.dbo.rvlfBoxId VALUES (@intBoxID,NULL,0,SYSUTCDATETIME(),10.997237,76.987802,0,'N/A',    
		-- DATEADD(MI,3,SYSUTCDATETIME()),'00000000', @bigOrganizationID, DATEADD(MI,1,SYSUTCDATETIME()),    
		-- 'N/A', 0, @uiMsgInID,NULL,null,NULL)    
    
		--INSERT INTO ETSERVER.TRINETRA_ET.DBO.rvlfBoxId (BoxId,FwChId,BoxArmed,LastValidDateTime,LastLatitude,LastLongitude,LastSpeed,LastStreetAddress,  
		--LastCommunicatedDateTime,LastSensorMask,OrganizationId,LastStatusDateTime,NearestLandmark,Heading,MessageInId,  
		--MaxSMSLimit,LastStreetAddress_AR,MessageDetails)  
		--VALUES (@intBoxID,NULL,0,SYSUTCDATETIME(),10.997237,76.987802,0,'N/A',    
		--DATEADD(MI,3,SYSUTCDATETIME()),'00000000', @bigOrganizationID, DATEADD(MI,1,SYSUTCDATETIME()),    
		--'N/A', 0, @uiMsgInID,NULL,null,NULL) 
         
		INSERT INTO rvlfBoxMsgSeverity     
		SELECT @intBoxID,b.BoxMsgInTypeId, p.DefaultAlarmLevel FROM rvlfBoxMsgInType b     
		INNER JOIN rvlfBoxProtocolMsgInType p ON b.BoxMsgInTypeId = p.BoxMsgInTypeId    
		WHERE b.OperationTypeID IN     
		(SELECT OperationID FROM rvlfPackageOperations WHERE PackageId =	(SELECT PackageId FROM rvlfOrganizationPackage 
																			WHERE OrganizationID = (SELECT OrganizationID     
																									FROM rvlfVehicle v 
																									INNER JOIN rvlfVehicleAssignment va 
																									ON v.VehicleID = va.VehicleID		
																									WHERE va.BoxID = @intBoxID) 
																			AND IsActive=1))
		AND b.CanSeveritySet = 1 AND b.BoxMsgInTypeId NOT IN (SELECT BoxMsgInTypeId FROM rvlfBoxMsgSeverity WHERE BoxId = @intBoxID)


		--insert into rvlfMAKDevices              
		--(BoxId,SubTypeId,EquipmentName,OrganizationId,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate,IsDelete,VehicleId)              
		--values(@intBoxID,@tiVehicleTypeID, @vcVehicleName,@bigOrganizationId,@bigProcessedBy,@dtProcessedDateTime,null,null,0,@bigVehicleId)
	END          

	 --If an error raised, passed the error code into a variable.If it is, go to problem.    
	 SELECT @intErrorCode=@@ERROR    
	 IF (@intErrorCode <> 0) GOTO PROBLEM      
	 COMMIT TRAN       
		SET @returnId = ISNULL(@bigVehicleId,0)    
       
	 --If an error raised, message will be displayed.    
	 PROBLEM:    
    
	 IF (@intErrorCode <> 0)     
	 BEGIN    
		PRINT 'Unexpected error occurred!'    
		ROLLBACK TRAN    
	 END
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveCarMakeSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_SaveCarMakeSettings]
	@CarId bigint=null,
	@MakeId bigint=null,
	@CarMakeName varchar(50)=null
	
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_SaveCarMakeSettings]
--	Description	:	To save the Car Make setting details
--	Author		:	V.Muthukumaravadivel
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	24-Feb-2011	VN	Created Intial Version 
/******************************************************************************/
BEGIN
		
	IF(@CarId >0)
		BEGIN
			UPDATE rvlfMake SET MakeName=@CarMakeName
			WHERE MakeId=@MakeId  		
		END
	ELSE
		BEGIN
			INSERT INTO rvlfMake(MakeName)
				VALUES(@CarMakeName)
		END
		
    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveCarModelSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE Procedure [dbo].[rvlf_sp_SaveCarModelSettings]  
 @CarId bigint=null,  
 @ModelId bigint=null,  
 @CarModelName varchar(50)=null,  
 @MakeId int=null,  
 @bigVehicleId bigint=null  
   
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_SaveCarModelSettings]  
-- Description : To save the Car Model setting details  
-- Author  : V.Muthukumaravadivel  
-- Company : Angler Technologies  
-- History : <<Date(dd-MON-yyyy)>> Initial Reason  
--         : 24-Feb-2011 VN Created Intial Version   
--         : 10-Nov-2011 Ranjith Model Update Condition issue
/******************************************************************************/  
BEGIN  
    
 IF(@CarId >0)  
  BEGIN  
   UPDATE rvlfModel SET ModelName=@CarModelName,MakeId=@MakeId,VehicleTypeId=@bigVehicleId  
   WHERE ModelId=@ModelId      
  END  
 ELSE  
  BEGIN  
   INSERT INTO rvlfModel(ModelName,MakeId,VehicleTypeId)  
    VALUES(@CarModelName,@MakeId,@bigVehicleId)  
  END  
    
      
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveDelayNotification]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================                        
-- Author:  Vijay.N                        
-- Create date: 20-Apr-2012                        
-- Description: Initial Version                         
--    : Vijay.N - To Save the Delay notification  
-- rvlf_sp_SaveTimeBasedGeozone 999983,'13,21',null,null,null,null,null,null,null,1,0,NULL                    
-- =============================================                        
CREATE PROCEDURE [dbo].[rvlf_sp_SaveDelayNotification]            
 -- Add the parameters for the stored procedure here                        
 --@VehicleId BIGINT,                        
 @BoxId BIGINT,                        
 @GeozoneId Varchar(500),                     
 @Trip1Time TIME = '00:00:00.0000000',            
 @Trip1GraceTime TINYINT = 0,            
 @Trip2Time TIME = '00:00:00.0000000',                
 @Trip2GraceTime TINYINT = 0,            
 @Trip3Time TIME = '00:00:00.0000000',                
 @Trip3GraceTime TINYINT = 0,             
 @RecurrenceDays VARCHAR(15) = NULL,                        
 @IsFromGeozoneVehicle BIT = 1,                        
 @IsAssign BIT = 1,                    
 @IsGeozoneVehicle BIT = NULL,      
@bigQueryingUser BIGINT = NULL,   
@IsUnAuthorizedGeozone BIT  = 0
                         
AS                        
BEGIN                        
 -- SET NOCOUNT ON added to prevent extra result sets from                        
 -- interfering with SELECT statements.                        
 SET NOCOUNT ON;                        
                        
    -- Insert statements for procedure here      
      
          
     DECLARE @HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0      
                                     
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded      
  FROM rvlfUserPreferences up                                   
   INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId                                      
  WHERE UP.UserId  = @bigQueryingUser      
          
  IF(@Trip1Time <> CAST('00:00:00.0000000' AS TIME(7)))
  BEGIN      
 SET @Trip1Time = DATEADD(MINUTE,-@MinsToBeAdded,DATEADD(HOUR,-@HoursToBeAdded,@Trip1Time))
  END
        
  IF(@Trip2Time <> CAST('00:00:00.0000000' AS TIME(7)))
  BEGIN      
 SET @Trip2Time = DATEADD(MINUTE,-@MinsToBeAdded,DATEADD(HOUR,-@HoursToBeAdded,@Trip2Time))
  END      
        
  IF(@Trip3Time <> CAST('00:00:00.0000000' AS TIME(7)))      
  BEGIN      
 SET @Trip3Time = DATEADD(MINUTE,-@MinsToBeAdded,DATEADD(HOUR,-@HoursToBeAdded,@Trip3Time))      
  END      
                   
    DECLARE @geoId BIGINT = 0                       
                            
    IF (@IsAssign = 1)                        
    BEGIN                        
                        
  IF (@IsGeozoneVehicle IS NOT NULL)                    
  BEGIN                    
   SELECT @geoId = GeozoneId from rvlfOrganizationGeozone where GeozoneNo IN (SELECT * FROM DBO.rvlf_fn_ConvertArrayToTable(@GeozoneId,','))                    
  END                    
  ELSE                    
  BEGIN                    
   SET @geoId = CAST(@GeozoneId AS BIGINT)                    
  END                        
                        
 IF EXISTS(SELECT * FROM DBO.rvlfDelayNotify WHERE Boxid = @BoxId AND GeozoneId = @geoId)              
 BEGIN               
  DELETE FROM DBO.rvlfDelayNotify WHERE BoxId = @BoxId AND GeozoneId = @geoId              
 END              
              
  INSERT INTO DBO.rvlfDelayNotify (BoxId,GeozoneId,Trip1time,Trip1Gracetime,Trip2time,Trip2Gracetime,Trip3time,Trip3Gracetime,RecurrenceDays,AssignedBy,IsUnAuthorisedGeoZone)
  VALUES(@BoxId,@geoId,@Trip1Time,@Trip1GraceTime,@Trip2Time,@Trip2GraceTime,@Trip3Time,@Trip3GraceTime,@RecurrenceDays,@bigQueryingUser,@IsUnAuthorizedGeozone)
                  
 END                        
 ELSE                        
 BEGIN                        
                     
 IF (@IsGeozoneVehicle IS NOT NULL)                    
  BEGIN                    
   SELECT @geoId= GeozoneId from rvlfOrganizationGeozone where GeozoneNo IN (SELECT * FROM DBO.rvlf_fn_ConvertArrayToTable(@GeozoneId,','))                    
                       
   DELETE rvlfDelayNotify WHERE  BoxId = @BoxId AND GeozoneId = @geoId                    
  END                    
  ELSE                    
  BEGIN                     
   DELETE rvlfDelayNotify WHERE  BoxId = @BoxId AND GeozoneId IN (SELECT * FROM DBO.rvlf_fn_ConvertArrayToTable(@GeozoneId,','))                    
   --SET @GeozoneId = CAST(@GeozoneId AS BIGINT)                    
  END                    
                      
 END                        
                         
 SET NOCOUNT OFF;                         
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveDeviceMgmt]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_SaveDeviceMgmt]                            
	@EquipmentID				varchar(50)		 =	NULL,               
	@EquipmentTypeID			INT=NULL,              
	@SubTypeId					TINYINT=NULL,                                        
	@EquipmentName				NVARCHAR(40),                                        
	@DOP						DATETIME=null,                                        
	@CustomerName				VARCHAR(50)   =	NULL,                                        
	--@Address					NVARCHAR(250) =	NULL,                                        
	@WarrantyStartDate			DATETIME	  =	NULL,                                        
	@WarrantyEndDate			DATETIME	  =	NULL,                                  
	@ContactNo					VARCHAR(15)   =	NULL,                                  
	@AddnlInfo					NVARCHAR(250) =	NULL,                                  
	@AMC						BIT			  =	NULL,                                  
	@AMCStartDate				DATETIME	  =	NULL,                                  
	@AMCEndDate					DATETIME	  =	NULL,                     
	@Email						VARCHAR(100)  =	NULL,                 
	@CustomerID					INT			  =	NULL,                              
	@OrgId						BIGINT		  =	NULL,                                  
	@UserID						INT			  =	NULL,                                    
	@tblNotificationsList		XML			  =	NULL,                                    
	@tblAMCNotificationsList	XML			  = NULL,        
	@OpenEngineHrs				INT			  =	0,
	--@EquipmentSrNo				NVARCHAR(40)  = NULL,
	@EquipmentLoca				TINYINT		  = NULL,
	@bitWarning1				BIT			  = NULL,
	@bitWarning2				BIT			  = NULL,
	@bitCritical				BIT			  = NULL,
	@bitIsSave					BIT			  = NULL,
	@EquipmentSrNo              NVARCHAR(250) =	NULL,
	@SNO                        NVARCHAR(250) =	NULL,
	@tblShift					XML			  = NULL,
	@tblCompactor				XML			  = NULL,
	@vfantype					TINYINT = 0,
	@bitMain					Bit =NULL,
	@bitAddParams				Bit =NULL,	
	@bitCompactor				Bit =NULL,
	@NoAlarm                    Bit =NULL,
	@ElecTrip					Bit =NULL,
	@Shutdown					Bit =NULL
	--@Currentforfan				float =null
as                       
/******************************************************************************/                                                              
-- Name  : rvlf_sp_SaveDeviceMgmt null,332323,2,'ghg ghfghfghfgh','24-jun-2014','name','gdfggdfg','30-jun-2014','30-jun-2014','4456564564','fggfhgh',1,'30-jun-2014','30-jun-2014','tter@dfg.dfg',86,292                
-- Description : save Mak device in the table                      
-- Author  : Gopal.R                      
-- Company  : Angler Technologies                      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason
--			: Modified on 29-Mar-2019 Compactor Details implemented by Asan N                      
--Created Date -11-jun-2014                       
/******************************************************************************/                       
begin                            
--set @SerialNo=(select MAX(Sno) from rvlfMAKDevices)+1                           
--To avoid default date insertion 1/1/1900
set @DOP = case when @DOP is null or @DOP ='' or LEN(@DOP)=0 then null else @DOP end
/****************************Reading XML File and Store into Temp table**************/                               
DECLARE @docHandle int                                 
Declare @noofShif INT
Declare @shiftType int
DECLARE  @temptable TABLE (UserID Bigint,Email bit,SMS bit)                                    
IF @tblNotificationsList IS NOT NULL                               
BEGIN                                              
	EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblNotificationsList                                                       
	INSERT INTO @tempTable                                                                    
	SELECT * FROM OPENXML(@docHandle, '/DocumentElement/Notification')                             
	WITH                               
	( 
	UserID bigint 'UserID'                                        
	,Email  bit  'Email'                                                                  
	,SMS bit  'SMS'                              
	)                                    
END                              

DECLARE @tblNotificationsListTmp AS NotificaitonUserList                             
INSERT INTO @tblNotificationsListTmp                            
SELECT * FROM @temptable                            
                              
 /**************************************************************************************/ 

/************* Reading XML File and Shift into Temp table******************************/
DECLARE @TempShift TABLE ([Shift] VARCHAR(10),ShiftType varchar(10),NoofShift VARCHAR(10),StratTime VARCHAR(10),EndTime VARCHAR(10))
 IF @tblShift IS NOT NULL                               
BEGIN                                              
	EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblShift                                                       
	INSERT INTO @TempShift                                                                    
	SELECT [Shift],ShiftType,NoofShift,FORMAT(CAST(StratTime AS DATETIME),'hh:mm tt') AS StratTime,FORMAT(CAST(EndTime AS DATETIME),'hh:mm tt') AS EndTime FROM OPENXML(@docHandle, '/DocumentElement/Shift')                             
	WITH                               
	( 
	[Shift] VARCHAR(10) 'Shift'                                        
	,ShiftType  varchar(10)  'ECType'                                                                  
	,NoofShift varchar(10)  'NoofShift'           
	,StratTime Varchar(10) 'StartTime'
	,EndTime Varchar(10) 'EndTime'                   
	)                                    
END                    
SELECT top 1 @noofShif=NoofShift,@shiftType=ShiftType FROM @TempShift   
 /**************************************************************************************/

 /************* Reading XML File and Compactor into Temp table******************************/
 DECLARE @TempCompactor TABLE (CompType TINYINT,CompModel varchar(15),IsVentilator bit,VentilatorModel VARCHAR(15),SeqNo TINYINT)
 IF @tblCompactor IS NOT NULL                               
BEGIN                                              
	EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblCompactor                                                       
	INSERT INTO @TempCompactor                                                                    
	SELECT CompType,CompModel,IsVentilator,VentilatorModel,SeqNo FROM OPENXML(@docHandle, '/DocumentElement/Compactor')                             
	WITH                               
	( 
	 CompType VARCHAR(10) 'CompType'                                        
	,CompModel  varchar(15)  'CompModel'                                                                  
	,IsVentilator varchar(10)  'IsVentilator'           
	,VentilatorModel Varchar(15) 'VentilatorModel'
	,SeqNo Varchar(10) 'SeqNo'                   
	)                                    
END  
/**************************************************************************************/
 SET @vfantype = (select count(*) from @TempCompactor)
                        
DECLARE @VehicleID int                        
SET NOCOUNT ON;                        
DECLARE @trancount INT;                        
SET @trancount = @@trancount;
DECLARE @Esno INT 
BEGIN TRY                        
IF @trancount = 0                        
	BEGIN TRANSACTION                        
ELSE                        
	SAVE TRANSACTION rvlf_sp_SaveDeviceMgmt;
                                
IF (@bitIsSave = 1)
BEGIN                               
	IF not exists (select BoxId from rvlfMAKDevices where (BoxId=@EquipmentID or EquipmentName=@EquipmentName) and IsDelete=0)                                
	BEGIN                    
		insert into rvlfVehicle (VehicleTypeId,VehicleDescription,OrganizationId,TimeZone,CreatedBy,CreatedDateTime,ModifiedBy,                                    
		[Modified DateTime],DisplayName,Location,InstalledDate,OpeningEngineHours,Notify,Warning,Critical,NoAlarms,ElecTripAlert,ShutdownAlert) Values                       
		(@EquipmentTypeID,@EquipmentName,@OrgId,100,@UserID,GETUTCDATE(),null,null,@EquipmentName,null,GETUTCDATE(),@OpenEngineHrs,@bitWarning1,@bitWarning2,@bitCritical,@NoAlarm,@ElecTrip,@Shutdown)
		   
		   select top 1 @VehicleID=VehicleId from rvlfVehicle where VehicleDescription=@EquipmentName and OrganizationId=@OrgId and CreatedBy=@UserID                              
 order by VehicleId desc 
                                                     
		--select top 1 @VehicleID=VehicleId from rvlfVehicleAssignment where BoxId=@EquipmentID order by VehicleId desc                              
                  
		--Update rvlfVehicle SET VehicleDescription = @EquipmentName, VehicleTypeId = @EquipmentTypeId,
		--Notify = @bitWarning1, Warning = @bitWarning2, Critical = @bitCritical, ModifiedBy = @UserID, [Modified DateTime] = GETUTCDATE()		 
		--Where VehicleID = @VehicleID

		insert into rvlfMAKDevices              
		(BoxId,SubTypeId,EquipmentName,DateOfPurchase,CustomerName,ContactNo,WarrantyStDate,WarrantyEndDate,AMCStDate,AMCEndDate,              
		AdditionalInfo,OrganizationId,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate,IsDelete,VehicleId,Email,CustomerId,EquipmentLoca,EConsumptionType,NoofShifts,VFantype,IsMainScr,isAddParams)
		values(@EquipmentID,@EquipmentTypeID,@EquipmentName,@DOP,@CustomerName,@ContactNo,@WarrantyStartDate,@WarrantyEndDate,@AMCStartDate,
		@AMCEndDate,@AddnlInfo,@OrgId,@UserID,GETUTCDATE(),null,null,0,@VehicleID,@Email,@CustomerID,@EquipmentLoca,@shiftType,@noofShif,@vfantype,@bitMain,@bitAddParams) 		

			                 
		EXEC rvlf_sp_Save_notificationsList @tblNotificationsListTmp,4,@VehicleID                                      
                              
		insert into rvlfBoxSettings(BoxId,BoxProtocolTypeId,CommModeId,FwID) values(@EquipmentID,1,1,16)                        
       -- delete from rvlfVehicleAssignment where VehicleId=  @VehicleID                 
		insert into rvlfVehicleAssignment (BoxId,VehicleId,AssingedBy,AssignedDateTime,IsDeleted,DeletedDateTime,ServiceID)                                    
		values(@EquipmentID,@VehicleID,@UserID,GETUTCDATE(),0,null,1)                                    
                              
		-- Select the Default Fleet Id for the particular Organization                                                        
		 DECLARE @bigDefaultFleetId AS BIGINT = 0                                                        
		SELECT @bigDefaultFleetId = FleetId FROM rvlfFleet WHERE OrganizationId = @OrgId AND IsDefault = 1         
		--delete from rvlfFleetVehicles where VehicleId=  @VehicleID                 
		-- Assign the created vehicle into default fleet of the particular Organization                                        
		INSERT INTO rvlfFleetVehicles (FleetId, VehicleId, IsActive, AssignedBy, AssignedDate)                                          
		 VALUES (@bigDefaultFleetId, @VehicleId, 1 , @UserID, GETUTCDATE())                                          
    
		DECLARE @uiMsgInID uniqueidentifier = NEWID()                                          
		--Commented becuse of client req, not to show until device communicate (22-jan-2015)           
		--INSERT INTO rvlfMsgInHst (MessageInID, BoxId, OriginDateTime, DateTimeReceived,ServiceID, BoxMsgInTypeId,                                          
		-- BoxProtocolTypeId, CommInfo1, CommInfo2, ValidGps, Latitude, Longitude, Speed, Heading, SensorMask, CustomProp,                                          
		-- StreetAddress, SequenceNum, IsArmed, NearestLandmark, Priority, IsNotificationSent, LandMarkID ) VALUES                                           
		-- (@uiMsgInID , @EquipmentID, SYSUTCDATETIME(), SYSUTCDATETIME(),1,160,                                
		-- 1,NULL,NULL,1,0.000000,0.000000,0,0,'00000000',null,'N/A',NULL,0,'N/A',0,0,NULL)                                          
                                 
		INSERT INTO rvlfBoxId(BoxId,FwChId,BoxArmed,LastValidDateTime,LastLatitude,LastLongitude,LastSpeed,LastStreetAddress,LastCommunicatedDateTime,LastSensorMask,OrganizationId,LastStatusDateTime,NearestLandmark,Heading,MessageInId,MaxSMSLimit,LastStreetAddress_AR,LastStreetAddress_Hin,OTASeqNoLastpdated,ControllerID,WeatherInfo,GateWayID) VALUES (@EquipmentID,NULL,0,SYSUTCDATETIME(),10.997237,76.987802,0,'N/A',                                          
		 DATEADD(MI,3,SYSUTCDATETIME()),'00000000', @OrgId, DATEADD(MI,1,SYSUTCDATETIME()),                                          
		 'N/A', 0, @uiMsgInID,0,null,null,null,null,null,null)                                          
                               
		INSERT INTO rvlfBoxMsgSeverity    
		SELECT @EquipmentID,b.BoxMsgInTypeId, p.DefaultAlarmLevel FROM rvlfBoxMsgInType b                                           
		INNER JOIN rvlfBoxProtocolMsgInType p ON b.BoxMsgInTypeId = p.BoxMsgInTypeId                                          
		WHERE b.OperationTypeID IN    
		(SELECT OperationID FROM rvlfPackageOperations WHERE PackageId =                                           
		(SELECT PackageId FROM rvlfOrganizationPackage WHERE OrganizationID = (SELECT OrganizationID                                           
		FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID                                           
		WHERE va.BoxID = @EquipmentID) AND IsActive=1))    
		AND b.CanSeveritySet = 1 AND b.BoxMsgInTypeId NOT IN                   
		(SELECT BoxMsgInTypeId FROM rvlfBoxMsgSeverity WHERE BoxId = @EquipmentID)   
		
	    --INSERT INTO rvlf_EnergyConsumption(EquipmentId,EConsumptionType,NoofShift,StartTime,EndTime,[Shift])
	    --SELECT @EquipmentID,ShiftType,NoofShift,StratTime,EndTime,[Shift] FROM @TempShift	

		--IF(@vfantype > 0)
		--BEGIN
		------------------------Save Compactor Details-------------------------------
		--INSERT INTO rvlf_CompactorDetails(DeviceId,CompType,CompModel,IsVentilator,VentilatorModel,SeqNo)
		--SELECT @EquipmentID,CompType,CompModel,IsVentilator,VentilatorModel,SeqNo FROM @TempCompactor
		-----------------------------------------------------------------------------
		--END 
		------ BoxId Range insert ------ Added by Asan
		EXEC rvlf_Sp_SaveBoxidRange @EquipmentID,@UserID
		                                 
	END                                
	ELSE                            
		RAISERROR('Equipment Id already exists',0,1)                         
END                        
---------------------------------------Update device detials------------------------------------------------------------                               
ELSE                                    
BEGIN                                     
	UPDATE rvlfMAKDevices SET
	SubTypeId=@EquipmentTypeID,                                    
	EquipmentName=@EquipmentName, 
	--EquipmentSrNo=@EquipmentSrNo,
	DateOfPurchase=@DOP,      
	CustomerName=@CustomerName,                                    
	--EquipmentLocation=@Address,                              
	ContactNo=@ContactNo,                                    
	WarrantyStDate=@WarrantyStartDate,                                    
	WarrantyEndDate=@WarrantyEndDate, 
	EquipmentLoca=@EquipmentLoca,                                                                      
	AdditionalInfo=@AddnlInfo,                         
	Email=@Email,          
	EConsumptionType=@shiftType,
	NoofShifts=@noofShif,                     
	OrganizationId=@OrgId,               
	CustomerId=@CustomerID,                                   
	ModifiedBy=@UserID,                                    
	ModifiedDate=GETUTCDATE(),VFantype =@vfantype,IsMainScr =@bitMain,isAddParams=@bitAddParams WHERE BoxId=@EquipmentID and OrganizationId=@OrgId                                    
                              
	UPDATE rvlfVehicle SET VehicleDescription=@EquipmentName,VehicleTypeId=@EquipmentTypeID,--Location=@Address,
	Notify = @bitWarning1, Warning = @bitWarning2, Critical = @bitCritical,
	[Modified DateTime]=GETUTCDATE(), ModifiedBy=@UserID,OpeningEngineHours=@OpenEngineHrs,NoAlarms=@NoAlarm,ElecTripAlert=@ElecTrip,ShutdownAlert=@Shutdown 
	WHERE VehicleId = (SELECT VehicleId FROM rvlfMAKDevices WHERE BoxId=@EquipmentID and IsDelete = 0 and OrganizationId=@OrgId) 
	--WHERE VehicleId = (SELECT VehicleId FROM rvlfMAKDevices WHERE BoxId=@EquipmentID and IsDelete !=0)        
                               
	--select @VehicleID=VehicleId from rvlfVehicleAssignment where BoxId=@EquipmentID                            
	SELECT @VehicleID=VehicleId FROM rvlfMAKDevices WHERE BoxId=@EquipmentID and IsDelete = 0
                                 
	DELETE FROM rvlfNotificationList WHERE TypeID = @VehicleID AND NotificationType = 4           
	EXEC rvlf_sp_Save_notificationsList @tblNotificationsListTmp,4,@VehicleID     
	
	--DELETE FROM  rvlf_EnergyConsumption WHERE EquipmentId=@EquipmentID
	
	--INSERT INTO rvlf_EnergyConsumption(EquipmentId,EConsumptionType,NoofShift,StartTime,EndTime,[Shift])
	--SELECT @EquipmentID,ShiftType,NoofShift,StratTime,EndTime,[Shift] FROM @TempShift	 
	
	--DELETE FROM  rvlf_CompactorDetails WHERE DeviceId=@EquipmentID
 --  ------------------------Save Compactor Details-------------------------------
 --  INSERT INTO rvlf_CompactorDetails(DeviceId,CompType,CompModel,IsVentilator,VentilatorModel,SeqNo)
 --  SELECT @EquipmentID,CompType,CompModel,IsVentilator,VentilatorModel,SeqNo FROM @TempCompactor
 --  -----------------------------------------------------------------------------  
                                  
END                                                   
LBEXIT:                        
    IF @trancount = 0                           
		COMMIT;                        
    END TRY                        
    BEGIN CATCH                        
		DECLARE @error int, @message varchar(4000), @xstate int;                        
        SELECT @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();                        
		if @xstate = -1                        
            ROLLBACK;                        
        if @xstate = 1 and @trancount = 0                        
            ROLLBACK                        
        if @xstate = 1 and @trancount > 0                        
            ROLLBACK TRANSACTION usp_my_procedure_name;                        
        RAISERROR ('Insert / Update Failed %d: %s', 16, 1, @error, @message) ;                        
    END CATCH                                 
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveDriverAssignment]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveDriverAssignment]
	@bigDriverId bigint=null,
	@bigVehicleId bigint=null,
	@dtFromDate datetime=null,
	@dtToDate datetime=null,
	@tFromTime time(7)=null,
	@tToTime time(7)=null,
	@bigAssignedBy bigint=null,
	@dtAssiedDate datetime=null,
	@intHoursToBeAdded INT = 0,
	@intMinsToBeAdded INT = 0,
	@bigFromLandmarkId bigint =null,
	@bigToLandmarkId bigint=null,
	@bitIsSecondDriver bit=null
	
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_SaveDriverAssignment] 3,1,'2010-06-24','2010-06-24','02:00:00','16:00:00',44,'2010-06-24',5,30
--	Description	:	To insert the driver schedule details.
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	11-Jun-2010	VN	Created Intial Version 
/******************************************************************************/

BEGIN
	DECLARE @VcDayName VARCHAR(15)=NULL	
	DECLARE @fTime time(7)=@tFromTime
	DECLARE @tTime time(7)=@tToTime
	DECLARE @dtFromtime DATETIME=NULL
	DECLARE @dtTotime DATETIME=NULL
	DECLARE @bigTripId bigint=null
	DECLARE @intBoxid int=null
	
		
	WHILE @dtFromDate <=@dtToDate 						
		BEGIN		
			SET @tFromTime=@fTime 
			SET @tToTime=@tTime 
			SET @dtFromtime =CONVERT(DATETIME,CONVERT(DATE,@dtFromDate))+@tFromTime 
			SET @dtFromtime=DATEADD(HOUR,(@intHoursToBeAdded*-1),DATEADD(MINUTE,(@intMinsToBeAdded*-1),@dtFromtime))	
			SET @tFromTime=CONVERT(TIME,@dtFromtime)			
			SET @dtTotime =CONVERT(DATETIME,CONVERT(DATE,@dtFromDate))+@tToTime  
			SET @dtTotime=DATEADD(HOUR,(@intHoursToBeAdded*-1),DATEADD(MINUTE,(@intMinsToBeAdded*-1),@dtTotime))	
			SET @tToTime=CONVERT(TIME,@dtTotime)									
			SELECT @intBoxid=BoxId  FROM rvlfVehicleAssignment WHERE VehicleId=@bigVehicleId 
			
			IF (@bitIsSecondDriver =1)
				BEGIN
					SELECT @bigTripId=AssignmentId FROM rvlfDriverAssignment 
						WHERE AssignmentDate=@dtFromDate AND FromTime=@dtFromtime AND ToTime=@dtTotime AND BOXID=@intBoxid  AND AssignedBy=@bigAssignedBy --AND FromLandmarkId=@bigFromLandmarkId AND ToLandmarkId=@bigToLandmarkId  
				END
				
				
			IF EXISTS(SELECT AssignmentID FROM rvlfDriverAssignment WHERE AssignmentDate=@dtFromDate 
				AND((@fTime >=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CONVERT(TIME,FromTime))))  
				AND @fTime<=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CONVERT(TIME,ToTime))))) 
				OR (@tTime >=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CONVERT(TIME,FromTime))))  
				AND @fTime <=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CONVERT(TIME,ToTime)))))))
				BEGIN
				
					DELETE rvlfDriverAssignment 
						WHERE DriverId=@bigDriverId AND AssignmentDate=@dtFromDate 
							AND((@fTime >=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CONVERT(TIME,FromTime))))  
							AND @fTime<=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CONVERT(TIME,ToTime))))) 
							OR (@tTime >=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CONVERT(TIME,FromTime))))  
							AND @fTime <=CONVERT(TIME,DATEADD(HOUR,+@intHoursToBeAdded,DATEADD(MINUTE,+@intMinsToBeAdded,CONVERT(TIME,ToTime))))))
					INSERT INTO rvlfDriverAssignment(DriverId,AssignmentDate,FromTime,ToTime,AssignedBy,AssignedDate,FromLandmarkId,ToLandmarkId,tripId,isamtIssued,BOXID)
						VALUES(@bigDriverId,@dtFromDate,@dtFromtime,@dtTotime,@bigAssignedBy,@dtAssiedDate,@bigFromLandmarkId,@bigToLandmarkId,@bigTripId,0,@intBoxid)		
													
				END
			ELSE
				BEGIN
					INSERT INTO rvlfDriverAssignment(DriverId,BOXID,AssignmentDate,FromTime,ToTime,AssignedBy,AssignedDate,FromLandmarkId,ToLandmarkId,tripId,isamtissued)
						VALUES(@bigDriverId,@intBoxid ,@dtFromDate,@dtFromtime,@dtTotime,@bigAssignedBy,@dtAssiedDate,@bigFromLandmarkId,@bigToLandmarkId,@bigTripId,0)																										
				END		
			IF(@bigTripId IS NOT NULL)
				BEGIN
					UPDATE rvlfDriverAssignment SET TRIPID=@bigTripId WHERE AssignmentId=@bigTripId 
				END
			SET @dtFromDate =DATEADD(D,1,@dtFromDate)							
		END
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveDriverRating]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveDriverRating]	
	@bigOrganizationID bigint = null,
	@bigRatingId bigint=null,
	@tintMsgInTypeId tinyint=null,
	@tintRating tinyint=null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_SaveDriverRating]
--	Description	:	To update the driver rating details
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	17-Jun-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN
	
	UPDATE rvlfViolationRating SET Rating=@tintRating 
		WHERE RATINGID=@bigRatingId AND BoxMsgInTypeID=@tintMsgInTypeId 	

END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveEnergyConsumption]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveEnergyConsumption] 
(
 @EquipmentID VARCHAR(50) = NULL,
 @tblShift XML = NULL,
 @OrganizationId BIGINT = NULL,
 @UserId BIGINT = NULL
)
AS
BEGIN
  DECLARE @docHandle int 
  DECLARE @noofShif INT
  DECLARE @shiftType int
  DECLARE @TempShift TABLE ([Shift] VARCHAR(10),ShiftType varchar(10),NoofShift VARCHAR(10),StratTime VARCHAR(10),EndTime VARCHAR(10))
 IF @tblShift IS NOT NULL                               
BEGIN                                              
	EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblShift                                                       
	INSERT INTO @TempShift                                                                    
	SELECT [Shift],ShiftType,NoofShift,FORMAT(CAST(StratTime AS DATETIME),'hh:mm tt') AS StratTime,FORMAT(CAST(EndTime AS DATETIME),'hh:mm tt') AS EndTime FROM OPENXML(@docHandle, '/DocumentElement/Shift')                             
	WITH                               
	( 
	[Shift] VARCHAR(10) 'Shift'                                        
	,ShiftType  varchar(10)  'ECType'                                                                  
	,NoofShift varchar(10)  'NoofShift'           
	,StratTime Varchar(10) 'StartTime'
	,EndTime Varchar(10) 'EndTime'                   
	)                                    
END                    
    SELECT TOP 1 @noofShif=NoofShift,@shiftType=ShiftType FROM @TempShift   

	UPDATE rvlfMAKDevices SET	
	EConsumptionType=@shiftType,
	NoofShifts=@noofShif,  
	ModifiedBy=@UserID,                                    
	ModifiedDate=GETUTCDATE() WHERE BoxId=@EquipmentID and OrganizationId=@OrganizationId

	DELETE FROM  rvlf_EnergyConsumption WHERE EquipmentId=@EquipmentID

    INSERT INTO rvlf_EnergyConsumption(EquipmentId,EConsumptionType,NoofShift,StartTime,EndTime,[Shift])
	SELECT @EquipmentID,ShiftType,NoofShift,StratTime,EndTime,[Shift] FROM @TempShift	

END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveFeedbackReply]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.e
-- Create date: 15-05-2015
-- Description:	Save Reply for User Feedbacks.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_SaveFeedbackReply]
	-- Add the parameters for the stored procedure here
	@bigUserFeedbackId		int = null,
	@vcReplyText			varchar(350) = null	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	UPDATE	rvlfUserFeedback SET ReplyText = @vcReplyText, ReplyDate = GETUTCDATE(), Status = 1
	WHERE	UserFeedbackId = @bigUserFeedbackId
	
	DECLARE @DevRegId Nvarchar(500) = NULL
	SET		@DevRegId = (SELECT DevRegID FROM rvlfUser WHERE UserId = 
						(SELECT UserId FROM rvlfUserFeedback WHERE UserFeedbackId = @bigUserFeedbackId))
	SELECT @DevRegId
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveFirmware]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[rvlf_sp_SaveFirmware]
	@bigFwId bigint = null,
	@bigBoxHwTypeId bigint,
	@bigFwTypeId bigint,
	@vcFwName varchar(75),
	@vcFwLocalPath varchar(150)  = null,
	@vcFwOAPPath varchar(150) = null,
	@intMaxGeozones int ,
	@intFirmwareCategoryId int,
	@intOAPPort int,
	@bigChid bigint = null,
	@tiChPrity tinyint = null
	--@bigBoxId bigint=null
as
/******************************************************************************/
--	Name		:	rvlf_sp_SaveFirmware
--	Description	:	To save the firmware versions
--	Author		:	V.Muthukumaravadivel.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	24-May-2011	VMKV Created Intial Version 
--				:	15-Feb-2012	Sakthi Set MaxGeozone is 50 by default
/******************************************************************************/
begin
  IF @bigFwId is null OR @bigFwId =''
  BEGIN
  IF NOT EXISTS(SELECT FwName FROM rvlfFirmware WHERE  FwName =@vcFwName)
	BEGIN
	INSERT INTO rvlfFirmware VALUES(@bigBoxHwTypeId,@bigFwTypeId,@vcFwName,@vcFwLocalPath,@vcFwOAPPath,GETUTCDATE(),50,@intOAPPort,@intFirmwareCategoryId,GETUTCDATE())
	SET @bigFwId=@@IDENTITY
	INSERT INTO rvlfFirmwareChannels VALUES(@bigChid,@bigFwId,@tiChPrity)
	--UPDATE rvlfBoxSettings SET FwID=@bigFwId WHERE BoxId=@bigBoxId
	END
	ELSE
		BEGIN
			UPDATE rvlfFirmware SET FwDateReleased =GETUTCDATE(),FwCategoryID=@intFirmwareCategoryId WHERE FwName =@vcFwName
		END
	
  END
  ELSE
	BEGIN
		UPDATE rvlfFirmware SET BoxHwTypeId = @bigBoxHwTypeId, FwTypeId = @bigFwTypeId,
			 FwLocalPath =ISNULL( @vcFwLocalPath,FwLocalPath ), FwOAPPath = ISNULL(@vcFwOAPPath, FwOAPPath),
			 FwDateReleased = GETUTCDATE(), MaxGeozones= 50, OAPPort = @intOAPPort
			WHERE FwId = @bigFwId
	END
end





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveFleetName]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveFleetName]
/******************************************************
Stored Procedure Name : rvlf_sp_SaveFleetName
Purpose     : Insert/Update fleet name
Created by    : N.Uma Maheswari
Created date   : 09-Jul-09
Updated by    :  Kumuthini.L 22-July-09 - Included Email Severity, Emails & SMS while Saving
			  :	 MJJC 03-Aug-2009 - Included the time zone settings.
*******************************************************/  

@FleetID   bigint,
@FleetName   varchar(100),
@Description  varchar(500),
@Notify bit = 0,
@Warning bit = 0,
@Critical bit = 0,
@Emails varchar(2010) = null,
@SMS varchar(160) = null,
@OrgnID    int,
@CreatedBy   int,
@Date DateTime,
@intTimeZomeID int

AS

BEGIN

if (@FleetID > 0)
 BEGIN
   UPDATE rvlfFleet SET
    OrganizationId=@OrgnID,
    Description=@Description,
    Notify=@Notify,
    Warning=@Warning,
    Critical=@Critical,
    Email=@Emails,
    SMS=@SMS,
    ModifiedBy=@CreatedBy,
    ModifiedDate=@Date,
    TimeZone = @intTimeZomeID
   WHERE FleetID=@FleetID          
 END
ELSE
 BEGIN
   INSERT INTO rvlfFleet(FleetName,OrganizationId,Description,Notify,Warning,Critical,Email,SMS,
		CreatedBy,CreatedDate, TimeZone)
   VALUES(@FleetName,@OrgnID,@Description,@Notify,@Warning,@Critical,@Emails,@SMS,
		@CreatedBy,@Date, @intTimeZomeID)
 END
END
-- exec rvlf_sp_SaveFleetName 0,'aaaaa', 'sfsfsfd',1,1


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveFuelEntry]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveFuelEntry]              
               
@bigFuelEntryId bigint = NULL,              
@bigVehicleId bigint = NULL,              
@dtFromDate Datetime = NULL,              
--@dtToDate Datetime = NULL,              
@bigFuel decimal(18,2) = NULL,              
@bigFuelCost decimal(18,2) = NULL,             
@vcFuelStation Varchar(250) = NULL,        
@vcComments Varchar(250) = NULL,              
@CreatedBy bigint = NULL              
              
AS              
/******************************************************************************/              
-- Name  : rvlf_sp_SaveFuelEntry 33,'2011-03-01','2011-03-04',22,27,'gg'              
-- Description : To save the Fuel Entry              
-- Author  : MuthuKumaraVadivel. V              
-- Company  : Angler Technologies              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
--    : 13-May-2011 VM Created Intial Version              
--    :   21-May-2011 LK  Included the update query             
--    :   2-Jun-2012 Vijay  removed the Exist condition in Update query.          
/******************************************************************************/              
BEGIN              
SET NOCOUNT ON               
              
 DECLARE @ErrorMessage VARCHAR(3000)              
 BEGIN TRY              
                
  DECLARE @ConversionFactor decimal(18,3) = 1.0     
  DECLARE @MinsToBeAdded INT = 0              
  DECLARE @HoursToBeAdded INT = 0              
                  
  SELECT @ConversionFactor = CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 END,
  @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded           
  FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz              
  ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @CreatedBy     
  

                
  IF (@bigFuelEntryId IS NULL OR @bigFuelEntryId = 0 OR @bigFuelEntryId = '')              
  BEGIN                     
                  
    INSERT INTO rvlfFuelEntry(VehicleID, FuelfilledDateTime, FuelFilled,FuelCost,fuelstation,Comments, CreatedBy, CreatedDateTime)              
    VALUES (@bigVehicleId, DATEADD(MINUTE,@MinsToBeAdded * -1,DATEADD(HOUR,@HoursToBeAdded * -1,@dtFromDate)),
     @bigFuel * @ConversionFactor, @bigFuelCost/@ConversionFactor,@vcFuelStation,@vcComments, @CreatedBy, GETUTCDATE())                    
                
  END              
  ELSE              
  BEGIN              
                
   --IF EXISTS (SELECT VehicleId FROM rvlfFuelEntry WHERE VehicleId = @bigVehicleId AND FuelEntryID       
   --<> @bigFuelEntryId AND ((FromDate BETWEEN @dtFromDate AND @dtToDate) OR (ToDate BETWEEN @dtFromDate       
   --AND @dtToDate) OR (@dtFromDate BETWEEN FromDate AND ToDate) OR (@dtToDate BETWEEN FromDate AND ToDate)))              
   --BEGIN                  
   -- RAISERROR('Fuel Entry for the selected vehicle exists on the specified duration.', 16, 1)         
   --END      
   --ELSE      
   --BEGIN      
                
    UPDATE rvlfFuelEntry SET FuelfilledDateTime = DATEADD(MINUTE,@MinsToBeAdded * -1,DATEADD(HOUR,@HoursToBeAdded * -1,@dtFromDate)),
     FuelFilled = (@bigFuel * @ConversionFactor),              
     FuelCost = @bigFuelCost/@ConversionFactor,Fuelstation = @vcFuelStation ,Comments = @vcComments, ModifiedBy = @CreatedBy, ModifiedDateTime = GETUTCDATE(),    
     VehicleId = @bigVehicleId              
    WHERE FuelEntryID = @bigFuelEntryId              
                 
   END              
                
  --END              
                
 END TRY              
 BEGIN CATCH              
               
  SET @ErrorMessage = ERROR_MESSAGE()              
  RAISERROR(@ErrorMessage, 16, 1)              
                
 END CATCH              
               
SET NOCOUNT OFF              
              
END              
              
              
              

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveGarminRoute]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveGarminRoute]            
@vehicleId bigint,            
@RouteId int=null,            
@userId int,            
@RouteStatus varchar(40)=null,            
@LandmarkId int,  
@operation int      
AS            
/******************************************************************************/                
-- Name   : [rvlf_sp_SaveGarminRoute] 0            
-- Description : To Save or delete Garmin Route      
-- Author  : Gopal .R                
-- Created Date : 23-dec-2013            
-- Company  : Angler Technologies             
/******************************************************************************/              
BEGIN            
 SET NOCOUNT ON            
  IF @operation = 1 -- INSERT            
  BEGIN            
    INSERT INTO rvlfGarminRoute (VehicleId,RouteId,UserId,CreatedDate,RouteStatus,LanmarkId)            
    VALUES(@vehicleId,@RouteId,@userId,GETUTCDATE(),'Unread Inactive',@LandmarkId)            
  END             
        
  ELSE IF @operation = 2 --DELETE  --changed 2 instead of 3 22-Nov-2013          
  BEGIN            
    DELETE rvlfGarminRoute WHERE VehicleId=@vehicleId AND RouteId=@RouteId      
  END            
  ELSE IF @operation = 3 --DELETE All            
  BEGIN               
    DELETE rvlfGarminRoute WHERE VehicleId=@vehicleId --AND StopId=@wayOrStopId            
  END            
 SET NOCOUNT OFF            
END  
  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveGarminWayOrStopPoint]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveGarminWayOrStopPoint]      
@vehicleId bigint,      
@wayOrStopId int,      
@landmarkId int=null,      
@userId int,      
@StopStatus int,      
@operation int,      
@isStopPoint bit,      
@streetAddress varchar(250) = null,      
@latitude decimal(10,6) = null,      
@longitude decimal(10,6) = null,  
@isRoute bit=null      
AS      
/******************************************************************************/          
-- Name   : [rvlf_sp_SaveGarminWayOrStopPoint] 0      
-- Description : To get Nextid or waypoint or stop id      
-- Author  : Sakthi Gopinath S          
-- Created Date : 10-Jan-2012      
-- Company  : Angler Technologies       
-- update for Delete All option by gopal 22-Nov-2013           
/******************************************************************************/        
BEGIN      
 SET NOCOUNT ON      
  IF @operation = 1 -- INSERT      
  BEGIN      
   IF @isStopPoint = 0      
   BEGIN      
    INSERT INTO rvlfGarminWaypoint(VehicleId,WayPointId,LandmarkId,UserId,CreatedDate,StreetAddress,Latitude,Longitude)      
    VALUES(@vehicleId,@wayOrStopId,@landmarkId,@userId,GETUTCDATE(),@streetAddress,@latitude,@longitude)      
   END      
   ELSE      
   BEGIN      
    INSERT INTO rvlfGarminStop(VehicleId,StopId,LandmarkId,UserId,CreatedDate,StopStatus,StreetAddress,Latitude,Longitude,isRoute)      
    VALUES(@vehicleId,@wayOrStopId,@landmarkId,@userId,GETUTCDATE(),'Unread Inactive',@streetAddress,@latitude,@longitude,@isRoute)      
   END      
  END       
  --ELSE IF @operation = 4 --UPDATE  --changed 4 instead of 2 22-Nov-2013    
  --BEGIN      
  -- IF @isStopPoint = 1      
  -- BEGIN      
  --  UPDATE rvlfGarminStop SET StopStatus=@StopStatus WHERE VehicleId=@vehicleId AND StopId=@wayOrStopId      
  -- END      
  --END      
  ELSE IF @operation = 2 --DELETE  --changed 2 instead of 3 22-Nov-2013    
  BEGIN      
   IF @isStopPoint = 0      
   BEGIN      
    DELETE rvlfGarminWaypoint WHERE VehicleId=@vehicleId AND WayPointId=@wayOrStopId      
   END      
   ELSE      
   BEGIN      
    DELETE rvlfGarminStop WHERE VehicleId=@vehicleId AND StopId=@wayOrStopId      
   END      
  END      
  ELSE IF @operation = 3 --DELETE All      
  BEGIN         
    DELETE rvlfGarminStop WHERE VehicleId=@vehicleId --AND StopId=@wayOrStopId      
  END      
 SET NOCOUNT OFF      
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveGeozoneRestricted]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveGeozoneRestricted]
@bigBoxId bigint,
@geozoneId int,
@isRestricted bit,
@isAssign bit
AS
/*********************************************************************************
Procedure Name	: rvlf_sp_SaveGeozoneRestricted 999888,135,0,1
Description		: Store the value of geozone is restricted or not
Created By		: Sakthi Gopinath S
Created Date	: 09-Mar-2015
*********************************************************************************/
BEGIN
SET NOCOUNT ON
	DECLARE @bigOrgId INT
	DECLARE @bigVehicleId INT
	DECLARE @geozoneNo INT
	SELECT @bigOrgId=v.OrganizationId,@bigVehicleId=v.VehicleId FROM rvlfVehicle v 
	INNER JOIN rvlfVehicleAssignment va ON v.VehicleId=va.VehicleId WHERE va.BoxId=@bigBoxId
	
	SELECT @geozoneNo=@geozoneId --GeozoneNo FROM rvlfOrganizationGeozone WHERE OrganizationId=@bigOrgId AND GeozoneId=@geozoneId

	IF @isAssign = 1
	BEGIN
		IF EXISTS(SELECT 1 FROM rvlfGeozoneRestricted gr INNER JOIN rvlfOrganizationGeozone og ON og.GeozoneNo=gr.GeozoneNo
		WHERE gr.VehicleID=@bigVehicleId and og.GeozoneNo=@geozoneNo)
		BEGIN
			DELETE rvlfGeozoneRestricted WHERE VehicleID=@bigVehicleId and GeozoneNo=@geozoneNo 
			INSERT INTO rvlfGeozoneRestricted(VehicleId,GeozoneNo,IsRestricted) VALUES (@bigVehicleID,@geozoneNo,@isRestricted)
		END
		ELSE
		BEGIN
			INSERT INTO rvlfGeozoneRestricted(VehicleId,GeozoneNo,IsRestricted) VALUES (@bigVehicleID,@geozoneNo,@isRestricted)
		END
	END
	ELSE
	BEGIN
		DELETE rvlfGeozoneRestricted WHERE VehicleID=@bigVehicleId and GeozoneNo=@geozoneNo 
	END
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveGeozoneSalikfare]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_SaveGeozoneSalikfare]      
(      
@SalikFare xml      
)      
as      
-- =============================================                      
-- Name   : rvlf_sp_SaveGeozoneSalikfare                      
-- Author  : Gopal.R                      
-- Create date : 18-Jan-2014                      
-- Description : Insert Salik Fare Details                      
-- Company  : Angler Technologies                      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                      
-- =============================================       
begin      
--insert into rvlfgeozonesalikfare      
--SELECT x.d.value('GeozoneID[1]','bigint') AS GeozoneID,x.d.value('VehicleTypeId[1]','int') AS VehicleTypeId,      
--x.d.value('Fare[1]','decimal(8,2)') AS Fare,x.d.value('DateFrom[1]','datetime') AS DateFrom,null,1      
--FROM @SalikFare.nodes('/DocumentElement/SalikFareDetails') x(d)     
    
declare @cnt int=0    
declare @GeozoneID bigint    
declare @vehicleTypeId int    
declare @validFrom datetime    
declare @Fare decimal(8,2)    
declare @Index int=0    
declare @date datetime  
SELECT @cnt=COUNT( x.d.value('GeozoneID[1]','bigint')) FROM @SalikFare.nodes('/DocumentElement/SalikFareDetails') x(d)    
    
WHILE @cnt>0    
BEGIN    
    
 SELECT top 1 @Index= x.d.value('Index[1]','int'),@GeozoneID= x.d.value('GeozoneID[1]','bigint'),@vehicleTypeId=x.d.value('VehicleTypeId[1]','int'), @Fare=x.d.value('Fare[1]','decimal(8,2)'),    
 @validFrom=x.d.value('DateFrom[1]','datetime')      
 FROM @SalikFare.nodes('/DocumentElement/SalikFareDetails') x(d)    
    
 IF exists(select * from rvlfGeozoneSalikFare where GeozoneID=@GeozoneID and ValidFrom=@validFrom and VehicleTypeId=@vehicleTypeId)    
 BEGIN    
  Update rvlfGeozoneSalikFare set TollFare=@Fare where GeozoneID=@GeozoneID and ValidFrom=@validFrom and VehicleTypeId=@vehicleTypeId    
  set @SalikFare.modify('delete //SalikFareDetails[Index=sql:variable("@Index")]')    
 END    
 ELSE    
 BEGIN    
  INSERT INTO rvlfgeozonesalikfare      
  SELECT  x.d.value('GeozoneID[1]','bigint')AS GeozoneID,x.d.value('VehicleTypeId[1]','int') AS VehicleTypeId,      
  x.d.value('Fare[1]','decimal(8,2)') AS Fare,x.d.value('DateFrom[1]','datetime') AS DateFrom ,null,1     
  FROM @SalikFare.nodes('/DocumentElement/SalikFareDetails') x(d) where x.d.value('Index[1]','int')=@Index    
  --Delete inserted row    
  set @SalikFare.modify('delete //SalikFareDetails[Index=sql:variable("@Index")]')    
      
 END    
 set @cnt=@cnt-1    
END     
      
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveGridAdvancedFilterSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasu.E
-- Create date: 13-09-2016
-- Description:	Saves the GridView Advanced filter settings for the current user.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_SaveGridAdvancedFilterSettings] 
	-- Add the parameters for the stored procedure here
	@bigUserId		bigint = NULL, 
	@bigModuleId	bigint = NULL,
	@nvFilterExpr	nvarchar(max) = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here

	IF EXISTS(SELECT * FROM rvlfGridAdvancedFilters WHERE UserID = @bigUserId AND ModuleId = @bigModuleId)
	BEGIN
		UPDATE rvlfGridAdvancedFilters SET FilterExpression = @nvFilterExpr 
		WHERE UserID = @bigUserId AND ModuleId = @bigModuleId 
	END
	ELSE
	BEGIN
		INSERT INTO rvlfGridAdvancedFilters (UserID, ModuleId, FilterExpression)
		VALUES(@bigUserId, @bigModuleId, @nvFilterExpr)
	END
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveIncentiveSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE Procedure [dbo].[rvlf_sp_SaveIncentiveSettings]
	@bigIncentiveId bigint=null,
	@vcVehicleType varchar(5)=null,
	@tiNoOfDrivers tinyint=null,
	@vcIncentiveName varchar(50)=null,
	@nuRatePerKM numeric(5,2)=null,
	@nuOtherAmt numeric(7,2)=null,
	@bigOrgId bigint=null,
	@intFromRange int=null,
	@intToRange int=null,
	@bitActive bit=null,
	@tFromTime time(7)=null,
	@tToTime time(7)=null,
	@bitIgnition bit=null,
	@sintViolationPoints int=null,
	@tintPercentage int=null,
	@bitIsAllowance bit=null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_SaveIncentiveSettings]
--	Description	:	To save the driver incentive setting details
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	13-Sep-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN
		
	IF(@bigIncentiveId >0)
		BEGIN			
			UPDATE rvlfDriverBattaDetails SET VehicleType=@vcVehicleType,NoOfDrivers=@tiNoOfDrivers,
				Description= @vcIncentiveName,RatePerKM=@nuRatePerKM,OtherAmt=@nuOtherAmt,
				OrganizationId=@bigOrgId,FromRange=@intFromRange,ToRange=@intToRange,ACTIVE=@bitActive,
				FromTime=@tFromTime,ToTime=@tToTime,IgnitionStatus=@bitIgnition,ViolationPoints=@sintViolationPoints,
				PercentageOfAmt=@tintPercentage,IsAllowance=@bitIsAllowance  
			WHERE BattaId=@bigIncentiveId  		
		END
	ELSE
		BEGIN
		    IF((@bitIsAllowance IS NOT NULL OR @bitIsAllowance='') AND (@sintViolationPoints IS NOT NULL OR @sintViolationPoints=''))
				BEGIN
					DELETE FROM rvlfDriverBattaDetails WHERE OrganizationId=@bigOrgId AND VehicleType=@vcVehicleType AND IsAllowance=@bitIsAllowance
				END
			INSERT INTO rvlfDriverBattaDetails(VehicleType,NoOfDrivers,Description,RatePerKM,OtherAmt,
					OrganizationId,FromRange,ToRange,ACTIVE,FromTime,ToTime,IgnitionStatus,ViolationPoints,PercentageOfAmt,
					IsAllowance)
				VALUES(@vcVehicleType,@tiNoOfDrivers,@vcIncentiveName,@nuRatePerKM,@nuOtherAmt,
					@bigOrgId,@intFromRange,@intToRange,@bitActive,@tFromTime,@tToTime,@bitIgnition,@sintViolationPoints,
					@tintPercentage,@bitIsAllowance)
		END
		
    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveMaintenancePlan]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE PROCEDURE [dbo].[rvlf_sp_SaveMaintenancePlan]  
/*****************************************************************                 
Stored Procedure Name : rvlf_sp_SaveMaintenancePlan  
Purpose               : Insert / Update / Delete Maintenance Plan  
Created By            : Kumuthini. L  
Created Date          : 10-Jun-10  
Updated History       : <<Date>> <<Author>> <<Reason>>  
            Initial Creation - Kumuthini - To insert or update or delete the maintenance plan  
            25-Jun-2010 - Kumuthini - Included the User Preferences for Odometer Reading Service Interval  
******************************************************************/  
  
@chrType char(1),  
@bigPlanId bigint = Null,  
@vcPlanName varchar(100) = Null,  
@bigOrganizationId bigint = Null,  
@vcDescription varchar(250) = Null,  
@bitIsRecurring bit = Null,  
@tiOverdueReminder tinyint = Null,  
@bigTotalPlannedCost numeric(18,2) = Null,  
@CreatedBy  bigint = Null,  
@CreatedDateTime DateTime = Null,  
@ModifiedBy bigint = Null,  
@ModifiedDateTime DateTime = Null,  
@tblPlanDetails  XML =NULL,      
@tblServiceDetails XML =NULL, 
--@tblPlanDetails AS MaintenancePlanDetails READONLY,  
--@tblServiceDetails AS MaintenancePlanServices READONLY,  
--@tblNotificationsList AS NotificaitonUserList READONLY  
 @tblNotificationsList XML = null,
 @BigVAT numeric(18,2) = null       
  
AS  
  
BEGIN  
  
 /****************************Reading XML File and Store into Temp table**************/     
    DECLARE @docHandle int             
	DECLARE @docHandle1 int       
	DECLARE @docHandle2 int        
	DECLARE  @temptable TABLE (UserID Bigint,Email bit,SMS bit)
	DECLARE  @ServiceTable TABLE(ServiceId Bigint,PlannedCost numeric(18,2))      
	DECLARE  @PlanDetails TABLE (bigPlanId bigint,ServiceType bigint,ServiceInterval bigint,Frequency int,Notification1 int,Notification2 int,Notification3 int)         
    IF @tblNotificationsList IS NOT NULL     
  BEGIN                    
   EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblNotificationsList                             
  INSERT INTO @tempTable                                          
   SELECT * FROM OPENXML(@docHandle, '/DocumentElement/Notification')   
   WITH     
   (             
  UserID bigint 'UserID'              
  ,Email  bit  'Email'                                        
  ,SMS bit  'SMS'    
   )          
 END    
 declare @tblNotificationsListTmp As NotificaitonUserList   
 insert into  @tblNotificationsListTmp  
 select * from @temptable   
 
 IF @tblPlanDetails IS NOT NULL      
 BEGIN      
  EXEC sp_xml_preparedocument @docHandle1 OUTPUT, @tblPlanDetails      
  INSERT INTO @PlanDetails      
  SELECT * FROM OPENXML(@docHandle1,'/DocumentElement/PlanDetails')      
  WITH      
  (      
   bigPlanId bigint 'bigPlanId'      
   ,ServiceType bigint  'ServiceType'      
  ,ServiceInterval bigint  'ServiceInterval'      
  ,Frequency int  'Frequency'      
  ,Notification1 int  'Notification1'      
  ,Notification2 int  'Notification2'      
  ,Notification3 int  'Notification3'      
  )       
  declare @tblPlanDetails1 As MaintenancePlanDetails        
  insert into  @tblPlanDetails1        
  select * from @PlanDetails       
 END      
       
 IF @tblServiceDetails IS NOT NULL      
  BEGIN      
  EXEC sp_xml_preparedocument @docHandle2 OUTPUT, @tblServiceDetails      
  INSERT INTO @ServiceTable      
  SELECT * FROM OPENXML(@docHandle2,'/DocumentElement/ServiceDetails')      
  WITH      
  (      
  ServiceId Bigint 'ServiceId',      
  PlannedCost numeric(18,2) 'PlannedCost'      
  )      
  declare @tblSericeDetails1 As MaintenancePlanServices        
  insert into  @tblSericeDetails1        
  select * from @ServiceTable       
 END        
 /**************************************************************************************/  
IF (@chrType = 'D') -- If operation is Delete  
BEGIN  
  
    -- Delete the maintenance plan details using Plan Id  
 DELETE FROM rvlfMaintenancePlanDetails WHERE PlanId = @bigPlanId  
      
    -- Delete the maintenance plan using Plan Id  
 DELETE FROM rvlfMaintenancePlan WHERE PlanId = @bigPlanId  
  
    -- Delete the maintenance plan services using Plan Id  
    DELETE FROM rvlfMaintenancePlanServices WHERE PlanId = @bigPlanId  
      
    -- Delete the details in the Notification Table using Plan Id   
    DELETE FROM rvlfNotificationList WHERE NotificationType = 8 AND TypeID = @bigPlanId  
  
END  
ELSE  
BEGIN  
   
 DECLARE @ConversionFactor numeric (10,2) = 1.0  
      
    SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END  
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz  
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @CreatedBy  
          
 IF (@bigPlanId > 0 )  
  BEGIN  
      
  -- Update the maintenance plan using Plan Id  
  UPDATE rvlfMaintenancePlan   
  SET PlanName = @vcPlanName, PlanDescription = @vcDescription, RecurringService = @bitIsRecurring,  
  OverdueReminder = @tiOverdueReminder, TotalPlannedCost = @bigTotalPlannedCost,  
  ModifiedBy = @ModifiedBy, ModifiedDateTime = @ModifiedDateTime ,VAT=@BigVAT    
  WHERE PlanId = @bigPlanId  
       
     -- Delete the details in the Maintenance Plan Details using Plan Id  
     DELETE FROM rvlfMaintenancePlanDetails  
     WHERE PlanId = @bigPlanId AND PlanDetailsId NOT IN (SELECT PlanDetailsId FROM @tblPlanDetails1 WHERE PlanDetailsId IS NOT NULL)  
      
     INSERT INTO rvlfMaintenancePlanDetails (PlanId, ServiceType, ServiceInterval, Frequency, Notification1, Notification2, Notification3)  
   SELECT @bigPlanId, pd.ServiceType,   
   CASE WHEN pd.ServiceType = 1 THEN (CASE WHEN (pd.ServiceInterval / @ConversionFactor) > 0 THEN ROUND((pd.ServiceInterval / @ConversionFactor), 0)  
           ELSE (pd.ServiceInterval / @ConversionFactor) END) ELSE pd.ServiceInterval END AS ServiceInterval,   
   pd.Frequency, pd.Notification1, pd.Notification2, pd.Notification3   
   FROM @tblPlanDetails1 AS pd WHERE pd.PlanDetailsId IS NULL  
     
  -- Delete the details in the Maintenance Plan Services using Plan Id  
  DELETE FROM rvlfMaintenancePlanServices WHERE PlanId = @bigPlanId  
    
  INSERT INTO rvlfMaintenancePlanServices (PlanId, ServiceId, PlannedCost)   
   SELECT @bigPlanId, ServiceId, PlannedCost FROM @tblSericeDetails1 
    
  -- Delete the details in the Notification Table using Plan Id   
  DELETE FROM rvlfNotificationList WHERE NotificationType = 8 AND TypeID = @bigPlanId  
      
  EXEC rvlf_sp_Save_notificationsList @tblNotificationsListTmp, 8 , @bigPlanId  
       
  END  
 ELSE  
  BEGIN  
    
    -- Insert the maintenance plan details  
    INSERT INTO rvlfMaintenancePlan(PlanName,OrganizationId,PlanDescription,RecurringService,OverdueReminder,TotalPlannedCost,  
    CreatedBy, CreatedDateTime,VAT)  
    VALUES(@vcPlanName,@bigOrganizationId,@vcDescription,@bitIsRecurring,@tiOverdueReminder,@bigTotalPlannedCost,  
    @CreatedBy, @CreatedDateTime,@BigVAT)  
     
    SET @bigPlanId = @@IDENTITY  
    
    INSERT INTO rvlfMaintenancePlanDetails (PlanId, ServiceType, ServiceInterval, Frequency, Notification1, Notification2, Notification3)  
      SELECT @bigPlanId, pd.ServiceType,   
      CASE WHEN pd.ServiceType = 1 THEN (CASE WHEN (pd.ServiceInterval / @ConversionFactor) > 0 THEN ROUND((pd.ServiceInterval / @ConversionFactor), 0)  
           ELSE (pd.ServiceInterval / @ConversionFactor) END) ELSE pd.ServiceInterval END AS ServiceInterval,    
      pd.Frequency, pd.Notification1, pd.Notification2, pd.Notification3 FROM @tblPlanDetails1 AS pd  
        
     INSERT INTO rvlfMaintenancePlanServices (PlanId, ServiceId, PlannedCost)   
   SELECT @bigPlanId, ServiceId, PlannedCost FROM @tblSericeDetails1	   
      
    EXEC rvlf_sp_Save_notificationsList @tblNotificationsListTmp, 8 , @bigPlanId  
            
  END 
 END  
END  
  
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateMaintenanceServiceDetails]    Script Date: 01/19/2011 12:30:53 ******/  
SET ANSI_NULLS ON 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveMaintenanceService]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveMaintenanceService]
/*************************************************************               
Stored Procedure Name : rvlf_sp_SaveMaintenanceService
Purpose               : Insert / Update Maintenance Services
Created By            : Kumuthini. L
Created Date          : 09-Jun-10
Updated History       : <<Date>> <<Author>> <<Reason>>
				        Initial Creation - Kumuthini - To insert or update the maintenance services
**************************************************************/

@chrType char(1),
@bigServiceId bigint = Null,
@vcServiceName varchar(100) = Null,
@bigOrganizationId bigint = Null,
@vcDescription varchar(250) = Null,
@CreatedBy  bigint = Null,
@CreatedDateTime DateTime = Null,
@ModifiedBy bigint = Null,
@ModifiedDateTime DateTime = Null,
--@tblNotificationsList AS NotificaitonUserList READONLY
 @tblNotificationsList XML = null 
AS

BEGIN
/****************************Reading XML File and Store into Temp table**************/   
   DECLARE @docHandle int     
   DECLARE  @temptable TABLE (UserID Bigint,Email bit,SMS bit)        
    IF @tblNotificationsList IS NOT NULL   
  BEGIN                  
   EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblNotificationsList                           
  INSERT INTO @tempTable                                        
   SELECT * FROM OPENXML(@docHandle, '/DocumentElement/Notification') 
   WITH   
   (           
		UserID bigint 'UserID'            
		,Email  bit  'Email'                                      
		,SMS bit  'SMS'  
   )        
	END  
	declare @tblNotificationsListTmp As NotificaitonUserList 
	insert into  @tblNotificationsListTmp
	select * from @temptable   
 /**************************************************************************************/
IF (@chrType = 'D') -- If operation is Delete
BEGIN

    -- Delete the maintenance service using Service Id
	DELETE FROM rvlfMaintenanceService WHERE ServiceId=@bigServiceId

	DELETE FROM rvlfNotificationList WHERE NotificationType = 7 AND TypeID = @bigServiceId

END
ELSE
BEGIN
	IF (@bigServiceId > 0 )
	 BEGIN
	   
		-- Update the maintenance service using Service Id
		UPDATE rvlfMaintenanceService 
		SET ServiceName=@vcServiceName,[Description]=@vcDescription,
		ModifiedBy=@ModifiedBy,ModifiedDateTime=@ModifiedDateTime 
		WHERE ServiceId=@bigServiceId
	    
	    DELETE FROM rvlfNotificationList WHERE NotificationType = 7 AND TypeID = @bigServiceId
				
		EXEC rvlf_sp_Save_notificationsList @tblNotificationsListTmp, 7 , @bigServiceId
	    
	 END
	ELSE
	 BEGIN
	 
	   -- Insert the maintenance service details
	   INSERT INTO rvlfMaintenanceService(ServiceName,OrganizationId,[Description],
			 CreatedBy, CreatedDateTime)
	   VALUES(@vcServiceName,@bigOrganizationId,@vcDescription,
			 @CreatedBy, @CreatedDateTime)
			
	   SET @bigServiceId = @@IDENTITY
		
	   EXEC rvlf_sp_Save_notificationsList @tblNotificationsListTmp, 7 , @bigServiceId
	         
	 END
 END
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveMaintenanceServiceCategory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveMaintenanceServiceCategory]
/************************************************************* ****************              
Stored Procedure Name : rvlf_sp_SaveMaintenanceServiceCategory
Purpose               : Insert / Update / Delete Maintenance Service Categories
Created By            : Kumuthini. L
Created Date          : 09-Jun-10
Updated History       : <<Date>> <<Author>> <<Reason>>
				        Initial Creation - Kumuthini - To insert or update or delete the maintenance service categories
******************************************************************************/

@chrType char(1),
@bigServiceCategoryId bigint = Null,
@vcServiceCategoryName varchar(100) = Null,
@bigOrganizationId bigint = Null,
@vcDescription varchar(250) = Null

AS

BEGIN

IF (@chrType = 'D') -- If operation is Delete
BEGIN

    -- Delete the maintenance service category using Service Category Id
	DELETE FROM rvlfMaintenanceServiceCategory WHERE ServiceCategoryId=@bigServiceCategoryId

END
ELSE
BEGIN
	IF (@bigServiceCategoryId > 0 )
	 BEGIN
	   
		-- Update the maintenance service category using Service category Id
		UPDATE rvlfMaintenanceServiceCategory 
		SET ServiceCategoryName=@vcServiceCategoryName, ServiceCatDescription=@vcDescription
		WHERE ServiceCategoryId=@bigServiceCategoryId
	    
	 END
	ELSE
	 BEGIN
	 
	   -- Insert the maintenance service category details
	   INSERT INTO rvlfMaintenanceServiceCategory(ServiceCategoryName,OrganizationId,ServiceCatDescription)
	   VALUES(@vcServiceCategoryName,@bigOrganizationId,@vcDescription)
	         
	 END
 END
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveManualEntry]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_SaveManualEntry]
	
@bigVehicleId bigint = NULL,
@dtFromDate Datetime = NULL,
@dtToDate Datetime = NULL,
@bigengineHours bigint = NULL,
@bigKilometersRun bigint = NULL,
@vcComments Varchar(250) = NULL,
@CreatedBy bigint = NULL

AS
/******************************************************************************/
--	Name		:	rvlf_sp_SaveManualEntry 33,'2011-03-01','2011-03-04',22,27,'gg'
--	Description	:	To save the Manual Entry
--	Author		:	MuthuKumaraVadivel. V
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	05-May-2011	VM	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 

	DECLARE @ErrorMessage VARCHAR(3000)
	BEGIN TRY
						
		IF EXISTS (SELECT VehicleId FROM rvlfManualEntry WHERE VehicleId = @bigVehicleId AND ((FromDate BETWEEN @dtFromDate AND @dtToDate) OR (ToDate BETWEEN @dtFromDate AND @dtToDate) OR (@dtFromDate BETWEEN FromDate AND ToDate) OR (@dtToDate BETWEEN FromDate AND ToDate)))
		BEGIN
		
			RAISERROR('Manual Entry for the selected vehicle exists on the specified duration.', 16, 1)
		
		END
		ELSE
		BEGIN
		
			DECLARE @ConversionFactor numeric (10,2) = 1.0
			
			SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END
			FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz
			ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @CreatedBy
			
			INSERT INTO rvlfManualEntry(VehicleId, FromDate, ToDate, EngineHours, Kilometers, Comments, CreatedBy, CreatedDateTime)
			VALUES (@bigVehicleId, @dtFromDate, @dtToDate, @bigengineHours, ROUND(@bigKilometersRun / @ConversionFactor,0), @vcComments, @CreatedBy, GETUTCDATE())
		
	    END
		
	END TRY
	BEGIN CATCH
	
		SET @ErrorMessage = ERROR_MESSAGE()
		RAISERROR(@ErrorMessage, 16, 1)
		
	END CATCH
	
SET NOCOUNT OFF
END





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveMDTMessageTable]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_SaveMDTMessageTable]
	@tiOprType tinyint,
	@bigVehId bigint,
	@tiMsgType tinyint,
	@vcPrecannedMsgId varchar(100)=null,
	@bigOrganizationId bigint=null

AS
/**********************************************************************************************************************/
--	Name		:	rvlf_sp_SaveMDTMessageTable
--	Description	:	To save precanned messages in the MDT Msg Table, Deleting particular Msg and deleting whole MDT Message Table
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	14-Dec-2009		Created Intial Version 
--				:	30-Aug-2011	VN Included the multiple msgs save and delete functionality.
/**********************************************************************************************************************/
BEGIN
SET NOCOUNT ON 
  
  DECLARE @intBoxId AS INT = (SELECT BoxId FROM rvlfVehicleAssignment WHERE VehicleId = @bigVehId) 
  
  IF @tiOprType = 0 -- Add / Update the MDT Message Table
	BEGIN
		INSERT INTO rvlfMDTBoxMessageTable (BoxId, CannedMsgId) 
		SELECT @intBoxId,CannedMsgId  FROM rvlfPrecannedMessages WHERE PrecannedMsgId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcPrecannedMsgId,',')) AND IsServerMsg = @tiMsgType	AND OrganizationId =@bigOrganizationId 
	END
  ELSE IF @tiOprType = 1 -- Delete particular message from MDT Message Table
	BEGIN  
		DELETE FROM rvlfMDTBoxMessageTable WHERE CannedMsgId IN(SELECT CannedMsgId FROM rvlfPrecannedMessages WHERE PrecannedMsgId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcPrecannedMsgId,',')) AND IsServerMsg = @tiMsgType AND OrganizationId =@bigOrganizationId ) AND BoxId = @intBoxId  
	END
  ELSE IF @tiOprType=2--Add / Update the MDT Users
	BEGIN
		IF EXISTS(SELECT UserId FROM rvlfMDTUserTable WHERE MDTUserId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcPrecannedMsgId,',')))
			BEGIN
				INSERT INTO rvlfMDTBoxMessageTable (BoxId,UserId) 
				SELECT @intBoxId,UserId FROM rvlfMDTUserTable WHERE MDTUserId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcPrecannedMsgId,',')) 	
			END
		ELSE
			BEGIN
				INSERT INTO rvlfMDTBoxMessageTable (BoxId,UserId) 
				SELECT @intBoxId,UserId FROM rvlfMDTUserTable WHERE UserId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcPrecannedMsgId,',')) 	
			END
	END
  ELSE IF @tiOprType=3 -- Delete particular user from MDT USER Table
	BEGIN
		IF EXISTS(SELECT UserId FROM rvlfMDTUserTable WHERE MDTUserId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcPrecannedMsgId,',')))
			DELETE FROM rvlfMDTBoxMessageTable WHERE UserId IN(SELECT UserId FROM rvlfMDTUserTable WHERE MDTUserId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcPrecannedMsgId,','))) AND BoxId = @intBoxId  
		ELSE
			DELETE FROM rvlfMDTBoxMessageTable WHERE UserId IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcPrecannedMsgId,',')) AND BoxId = @intBoxId  
	END
  ELSE IF @tiOprType=4-- DELETE ALL USERS BASED ON THE BOXID
	BEGIN  
		DELETE FROM rvlfMDTBoxMessageTable WHERE BoxId = @intBoxId AND CannedMsgId IS NULL AND USERID IS NOT NULL 
	END
  ELSE-- DELETE ALL MESSAGES BASED ON THE BOXID
	BEGIN  
		DELETE FROM rvlfMDTBoxMessageTable 
			WHERE BoxId = @intBoxId AND CannedMsgId IS NOT NULL AND USERID IS NULL   
				AND  CannedMsgId IN(SELECT CannedMsgId FROM rvlfPrecannedMessages WHERE IsServerMsg = @tiMsgType AND OrganizationId =@bigOrganizationId )
	END
  
  
SET NOCOUNT OFF
END




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveMDTUserTable]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveMDTUserTable]
	@tiOprType tinyint=null,
	@bigVehId bigint=null,
	@bigUserId bigint=null,
	@vcMDTUserId varchar(5) = NULL,
	@vcMDTUserName varchar(50) = NULL,
	@vcMDTUserPassword varchar(8) = NULL,
	@bigOrganizationId bigint=null
AS
/**********************************************************************************************************************/
--	Name		:	rvlf_sp_SaveMDTUserTable
--	Description	:	To save user in the MDT User Table, Deleting particular user and deleting whole MDT User Table
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	14-Dec-2009		Created Intial Version 
--				:	18-AUG-2011	VN INCLUDED THE ORGANIZATIONID IN THE TABLE.
/**********************************************************************************************************************/
BEGIN
SET NOCOUNT ON 
  
  --DECLARE @intBoxId AS INT = (SELECT BoxId FROM rvlfVehicleAssignment WHERE VehicleId = @bigVehId)  
  IF @tiOprType = 0 -- Add / Update the MDT User Table
	  BEGIN	  
		IF(@bigUserId>0)
			BEGIN
				UPDATE rvlfMDTUserTable SET MDTUserName = @vcMDTUserName, MDTUserPassword = @vcMDTUserPassword,
						MDTUserId=@vcMDTUserId					
					WHERE UserId = @bigUserId AND ORGANIZATIONID=@bigOrganizationId	
			END
		ELSE
			BEGIN		
				INSERT INTO rvlfMDTUserTable ( MDTUserId, MDTUserName, MDTUserPassword,ORGANIZATIONID) 
				VALUES( @vcMDTUserId, @vcMDTUserName, @vcMDTUserPassword,@bigOrganizationId)		
			END	  
	  END
  ELSE IF @tiOprType = 1 -- Delete particular user from MDT User Table
	BEGIN  
		DELETE FROM rvlfMDTUserTable WHERE MDTUserId = @vcMDTUserId AND  ORGANIZATIONID=@bigOrganizationId  
	END
ELSE IF(@tiOprType=2)
	BEGIN
		DELETE FROM rvlfMDTUserTable WHERE UserId=@bigUserId AND ORGANIZATIONID=@bigOrganizationId 
	END
  ELSE
	BEGIN  
		DELETE FROM rvlfMDTUserTable WHERE  ORGANIZATIONID=@bigOrganizationId  
	END  
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveOrganization]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
           
CREATE Procedure [dbo].[rvlf_sp_SaveOrganization]              
 @bigOrganizationID bigint = null,              
 @vcOrganizationName varchar(200)= null,              
 @vcOrganizationDisplayName varchar(20) = null,              
 @vcOrganizationCode varchar(5) = null,              
 @vcVATNumber varchar(20) = null,              
 @vcAddress varchar(200) = null,              
 @vcCityName varchar(75) = null,              
 @vcStateName varchar(75) = null,               
 @bigCountryID bigint = null,               
 @vcPhoneNo varchar(20) = null,              
 @vcMobileNo varchar(15) = null,              
 @vcWebsiteURL varchar(150) = null,              
 @vcOrganizationEmailID varchar(200) = null,              
 @vcDescription varchar(250) = null,              
 @vcLogoName varchar(150) = null,              
 @intMapGroupId int = null,              
 @vcContactPerson varchar(100) = null,              
 @vcDesignation varchar(100) = null,              
 @vcContactEmailID varchar(200) = null,              
 @vcContactPhoneno varchar(20) = null,              
 @bigProcessedBy bigint = null, -- Holds CreatedBy if new else ModifiedBy              
 @dtProcessedOn datetime = null, -- Holds CreatedDate if new else ModifiedDate                 
 @intTotalNoOfEmails int=null,              
 @intTotalNoOfSMS int=null,              
 @intTotalNoOfFleets int=null,              
 @intTotalNoOfVehicles int=null,              
 @intTotalNoOfUsers int=null,              
 @intTotalNoOfPWDChar int=null,              
 @intTotalNoOfIPLockDuration int=null,               
 @intIPTries int=null,              
 @intLockUserTries int=null,                 
 @bitLockIP bit=null,              
 @bitLockUsers bit=null,              
 @bitEnforcesPassword bit=null,              
 @bitChangeOnFirstLogin bit=null,              
 @vcAdminPassword varchar(100)=null,              
 @vcPartnerIds varchar(100)=null,              
 @intDistance int =Null,            
 @intMapProvider int = Null,          
 @vcLogoOptionIds varchar(20)=null,    
 @vcContactPerson2  varchar(100) = null,     
 @vcContactEmailID2 varchar(200) = null,     
 @vcContactPerson3  varchar(100) = null,     
 @vcContactEmailID3 varchar(200) = null,     
 @vcContactPerson4  varchar(100) = null,     
 @vcContactEmailID4 varchar(200) = null,     
 @vcContactPerson5  varchar(100) = null,     
 @vcContactEmailID5 varchar(200) = null,     
 @vcContactPerson6  varchar(100) = null,     
 @vcContactEmailID6 varchar(200) = null,    
 @intCurrId tinyint = 1,    
 @vcOrgLang varchar(50) = null,    
 @intSmsQryCount INT = NULL,  
 @intNoOfLandmarks int = null,   
 @intNoOfGeozones int = null,   
 @intNoOfUserGroups int = null,    
 @vcLangSettings varchar(20) = null,  
  @bitAppEnable bit = null,  
 @intAppExpiryMonth int = null,  
 @intAppReminder int = null,
 @dtAppInsDate datetime = null        
AS              
/******************************************************************************/              
-- Name  : rvlf_sp_SaveOrganization              
-- Description : To insert / update the organization              
-- Author  : M. Jebamalai Jaya Chitra.              
-- Company  : Angler Technologies              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
--    : 11-Nov-2009 MJJC Created Intial Version               
--    : 26-Nov-2009 VN for insert user,insert userprefences and insert / update the organization               
--      setting details              
--    : 2-Dec-2009 VN for insert IP Tries and LockUser Tries              
--    : 21-Feb-2010 MJJC Included the default fleet setting              
--    : 23-Apr-2010 MJJC Included the solution configuration              
--    : 20-Aug-2010 VN include the second level administrator in user preferences              
--    : 18-Sep-2010 SJ included distance and Logo Option              
--    : 28-Oct-2010 SJ Returned OrganizationID             
--    : 24-Feb-2010 TSK Included Hidden user concept             
--    : 20-Jan-2011 Vijay Added new column to the table rvlfOrganization and added map provider option for Navteq and Google          
--    : 25-Oct-2013 Sakthi Currency field included for ROI module    
/******************************************************************************/              
BEGIN              
 SET NOCOUNT ON               
               
 BEGIN TRANSACTION ManageOrganization              
                          
  BEGIN TRY              
   -- Checks whether to insert or update by checking the organization ID              
   IF @bigOrganizationID IS NOT NULL              
    BEGIN              
     -- Checks whether the organization exists.              
     IF EXISTS(SELECT OrganizationID FROM rvlfOrganization WHERE OrganizationId = @bigOrganizationID)              
      BEGIN              
       UPDATE rvlfOrganization SET              
        OrganizationName = @vcOrganizationName,              
        OrganizationDisplayName = @vcOrganizationDisplayName,              
        OrganizationCode = @vcOrganizationCode,              
        VATNumber = @vcVATNumber,              
        [Address] = @vcAddress,              
        CityName = @vcCityName,              
        StateName = @vcStateName,              
     CountryId = @bigCountryID,              
        PhoneNo = @vcPhoneNo,              
        MobileNo = @vcMobileNo,              
        WebsiteURL = @vcWebsiteURL,              
  OrganizationEmailID = @vcOrganizationEmailID,              
        [Description] = @vcDescription,              
        LogoName = @vcLogoName,              
        MapGroupId = @intMapGroupId,              
        ContactPerson = @vcContactPerson,              
        Designation = @vcDesignation,              
        ContactEmailID = @vcContactEmailID,              
        ContactPhoneNo = @vcContactPhoneno,              
        ModifiedBy = @bigProcessedBy,              
        ModifiedDateTime = @dtProcessedOn,              
        TotalNoofEmailTries=@intTotalNoOfEmails,              
    TotalNoofSMSTries =@intTotalNoOfSMS,              
        NoOfFleet =@intTotalNoOfFleets,              
        NoOfVehicles=@intTotalNoOfVehicles,              
        NoOfUsers=@intTotalNoOfUsers,              
        PwdMinCharacters=@intTotalNoOfPWDChar,              
        LockIP=@bitLockIP,              
        IPLockDuration=@intTotalNoOfIPLockDuration,              
        LockUser=@bitLockUsers,              
        IPTries=@intIPTries,              
        LockUserTries=@intLockUserTries,               
        EnforcePasswordPolicy=@bitEnforcesPassword,              
        CngOnFirstLogin=@bitChangeOnFirstLogin,            
        OrgDistance=@intDistance,          
        OrgMapProvider=@intMapProvider,          
        ContactPerson2=@vcContactPerson2,    
        ContactPerson3=@vcContactPerson3,         
        ContactPerson4=@vcContactPerson4,    
        ContactPerson5=@vcContactPerson5,    
        ContactPerson6=@vcContactPerson6,    
        ContactEmailID2=@vcContactEmailID2,    
        ContactEmailID3=@vcContactEmailID3,    
        ContactEmailID4=@vcContactEmailID4,    
        ContactEmailID5=@vcContactEmailID5,    
        ContactEmailID6=@vcContactEmailID6,    
        CurrencyTypeId=@intCurrId,    
        OrgLang=@vcOrgLang,     
        SMSQryCount = @intSmsQryCount,  
        NoOfLandmarks = @intNoOfLandmarks,  
        NoOfGeozones = @intNoOfGeozones,  
        NoOfUSerGroups = @intNoOfUserGroups,  
        OrgLangSettings = @vcLangSettings,   
        AppInsdate = @dtAppInsDate,   
        EnableApp = @bitAppEnable,  
        AppExpDays = @intAppExpiryMonth,  
        AppReminder1 =  @intAppReminder          
       WHERE OrganizationId= @bigOrganizationID              
                    
      --DELETE THE EXISTING BDES                     
       DELETE rvlfPartnerMaster WHERE OrganizationId=@bigOrganizationID               
      --INSERT THE NEW BDES               
       IF(@vcPartnerIds IS NOT NULL)              
        BEGIN               
         INSERT INTO RVLFPARTNERMASTER(PARTNERID,ORGANIZATIONID)        
          SELECT CAST(FieldValue as bigint),@bigOrganizationID FROM dbo.rvlf_fn_ConvertArrayToTable(@vcPartnerIds,',')              
        END             
        --Included by Jeyanthi  on 18-Sep-2010                   
       --DELETE THE EXISTING Logo Option                     
       DELETE rvlfOrganizationLogoOption WHERE OrganizationId=@bigOrganizationID               
      --INSERT THE NEW BDES               
       IF(@vcLogoOptionIds IS NOT NULL)              
        BEGIN               
         INSERT INTO rvlfOrganizationLogoOption(LogoOptionID,OrganizationID)              
          SELECT @bigOrganizationID,CAST(FieldValue as bigint) FROM dbo.rvlf_fn_ConvertArrayToTable(@vcLogoOptionIds,',')              
        END              
            --End Logo Option                      
      END              
    END              
   ELSE              
    BEGIN             
     -- Inserts the new organization information.              
     INSERT INTO rvlfOrganization               
      ( OrganizationName,OrganizationDisplayName,OrganizationCode,VATNumber,               
        [Address] , CityName, StateName,CountryId, PhoneNo, MobileNo,               
        WebsiteURL, OrganizationEmailID, [Description], LogoName, MapGroupId,              
        ContactPerson, Designation, ContactEmailID,ContactPhoneNo,              
        CreatedBy, CreatedDateTime,TotalNoofEmailTries,TotalNoofSMSTries,NoOfFleet,NoOfVehicles,NoOfUsers,              
        PwdMinCharacters,LockIP,IPLockDuration,LockUser,EnforcePasswordPolicy,CngOnFirstLogin,IPTries,LockUserTries,OrgDistance,OrgMapProvider,    
        ContactPerson2,ContactPerson3,ContactPerson4,ContactPerson5,ContactPerson6,ContactEmailID2,ContactEmailID3,ContactEmailID4,    
        ContactEmailID5,ContactEmailID6,CurrencyTypeId,OrgLang,SMSQryCount,OrgLangSettings,NoOfLandmarks,NoOfGeozones,NoOfUSerGroups,  
         EnableApp,AppExpDays, AppReminder1)               
     VALUES              
      ( @vcOrganizationName, @vcOrganizationDisplayName,@vcOrganizationCode, @vcVATNumber,              
        @vcAddress, @vcCityName,@vcStateName, @bigCountryID, @vcPhoneNo, @vcMobileNo,              
        @vcWebsiteURL, @vcOrganizationEmailID, @vcDescription, @vcLogoName, @intMapGroupId,               
        @vcContactPerson, @vcDesignation, @vcContactEmailID, @vcContactPhoneno,              
        @bigProcessedBy, @dtProcessedOn,@intTotalNoOfEmails,@intTotalNoOfSMS,              
        @intTotalNoOfFleets,@intTotalNoOfVehicles,@intTotalNoOfUsers,@intTotalNoOfPWDChar,@bitLockIP,              
        @intTotalNoOfIPLockDuration,@bitLockUsers,@bitEnforcesPassword,@bitChangeOnFirstLogin,@intIPTries,@intLockUserTries,@intDistance,@intMapProvider,    
        @vcContactPerson2,@vcContactPerson3,@vcContactPerson4,@vcContactPerson5,@vcContactPerson6,@vcContactEmailID2,@vcContactEmailID3,@vcContactEmailID4,    
        @vcContactEmailID5,@vcContactEmailID6,@intCurrId,@vcOrgLang,@intSmsQryCount,@vcLangSettings,@intNoOfLandmarks,@intNoOfGeozones,@intNoOfUserGroups,  
        @bitAppEnable,@intAppExpiryMonth,@intAppReminder)                  
                      
     SET @bigOrganizationID = @@IDENTITY              
                   
     --DELETE THE EXISTING BDES                     
       DELETE rvlfPartnerMaster WHERE OrganizationId=@bigOrganizationID               
     --INSERT THE NEW BDES               
       IF(@vcPartnerIds IS NOT NULL)              
        BEGIN               
         INSERT INTO RVLFPARTNERMASTER(PARTNERID,ORGANIZATIONID)              
          SELECT CAST(FieldValue as bigint),@bigOrganizationID FROM dbo.rvlf_fn_ConvertArrayToTable(@vcPartnerIds,',')              
        END             
                    
   --Included by Jeyanthi  on 18-Sep-2010             
       --DELETE THE EXISTING Logo Option                     
       DELETE rvlfOrganizationLogoOption WHERE OrganizationId=@bigOrganizationID               
      --INSERT THE NEW BDES               
       IF(@vcLogoOptionIds IS NOT NULL)              
        BEGIN               
         INSERT INTO rvlfOrganizationLogoOption(LogoOptionID,OrganizationID)              
          SELECT @bigOrganizationID,CAST(FieldValue as bigint) FROM dbo.rvlf_fn_ConvertArrayToTable(@vcLogoOptionIds,',')              
        END                 
       --End Logo Option            
              
     INSERT INTO rvlfOrganizationSolution (OrganizationId, SolutionId) VALUES (@bigOrganizationID,1)              
                   
     -- Inserts the default fleet to the organizaiton              
     INSERT INTO rvlfFleet               
      ( FleetName, OrganizationId, [Description], CreatedBy, CreatedDate, IsDefault )              
     VALUES              
      ( 'All', @bigOrganizationID, 'Default', @bigProcessedBy, @dtProcessedOn, 1 )              
                   
     DECLARE @bigFleetID bigint = @@IDENTITY              
                   
     -- Inserts the groups related to the organization              
     INSERT INTO rvlfUserGroup               
      ( UserGroupName, UserGroupDesc,IsDefaultUserGroup, OrganizationId, CreatedBy, CreatedDate )              
     VALUES               
      ('Security Admin', 'Security Admin',1, @bigOrganizationID, @bigProcessedBy, @dtProcessedOn)              
      --,('Security High', 'Security High',1, @bigOrganizationID, @bigProcessedBy, @dtProcessedOn),              
      --('Security Low', 'Security Low',1, @bigOrganizationID, @bigProcessedBy, @dtProcessedOn)              
                   
     DECLARE @bigUserGroupID bigint=@@IDENTITY              
                   
     -- Inserts the default User              
     INSERT INTO rvlfUser               
      (UserName,[Password],OrganizationId,Firstname,LastName,IsLocked,              
       CreatedBy,CreatedDateTime,IsActive, DisplayName, IsPwdChanged,ISDELETE)              
     VALUES              
      ('Administrator',@vcAdminPassword,@bigOrganizationID,              
       'Admin','Admin',0,@bigProcessedBy, @dtProcessedOn,1,'Admin',1,0)              
                   
       DECLARE @bigUserID bigint=@@IDENTITY             
                   
       INSERT INTO rvlfUser               
      (UserName,[Password],OrganizationId,Firstname,LastName,IsLocked,              
       CreatedBy,CreatedDateTime,IsActive, DisplayName, IsPwdChanged,ISDELETE,IsHidden)              
     VALUES              
      ('hidden',@vcAdminPassword,@bigOrganizationID,              
       'Admin','Admin',0,@bigProcessedBy, @dtProcessedOn,1,'Hidden',1,0,1)              
                   
      DECLARE @bigHiddenUserID bigint=@@IDENTITY             
                   
     --Insert the default User Preferences              
     INSERT INTO rvlfUserPreferences               
      (UserId, TimezoneId, RefreshFrequencyId, Distance, DefaultFleetId,DefaultDateFormat,UserPreferedChart,Lang)              
     VALUES              
      (@bigUserID,@bigCountryID,0,0,@bigFleetID,106,'4,3,2,1','LanguageEn')              
                   
       --Insert the default User Preferences for hidden user             
     INSERT INTO rvlfUserPreferences               
      (UserId, TimezoneId, RefreshFrequencyId, Distance, DefaultFleetId,DefaultDateFormat,UserPreferedChart,Lang)              
     VALUES              
      (@bigHiddenUserID,@bigCountryID,0,0,@bigFleetID,106,'4,3,2,1','LanguageEn')             
                   
     IF(@bigUserID>0)              
      BEGIN              
       --Insert the Default User Group              
       INSERT INTO rvlfUserGroupAssignment              
        (UserId,UserGroupId,AssignedBy,AssignedDate)              
       VALUES(@bigUserID,@bigUserGroupID,@bigProcessedBy,@dtProcessedOn)               
                   
       --Insert the Default User Group for hidden user              
       INSERT INTO rvlfUserGroupAssignment              
        (UserId,UserGroupId,AssignedBy,AssignedDate)              
       VALUES(@bigHiddenUserID,@bigUserGroupID,@bigProcessedBy,@dtProcessedOn)               
                   
       END              
                   
     --Check the fleet count for the default user              
     DECLARE @FleetCount AS BIGINT = 0;              
                 
     SELECT @FleetCount = COUNT(*)               
          FROM rvlfFleetUsers               
          WHERE UserId=@bigUserID AND FleetId = @bigFleetID              
     IF (@FleetCount=0)              
       BEGIN              
      INSERT INTO rvlfFleetUsers               
       (FleetId,UserId,AssignedBy,AssignedDate)               
      VALUES               
       (@bigFleetID,@bigUserID,@bigProcessedBy,@dtProcessedOn)             
                   
       -- Hidden user            
       INSERT INTO rvlfFleetUsers               
       (FleetId,UserId,AssignedBy,AssignedDate)               
      VALUES               
       (@bigFleetID,@bigHiddenUserID,@bigProcessedBy,@dtProcessedOn)              
       END                     
     END             
                 
     --INCLUDED BY JEYANTHI FOR BULK DEVICE AND VEHICLE CREATION             
     DECLARE @NoOfVehicles bigint=(SELECT NoOfVehicles FROM rvlfOrganization WHERE OrganizationId =  @bigOrganizationID)              
     DECLARE @NoOfVehiclesAvailable bigint=(SELECT Count(VehicleId)  FROM rvlfVehicle WHERE OrganizationId =  @bigOrganizationID)              
     DECLARE @NoOfVehiclesPending bigint=ISNULL(@NoOfVehicles,0)-ISNULL(@NoOfVehiclesAvailable,0)            
                 
     SELECT @bigOrganizationID  OrganizationID,ISNULL(@NoOfVehicles,0)NoOfVehicles,            
     ISNULL(@NoOfVehiclesAvailable,0) NoOfVehiclesAvailable,  ISNULL(@NoOfVehiclesPending,0)NoOfVehiclesPending            
     --END            
   COMMIT              
  END TRY              
  BEGIN CATCH              
   ROLLBACK              
   DECLARE @vcError varchar(max) = 'Error in updating the organization. Try Again !'              
   raiserror(@vcError,16,1);              
  END CATCH              
 SET NOCOUNT OFF              
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveorModifyEquipmentAssign]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_SaveorModifyEquipmentAssign]
	-- Add the parameters for the stored procedure here
	@tag char(1),
	@BoxID varchar(100)=null,
	@OrganizationID bigint=null,
	@bigUserid bigint=null,
	@EquipmentIDs varchar(MAX)=null,
	--@EquItemID varchar(MAX)=null,
	@isAssign bit=null
AS
BEGIN
	SET NOCOUNT ON;

	if(@tag='A')
		begin
			--delete from rvlfEquipmentAssignment where BoxID=@BoxID
			insert into rvlfEquipmentAssignment
			select value,@BoxID,@bigUserid,GETDATE() from [dbo].[fn_Split](@EquipmentIDs,',')
			insert into rvlfEquipmentItemAssignment(EquipmentID,ItemID,BoxID,CreatedBy,CreatedDate)
			Select ITD.ItemTypeID,ITD.ItemID,@BoxID,@bigUserid,GETDATE() from rvlfItemTypeDetails ITD inner join [dbo].[fn_Split](@EquipmentIDs,',') EQ on EQ.value=ITD.ItemTypeID
			--select (Select value from [dbo].[fn_Split](value,'-') where position=1) as EQID,(Select value from [dbo].[fn_Split](value,'-') where position=2) as ItemID,@BoxID,@bigUserid,GETDATE() from [dbo].[fn_Split](@EquItemID,',')
			--insert into rvlfEquipmentItemAssignment
		end
	if(@tag='U')
		begin
			delete from rvlfEquipmentAssignment where BoxID=@BoxID and EquipmentID in (select value from [dbo].[fn_Split](@EquipmentIDs,','))
			delete from rvlfEquipmentItemAssignment where BoxID=@BoxID and EquipmentID in (select value from [dbo].[fn_Split](@EquipmentIDs,','))
		end
	else if(@tag='S')
		begin
			if(@isAssign=0)
				begin
					SELECT ITM.ItemTypeID, ITM.ItemTypeName,ITM.ItemtypeDesc,
					ISNULL(STUFF((SELECT ', ' + ItemName
					FROM dbo.rvlfItemTypeDetails ITD
					INNER JOIN dbo.rvlfInvItemMaster IM ON IM.ItemSNo = ITD.ItemID
					WHERE ITD.ItemTypeID = ITM.ItemTypeID
					FOR XML PATH('')
					), 1, 1, ''), 'Not Assigned Yet') AS ItemList,ISNULL(STUFF((SELECT ',' + cast(ItemSNo as varchar(10))
					FROM dbo.rvlfItemTypeDetails ITD
					INNER JOIN dbo.rvlfInvItemMaster IM ON IM.ItemSNo = ITD.ItemID
					WHERE ITD.ItemTypeID = ITM.ItemTypeID
					FOR XML PATH('')
					), 1, 1, ''), '') AS ItemListID,Image
					FROM dbo.rvlfItemTypeMaster ITM where OrganizatioID=@OrganizationID and ITM.isDelete=0 and ITM.ItemTypeID not in (select EquipmentID from rvlfEquipmentAssignment where BoxID=@BoxID)
					
					select MD.BoxId,md.EquipmentName,c.CustomerName,c.MobileNo,VT.VehicleTypeName from rvlfMAKDevices MD inner join rvlfVehicleType VT on MD.SubTypeId=VT.VehicleTypeId inner join rvlfCustomers c on c.CustomerId=MD.CustomerId where MD.BoxID=@BoxID

					select ITM.ItemTypeID,ITM.ItemTypeName,ITM.ItemtypeDesc,IM.OrganizatioID,IM.ItemSNo,IM.Itemcode,IM.ItemName,IM.ItemDesc,(cast(ITM.ItemTypeID as varchar)  + '-' + cast(IM.ItemSNo as varchar)) as ItemDetails
					FROM dbo.rvlfItemTypeMaster ITM 
					inner join dbo.rvlfItemTypeDetails ITD on ITM.ItemTypeID=ITD.ItemTypeID 
					inner join dbo.rvlfInvItemMaster IM on IM.ItemSNo=ITD.ItemID
					where ITM.isDelete=0 and ITM.ItemTypeID not in (select EquipmentID from rvlfEquipmentAssignment where BoxID=@BoxID) order by ITM.ItemTypeID

				end
			else if(@isAssign=1)
				begin
					SELECT ITM.ItemTypeID, ITM.ItemTypeName,ITM.ItemtypeDesc,
					ISNULL(STUFF((SELECT ', ' + ItemName
					FROM dbo.rvlfItemTypeDetails ITD
					INNER JOIN dbo.rvlfInvItemMaster IM ON IM.ItemSNo = ITD.ItemID
					inner join dbo.rvlfEquipmentItemAssignment IA ON IA.ItemID=ITD.ItemID and ITD.ItemTypeID=IA.EquipmentID and IA.BoxID=@BoxID
					WHERE ITD.ItemTypeID = ITM.ItemTypeID
					FOR XML PATH('')
					), 1, 1, ''), 'Not Assigned Yet') AS ItemList,ISNULL(STUFF((SELECT ',' + cast(ItemSNo as varchar(10))
					FROM dbo.rvlfItemTypeDetails ITD
					INNER JOIN dbo.rvlfInvItemMaster IM ON IM.ItemSNo = ITD.ItemID
					inner join dbo.rvlfEquipmentItemAssignment IA ON IA.ItemID=ITD.ItemID and ITD.ItemTypeID=IA.EquipmentID and IA.BoxID=@BoxID
					WHERE ITD.ItemTypeID = ITM.ItemTypeID
					FOR XML PATH('')
					), 1, 1, ''), '') AS ItemListID,Image
					FROM dbo.rvlfItemTypeMaster ITM where OrganizatioID=@OrganizationID and ITM.isDelete=0 and ITM.ItemTypeID in (select EquipmentID from rvlfEquipmentAssignment where BoxID=@BoxID)

					select MD.BoxId,md.EquipmentName,c.CustomerName,c.MobileNo,VT.VehicleTypeName from rvlfMAKDevices MD inner join rvlfVehicleType VT on MD.SubTypeId=VT.VehicleTypeId inner join rvlfCustomers c on c.CustomerId=MD.CustomerId where MD.BoxID=@BoxID

					select ITM.ItemTypeID,ITM.ItemTypeName,ITM.ItemtypeDesc,IM.OrganizatioID,IM.ItemSNo,IM.Itemcode,IM.ItemName,IM.ItemDesc,(cast(ITM.ItemTypeID as varchar)  + '-' + cast(IM.ItemSNo as varchar)) as ItemDetails
					FROM dbo.rvlfItemTypeMaster ITM 
					inner join dbo.rvlfItemTypeDetails ITD on ITM.ItemTypeID=ITD.ItemTypeID 
					inner join dbo.rvlfInvItemMaster IM on IM.ItemSNo=ITD.ItemID
					where ITM.isDelete=0 and ITM.ItemTypeID in (select EquipmentID from rvlfEquipmentAssignment where BoxID=@BoxID) order by ITM.ItemTypeID

				end
		end
    
	
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_Sp_SaveorUpdateItemTypeMaster]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- rvlf_Sp_SaveorUpdateItemTypeMaster @tag='S'
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_Sp_SaveorUpdateItemTypeMaster]
	-- Add the parameters for the stored procedure here
	@tag char(1),
	@ItemTypeID bigint=null,
	@ItemTypeName varchar(100)=null,
	@ItemTypeDesc varchar(250)=null,
	@Image nvarchar(MAX)=null,
	@bigOrganizationId bigint=null,
	@ItemDetailsXML XML =NULL, 
	@BoxID varchar(100)=null,
	@bigUserID bigint=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @ErrorMessage varchar(3000)  
	DECLARE @docHandle int   
	DECLARE  @tblItemDetailsXML TABLE (ItemId bigint,SlNo bigint ) 

	EXEC sp_xml_preparedocument @docHandle OUTPUT, @ItemDetailsXML                                         
					INSERT INTO @tblItemDetailsXML                                                      
					  SELECT * FROM OPENXML(@docHandle, '/DocumentElement/ItemDetails')               
					  WITH                 
					  (                         
					  ItemSNo bigint 'ItemSNo'                          
					  ,SerialNo bigint 'SerialNo'           
					  )      
    -- Insert statements for procedure here
	if(@tag='I')
		begin
			declare @LastItemTypeID bigint
			if not exists(select * from rvlfItemTypeMaster where ItemTypeName =@ItemTypeName and OrganizatioID=@bigOrganizationId and isDelete=0)
				begin
					insert into rvlfItemTypeMaster(ItemTypeName,ItemtypeDesc,Image,CreatedBy,CreatedDate,OrganizatioID,isDelete) values (@ItemTypeName,@ItemtypeDesc,@Image,@bigUserID,GETDATE(),@bigOrganizationId,0)
					SET @LastItemTypeID = IDENT_CURRENT('rvlfItemTypeMaster')
					insert into rvlfItemTypeDetails
					select @LastItemTypeID,* from @tblItemDetailsXML
				end
			else
				begin	
					    RAISERROR('Item Type Name already exists!',15,0)  
				end
		end
	else if(@tag='U')
		begin
			update rvlfItemTypeMaster set ItemTypeName=@ItemTypeName,ItemtypeDesc=@ItemtypeDesc,Image=@Image,ModifyBy=@bigUserID,ModifyDate=GETDATE() where ItemTypeID=@ItemTypeID
			delete from rvlfItemTypeDetails where ItemTypeID=@ItemTypeID
			insert into rvlfItemTypeDetails
			select @ItemTypeID,* from @tblItemDetailsXML
		end
	else if(@tag='D')
		begin
			if exists(select * from rvlfEquipmentAssignment where EquipmentID=@ItemTypeID)
				begin
					 RAISERROR('You cannot delete an equipment already assigned to device',15,0)           
				end
			else
				begin
					update rvlfItemTypeMaster set isDelete=1,ModifyBy=@bigUserID,ModifyDate=getdate() where ItemTypeID=@ItemTypeID
					delete from rvlfItemTypeDetails where ItemTypeID=@ItemTypeID
				end
		end
	else if(@tag='S')
		begin
			SELECT ITM.ItemTypeID, ITM.ItemTypeName,ITM.ItemtypeDesc,
			'' AS ItemList,ISNULL(STUFF((SELECT ',' + cast(ItemSNo as varchar(10))
			FROM dbo.rvlfItemTypeDetails ITD
			INNER JOIN dbo.rvlfInvItemMaster IM ON IM.ItemSNo = ITD.ItemID
			WHERE ITD.ItemTypeID = ITM.ItemTypeID
			FOR XML PATH('')
			), 1, 1, ''), '') AS ItemListID,Image
			FROM dbo.rvlfItemTypeMaster ITM where 
			((@ItemTypeID IS NULL OR @ItemTypeID='') OR ITM.ItemTypeID = @ItemTypeID)
			and OrganizatioID=@bigOrganizationId and ITM.isDelete=0

			select ItemSNo,Itemcode,ItemName,ItemDesc,AvailQty,OpenQty,ReorderQty,UnitPrice,IsActive,        
			ItemCatID,ItemCategoryName, TotalReceipts, UOM,   
			null as EmailList,                                                
			 null as SMSList,                                        
			 null as EmailUserNameList,     
			 null as SMSUserNameList,isnull(ItemImage,'') as ItemImage,SerialNo as SerialNo,ItemID,ItemTypeDetailID,ItemTypeID,SlNo,isAvail
			 from (       
			 SELECT ItemSNo,ITM.Itemcode,ItemName,ItemDesc,AvailQty,OpenQty,ReorderQty,ITM.UnitPrice,IsActive,        
			ITM.ItemCatID,ItemCategoryName,COUNT(IET.InvSno) as TotalReceipts ,ITM.UOM ,ITM.ItemImage,ITM.SerialNo,ITD.ItemID,ITD.ItemTypeDetailID,ITD.ItemTypeID,ITD.SlNo,(case when IA.ItemID is null then 1 else 2 end) as isAvail
			from rvlfInvItemMaster ITM 
			inner join rvlfItemCategory ItmC on ITM.ItemCatID=Itmc.ItemCatID   
			inner join rvlfItemTypeDetails ITD on ITM.ItemSNo=ITD.ItemID
			left join dbo.rvlfEquipmentItemAssignment IA ON IA.ItemID=ITD.ItemID and ITD.ItemTypeID=IA.EquipmentID and IA.BoxID=@BoxID
			left join rvlfInvoiceItems IET on ITM.Itemcode=IET.ItemCode
			where ITM.OrganizatioID=@bigOrganizationId  and IsActive=1 and ((@ItemTypeID IS NULL OR @ItemTypeID='') OR ItemTypeID = @ItemTypeID)
			group by ItemSNo,ITM.Itemcode,ItemName,ItemDesc,AvailQty,OpenQty,ReorderQty,ITM.UnitPrice,IsActive,        
			ITM.ItemCatID,ItemCategoryName ,ITM.UOM ,ITM.ItemImage,ITD.ItemID,ITD.ItemTypeDetailID,ITD.ItemTypeID,ITD.SlNo,ITM.SerialNo,IA.ItemID
			) as a  order by ItemSNo desc  
			--select * from rvlfItemTypeDetails where ItemTypeID=COALESCE(@ItemTypeID,ItemTypeID)
		end

END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveorupdateSparesRequest]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- rvlf_sp_SaveorupdateSparesRequest @tag='S'
-- exec rvlf_sp_SaveorupdateSparesRequest @tag=N'S',@OrganizationID=N'6',@bigUserId=N'561'
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_SaveorupdateSparesRequest]
	-- Add the parameters for the stored procedure here
	@tag char(1),
	@RequestID bigint=null,
	--@BoxId varchar(100)=null,
	--@EquipmentID bigint=null,
	--@ItemIDs varchar(200)=null,
	@RequestDetails XML = null,
	@RequestBy bigint=null,
	@FromDate datetime=null,
	@Todate datetime=null,
	@OrganizationID bigint=null,
	@bigUserId bigint=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;



	DECLARE @docHandle int           
	DECLARE  @temptable TABLE (DeviceID varchar(100),EquipmentID bigint,ItemsID varchar(max),TotalQty varchar(max))        
            
	IF @RequestDetails IS NOT NULL         
		BEGIN                        
			EXEC sp_xml_preparedocument @docHandle OUTPUT, @RequestDetails                                 
			INSERT INTO @tempTable                                              
			SELECT * FROM OPENXML(@docHandle, '/DocumentElement/Request')       
			WITH
			(
				DeviceID varchar(100) 'DeviceID',
				EquipmentID bigint 'EquipmentID',
				ItemsID varchar(max) 'ItemsID',
				TotalQty varchar(max) 'TotalQty'
			)
		END
			DECLARE @DefaultDateFormat INT = 0      
			--declare @CheckUser int =null,@lastname nvarchar(100),@CheckUGid int 
			--select @CheckUGid=UserGroupId from rvlfUserGroupAssignment where UserId=@bigUserId
			--select @lastname=LastName from rvlfUser where UserId=@bigUserId
			--if((@lastname like '%VXL%' or @lastname like '%trinetra%') or @CheckUGid=1)
			--	begin
			--		set @CheckUser=null
			--	end
			--else
			--	begin
			--		set @CheckUser=1
			--	end
  
		 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(@bigUserId IS NULL OR @bigUserId='' OR up.UserId = @bigUserId)                        

			-- Insert statements for procedure here
			if(@tag='I')
				begin
					declare @SparesID bigint
					--insert into rvlfSparesRequestMaster(BoxId,EquipmentID,ItemIDs,RequestBy,RequestDate,OrganizationID,isDelete) values (@BoxId,@EquipmentID,@ItemIDs,@RequestBy,getdate(),@OrganizationID,0)
					insert into rvlfSparesRequestMaster(RequestBy,RequestDate,OrganizationID,isDelete) values (@RequestBy,getdate(),@OrganizationID,0)
					select @SparesID=IDENT_CURRENT('rvlfSparesRequestMaster')
					insert into rvlfSparesRequestDetails(RequestID,BoxID,EquipmentID,ItemIds,ItemIDswithQty)
					select @SparesID,DeviceID, EquipmentID, ItemsID,TotalQty from @temptable

				end
			else if(@tag='U')
				begin
					update rvlfSparesRequestMaster set ModifyBy=@RequestBy,ModifyDate=GETDATE(),OrganizationID=@OrganizationID where RequestID=@RequestID
					delete from rvlfSparesRequestDetails where RequestID=@RequestID
					insert into rvlfSparesRequestDetails(RequestID,BoxID,EquipmentID,ItemIds,ItemIDswithQty)
					select @RequestID,DeviceID, EquipmentID, ItemsID,TotalQty from @temptable
				end
			else if(@tag='D')
				begin
					update rvlfSparesRequestMaster set isDelete=1 where RequestID=@RequestID
				end
			else if(@tag='S')
				begin
					select distinct SM.RequestID,D.CustomerName,ItemList=cast(STUFF  
(  
    (  
      SELECT DISTINCT CAST(ISNULL(STUFF(CHAR(10) +' ~Device Name: ' + D.EquipmentName + CHAR(10) +' ~Equipment Name: ' + ITM.ItemTypeName + CHAR(10) +' ~Spares List: ' + 
	  
	  (SELECT  ItemName + ' - ' + cast(ITD.value as varchar) + ', '  FROM (Select ITD.value as ItemID,ITD1.value from [dbo].[fn_Split]((select value from [dbo].[fn_Split](g.ItemIDswithQty,'$') where position=1),',') ITD inner join [dbo].[fn_Split]((select value from [dbo].[fn_Split](g.ItemIDswithQty,'$') where position=2),',') ITD1 on ITD.position=ITD1.position
	  ) ITD
					INNER JOIN dbo.rvlfInvItemMaster IM ON IM.ItemSNo = ITD.ItemID
					FOR XML PATH('')
					) + '~~', 1, 1, ''), 'Not Assigned Yet') AS VARCHAR(MAX))  
      FROM rvlfSparesRequestDetails g,rvlfSparesRequestDetails e ,rvlfMAKDevices D ,rvlfItemTypeMaster ITM  ,rvlfUser U
      WHERE g.RequestID=e.RequestID and e.RequestID=SM.RequestID and d.BoxId=g.BoxID and g.EquipmentID=ITM.ItemTypeID and U.UserId=SM.RequestBy
      FOR XMl PATH('')  
    ),1,1,''  
) as varchar(max)),ItemDetails=cast(REPLACE(REPLACE(REPLACE(REPLACE(STUFF(  (SELECT DISTINCT ' <table class="table table-bordered" style="margin-bottom:10px"><tr><td>' + CAST(ISNULL(STUFF(CHAR(10) +'<b>Device Name</b></td><td>' + D.EquipmentName + '</td></tr><tr><td>' +'<b>Equipment Name</b></td><td>' + ITM.ItemTypeName + '</td></tr><tr><td colspan="2">' +'<b>Spares List</b> </td></tr><tr><td colspan="2"><table class="table table-bordered" style="margin-bottom:0px"><tr><td><b>Item</b></td><td><b>Qty</b></td></tr>' + 
	  
	  (SELECT '<tr><td>'+ ItemName + '</td><td>' + cast(ITD.value as varchar) + '</td></tr>'  FROM (Select ITD.value as ItemID,ITD1.value from [dbo].[fn_Split]((select value from [dbo].[fn_Split](g.ItemIDswithQty,'$') where position=1),',') ITD inner join [dbo].[fn_Split]((select value from [dbo].[fn_Split](g.ItemIDswithQty,'$') where position=2),',') ITD1 on ITD.position=ITD1.position
	  ) ITD
					INNER JOIN dbo.rvlfInvItemMaster IM ON IM.ItemSNo = ITD.ItemID
					FOR XML PATH('')
					) + '</table></td></tr></table>', 1, 1, ''), 'Not Assigned Yet') AS VARCHAR(MAX))  
      FROM rvlfSparesRequestDetails g,rvlfSparesRequestDetails e ,rvlfMAKDevices D ,rvlfItemTypeMaster ITM  ,rvlfUser U
      WHERE g.RequestID=e.RequestID and e.RequestID=SM.RequestID and d.BoxId=g.BoxID and g.EquipmentID=ITM.ItemTypeID and U.UserId=SM.RequestBy
      FOR XMl PATH('') )  ,1,1,''  
),'&lt;','<'),'&gt;','>'),'&amp;lt;','<' ),'&amp;gt;','>') as varchar(max))   ,Convert(varchar,SM.RequestDate,@DefaultDateFormat) + ' '+ Convert(varchar,cast(SM.RequestDate as time),22) as RequestDate,U.DisplayName,SM.ItemIDs from rvlfSparesRequestMaster SM 
					inner join rvlfSparesRequestDetails itd on itd.RequestID=sm.RequestID
					inner join rvlfMAKDevices D on itd.BoxID=D.BoxId and D.IsDelete=0
					inner join rvlfItemTypeMaster ITM on ITM.ItemTypeID=itd.EquipmentID 
					inner join rvlfUser U on u.UserId=SM.RequestBy where 
					--((@BoxId IS NULL OR @BoxId='') OR SM.BoxId = @BoxId)
					--and ((@EquipmentID IS NULL OR @EquipmentID='') OR SM.EquipmentID = @EquipmentID) and 
					cast(SM.RequestDate as date) between cast(coalesce(@FromDate,SM.RequestDate) as date) and cast(coalesce(@Todate,SM.RequestDate) as date) 
					and ((@RequestBy IS NULL OR @RequestBy='') OR SM.RequestBy = @RequestBy) and SM.RequestID=coalesce(@RequestID,SM.RequestID)
					--and ((@CheckUser is Null) or (D.CustomerName = @lastname)) 
					and SM.OrganizationID=@OrganizationID  order by SM.RequestID desc 
					select * from rvlfuser u inner join rvlfTitle t on t.TitleId=u.TitleId where u.UserName='SparesEmail' and OrganizationId=@OrganizationID
				end
			else if(@tag='M')
				begin
					select DISTINCT SM.RequestID,SD.BoxID as DeviceID,SD.EquipmentID,D.CustomerId,D.CustomerName,ITM.ItemTypeName as EquipmentName,D.EquipmentName as DeviceName,SD.ItemIds as ItemsID,Convert(varchar,SM.RequestDate,@DefaultDateFormat) + ' '+ Convert(varchar,cast(SM.RequestDate as time),22) as RequestDate,CAST(ISNULL(STUFF((SELECT ', ' + ItemName + ' - ' + cast(ITD.value as varchar)   FROM (Select ITD.value as ItemID,ITD1.value from [dbo].[fn_Split]((select value from [dbo].[fn_Split](SD.ItemIDswithQty,'$') where position=1),',') ITD inner join [dbo].[fn_Split]((select value from [dbo].[fn_Split](SD.ItemIDswithQty,'$') where position=2),',') ITD1 on ITD.position=ITD1.position
	  ) ITD
					INNER JOIN dbo.rvlfInvItemMaster IM ON IM.ItemSNo = ITD.ItemID
					FOR XML PATH('')
					), 1, 1, ''), 'Not Assigned Yet') AS VARCHAR(MAX)) as ItemDetails, 
					
					cast(REPLACE(REPLACE(REPLACE(REPLACE(STUFF(  (SELECT DISTINCT ' <table class="table table-bordered" style="margin-bottom:10px"><tr><td colspan="2">' + CAST(ISNULL(STUFF(CHAR(10) +'<b>Spares List</b> </td></tr><tr><td colspan="2"><table class="table table-bordered" style="margin-bottom:0px"><tr><td><b>Item</b></td><td><b>Qty</b></td></tr>' + 
	  
	  (SELECT '<tr><td>'+ ItemName + '</td><td>' + cast(ITD.value as varchar) + '</td></tr>'  FROM (Select ITD.value as ItemID,ITD1.value from [dbo].[fn_Split]((select value from [dbo].[fn_Split](g.ItemIDswithQty,'$') where position=1),',') ITD inner join [dbo].[fn_Split]((select value from [dbo].[fn_Split](g.ItemIDswithQty,'$') where position=2),',') ITD1 on ITD.position=ITD1.position
	  ) ITD
					INNER JOIN dbo.rvlfInvItemMaster IM ON IM.ItemSNo = ITD.ItemID
					FOR XML PATH('')
					) + '</table></td></tr></table>', 1, 1, ''), 'Not Assigned Yet') AS VARCHAR(MAX))  
      FROM rvlfSparesRequestDetails g,rvlfSparesRequestDetails e ,rvlfMAKDevices D ,rvlfItemTypeMaster ITM  ,rvlfUser U
      WHERE g.RequestID=e.RequestID and e.RequestID=SM.RequestID and d.BoxId=g.BoxID and g.EquipmentID=ITM.ItemTypeID and U.UserId=SM.RequestBy and g.BoxID=SD.BoxID
      FOR XMl PATH('') )  ,1,1,''  
),'&lt;','<'),'&gt;','>'),'&amp;lt;','<' ),'&amp;gt;','>') as varchar(max)) as ItemNames from rvlfSparesRequestMaster SM inner join rvlfSparesRequestDetails SD on SM.RequestID=SD.RequestID inner join rvlfMAKDevices D on D.BoxId=SD.BoxID inner join rvlfItemTypeMaster ITM on ITM.ItemTypeID=SD.EquipmentID where cast(SM.RequestDate as date) between cast(coalesce(@FromDate,SM.RequestDate) as date) and cast(coalesce(@Todate,SM.RequestDate) as date) 
					and ((@RequestBy IS NULL OR @RequestBy='') OR SM.RequestBy = @RequestBy) and SM.RequestID=coalesce(@RequestID,SM.RequestID)
					--and ((@CheckUser is Null) or (D.CustomerName = @lastname))
					and SM.OrganizationID=@OrganizationID  order by SM.RequestID desc 
				end
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveorupdateSystemConfiguration]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_SaveorupdateSystemConfiguration]
	-- Add the parameters for the stored procedure here
	@tag char(1),
	@SysconfigID bigint=null,
	@CustomerID bigint=null,
	@BoxID varchar(100)=null,
	@ItemDetailsXML XML =NULL, 
	@bigUserID bigint=null,
	@bigOrganizationId bigint=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @ErrorMessage varchar(3000)  
	DECLARE @docHandle int   
	DECLARE  @tblItemDetailsXML TABLE (RowIndex bigint,MachineName varchar(150),MachineVolume decimal(18,2)) 
	EXEC sp_xml_preparedocument @docHandle OUTPUT, @ItemDetailsXML                                         
					INSERT INTO @tblItemDetailsXML                                                      
					  SELECT * FROM OPENXML(@docHandle, '/DocumentElement/ItemDetails')               
					  WITH                 
					  (
					  RowIndex bigint 'RowIndex',
					  MachineName varchar(150) 'MachineName'
					  ,MachineVolume decimal(18,2) 'MachineVolume'
					  )      


    -- Insert statements for procedure here
	if(@tag='I')
		begin
			declare @LastSysconfiguID bigint
			insert into rvlfSystemConfigMaster (CustomerID,BoxID,OrganizationID,CreatedBy,CreatedDate,isDelete) values (@CustomerID,@BoxID,@bigOrganizationId,@bigUserID,getdate(),0)
			SET @LastSysconfiguID = IDENT_CURRENT('rvlfSystemConfigMaster')
			insert into rvlfSystemConfigDetails 
			select @LastSysconfiguID,MachineName,MachineVolume,RowIndex  from @tblItemDetailsXML
		end
	else if(@tag='U')
		begin
			update rvlfSystemConfigMaster set CustomerID=@CustomerID,BoxID=@BoxID,OrganizationID=@bigOrganizationId,ModifyBy=@bigUserID,ModifyDate=getdate() where SysConfigID=@SysconfigID
			delete from rvlfSystemConfigDetails where SysConfigID=@SysconfigID
			insert into rvlfSystemConfigDetails 
			select @SysconfigID,MachineName,MachineVolume,RowIndex  from @tblItemDetailsXML
		end
	else if(@tag='D')
		begin
			update rvlfSystemConfigMaster set isDelete=1,ModifyBy=@bigUserID,ModifyDate=getdate() where SysConfigID=@SysconfigID
		end
	else if(@tag='S')
		begin
			select C.CustomerName,SM.BoxID,SM.CustomerID,D.EquipmentName,SM.SysConfigID,ISNULL(STUFF((SELECT ', ' + 'Machine Name: ' + MachineName + ' Machine Volume: ' + cast(MachineVolume as varchar)
			FROM dbo.rvlfSystemConfigDetails SCD
			WHERE SCD.SysConfigID = SM.SysConfigID
			FOR XML PATH('')
			), 1, 1, ''), 'Not Assigned') AS ItemList from rvlfSystemConfigMaster SM inner join rvlfCustomers C on c.CustomerId=SM.CustomerID inner join rvlfMAKDevices D on D.BoxId=SM.BoxID
			where 
			((@BoxId IS NULL OR @BoxId='') OR SM.BoxId = @BoxId)
			and ((@SysconfigID IS NULL OR @SysconfigID='') OR SM.SysConfigID = @SysconfigID)
			and ((@CustomerID IS NULL OR @CustomerID='') OR SM.CustomerID = @CustomerID)
			and ((@bigOrganizationId IS NULL OR @bigOrganizationId='') OR SM.OrganizationID = @bigOrganizationId) and SM.isDelete=0

			select MachineName,MachineVolume from rvlfSystemConfigDetails where ((@SysconfigID IS NULL OR @SysconfigID='') OR SysConfigID = @SysconfigID)

		end
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SavePackage]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SavePackage]
	@bigPackageId bigint = null,
	@vcPackageName varchar(50),
	@vcPackageDesc varchar(250) = NULL,
	@vcModuleIDs varchar(500),
	@vcOperationIDs varchar(1000),
	@bigCreatedBy bigint,
	@dtCreatedDateTime datetime
AS
/**************************************************************************************/
--	Name		:	rvlf_sp_SavePackage
--	Description	:	To save the package and assigning the modules and operations to it
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	26-Nov-2009		Created Intial Version 
/**************************************************************************************/
BEGIN
SET NOCOUNT ON 
  IF @bigPackageId IS NULL
	BEGIN
		-- Insert the Package Information
		INSERT INTO rvlfPackage (PackageName, PackageDesc, CreatedBy, CreatedDateTime) VALUES 
				(@vcPackageName, @vcPackageDesc, @bigCreatedBy, @dtCreatedDateTime)
		
		SET @bigPackageId = @@IDENTITY
	END
  ELSE
	BEGIN
		UPDATE rvlfPackage SET PackageName = @vcPackageName, PackageDesc = @vcPackageDesc,
			ModifiedBy = @bigCreatedBy, ModifiedDateTime = @dtCreatedDateTime WHERE PackageId = @bigPackageId
		
		DELETE FROM rvlfPackageOperations WHERE PackageId = @bigPackageId
	END
	
	    IF CHARINDEX('175', @vcOperationIDs, 1) > 0 OR CHARINDEX('177', @vcOperationIDs, 1) > 0 OR CHARINDEX('178', @vcOperationIDs, 1) > 0
	    BEGIN
	       SET @vcOperationIDs = @vcOperationIDs + ',144'
	    END
	
			-- Insert the Operations for the Packages
		INSERT INTO rvlfPackageOperations(PackageId, ModuleID, OperationID) 
				 (SELECT @bigPackageId, OT.ModuleID, OT.OperationTypeId FROM rvlfOperationType OT
				  WHERE OT.OperationTypeId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcOperationIDs,','))
				 )
		
		-- Insert the Modules for the Packages
		INSERT INTO rvlfPackageOperations(PackageId, ModuleID, OperationID) 
			 (SELECT @bigPackageId, ModuleID, NULL AS OperationID FROM rvlfModule
				  WHERE ModuleID IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcModuleIDs,','))
			 )
			 --print 1
			 --SELECT distinct ParentModuleId FROM rvlfModule 
				--	WHERE ModuleID IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcModuleIDs,','))
		INSERT INTO rvlfPackageOperations (ModuleID,PackageId, OperationID)	 
			SELECT distinct ParentModuleId , @bigPackageId, null FROM rvlfModule 
				WHERE ModuleID IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcModuleIDs,','))
				AND ParentModuleId IS NOT NULL
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveReportingIntDur_Live]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveReportingIntDur_Live]
@nSno INT = NULL,
@nVal INT = NULL,
@nOrgId INT = NULL,
@nUserId INT = NULL,
@nOperation INT = NULL,
@bIsRptInt BIT = 0
AS
/*************************************************************************************      
Procedure Name		: rvlf_sp_SaveReportingIntDur_Live NULL,6,6,94,1,0
Purpose				: Save Reporting interval & duration for live tracking
Created by			: Sakthi Gopinath S
Created date		: 2016-08-12
**************************************************************************************/    
BEGIN
SET NOCOUNT ON
	DECLARE @OperationId TINYINT = 1
	IF @bIsRptInt = 1
	BEGIN
		IF @nOperation = 1
		BEGIN
			IF EXISTS(SELECT 1 FROM rvlfRptInterval_LT WHERE OrgId=@nOrgId AND CreatedBy=@nUserId AND IntInMeter=@nVal)
			BEGIN
				SET @OperationId = 0
				RAISERROR('Given reporting interval is already exist',1,16)
			END
			ELSE
			BEGIN
				INSERT INTO rvlfRptInterval_LT(IntInMeter,OrgId,IsDefault,CreatedBy,CreatedDate,IsDelete) VALUES
				(@nVal,@nOrgId,0,@nUserId,GETUTCDATE(),0)
			END
		END
		ELSE IF @nOperation = 2
		BEGIN
			Update rvlfRptInterval_LT SET IntInMeter=@nVal,ModifiedBy=@nUserId,ModifiedDate=GETUTCDATE() WHERE Sno=@nSno
		END
		ELSE IF @nOperation = 3
		BEGIN
			Update rvlfRptInterval_LT SET IsDelete=1,ModifiedBy=@nUserId,ModifiedDate=GETUTCDATE() WHERE Sno=@nSno
		END
	END
	ELSE
	BEGIN
		IF @nOperation = 1
		BEGIN
			IF EXISTS(SELECT 1 FROM rvlfRptDuration_LT WHERE OrgId=@nOrgId AND CreatedBy=@nUserId AND IntInMin=@nVal)
			BEGIN
				SET @OperationId = 0
				RAISERROR('Given reporting duration is already exist',1,16)
				RETURN;
			END
			ELSE
			BEGIN
				INSERT INTO rvlfRptDuration_LT(IntInMin,IntInSec,OrgId,IsDefault,CreatedBy,CreatedDate,IsDelete) VALUES
				(@nVal,(@nVal*60),@nOrgId,0,@nUserId,GETUTCDATE(),0)
			END
		END
		ELSE IF @nOperation = 2
		BEGIN
			Update rvlfRptDuration_LT SET IntInMin=@nVal,IntInSec=(@nVal*60),ModifiedBy=@nUserId,ModifiedDate=GETUTCDATE() WHERE Sno=@nSno
		END
		ELSE IF @nOperation = 3
		BEGIN
			Update rvlfRptDuration_LT SET IsDelete=1,ModifiedBy=@nUserId,ModifiedDate=GETUTCDATE() WHERE Sno=@nSno
		END
	END
	SELECT @OperationId AS [Status]
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveROICost]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_SaveROICost]
@CostId tinyint = null,
@CostTypeId tinyint = null,
@CostName varchar(30) = null,
@CostDesc varchar(150) = null,
@isBitDelete bit = 0,
@bigOrganizationID bigint = null,
@bigQueryingUser bigint = 0
AS
/********************************************************************************************  
Stored Procedure Name : rvlf_sp_SaveROICost  
Purpose       : Insert / Update the ROI cost
Created by    : S. Sakthi Gopinath
Created date  : 15-Jul-13
*********************************************************************************************/    
BEGIN
IF (@CostId > 0 AND @isBitDelete=0)  
BEGIN  
   UPDATE rvlfROICost SET CostDesc=@CostDesc,CostName=@CostName,CostType=@CostTypeId,CreatedBy=@bigQueryingUser
   WHERE Id=@CostId AND (@bigOrganizationID IS NULL OR @bigOrganizationID = 0 AND OrgId=@bigOrganizationID)
END  
ELSE IF (@CostId > 0 AND @isBitDelete=1)  
BEGIN  
   Update rvlfROICost SET IsDelete=1 WHERE Id=@CostId            
END  
ELSE  
 BEGIN  
   INSERT INTO rvlfROICost(CostName,CostDesc,CreatedBy,CreatedDate,CostType,OrgId)  
   VALUES(@CostName,@CostDesc,@bigQueryingUser,GETUTCDATE(),@CostTypeId,@bigOrganizationID)  
 END  
END




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveScheduledVehicleReq]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[rvlf_sp_SaveScheduledVehicleReq]
	@bigRequisitionId bigint=null,
	@bigEmployeeId bigint=null,
	@dtRequisitionDate datetime=null,
	@vcFromAddress varchar(200)=null,
	@vcToAddress varchar(200)=null,
	@intDistanceKM int=null,
	@vcRequisitionService varchar(7)=null,
	@dtRequisitionFromDate datetime=null,
	@dtRequisitionToDate datetime=null,
	@vcPurpose varchar(100)=null,
	@vcComments varchar(200)=null,
	@cApproval char(1)=null,
	@vcClosedComments varchar(200)=null,
	
	
	@dtMondayShiftIn time=null,
	@dtMondayShiftOut time=null,
	@dtTuesdayShiftIn time=null,
	@dtTuesdayShiftOut time=null,
	@dtWednesdayShiftIn time=null,
	@dtWednesdayShiftOut time=null,
	@dtThursdayShiftIn time=null,
	@dtThursdayShiftOut time=null,
	@dtFridayShiftIn time=null,
	@dtFridayShiftOut time=null,
	@dtSaturdayShiftIn time=null,
	@dtSaturdayShiftOut time=null,
	@dtSundayShiftIn time=null,
	@dtSundayShiftOut time=null,
	
	@nuLatitude numeric(10,6)=null,
	@nuLongitude numeric(10,6)=null
	
	
AS
/******************************************************************************/
--	Name		:	rvlf_sp_SaveScheduledVehicleReq
--	Description	:	To insert/update scheduled vehicle requisition details.
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	09-Dec-2009	VN	Created Intial Version 
/******************************************************************************/

BEGIN
	
			DECLARE @vcDayName varchar(10)
			
				IF EXISTS(SELECT RequisitionId FROM rvlfScheduledVehicleRequisition 
								WHERE EmployeeId=@bigEmployeeId 
									AND Closed=0 
									--AND RequisitionService=@vcRequisitionService
									AND(RequisitionFromDate BETWEEN @dtRequisitionFromDate AND @dtRequisitionToDate))									
					BEGIN
						UPDATE rvlfScheduledVehicleRequisition  SET Closed=1,DateOfClosed=GETDATE(),ClosedComments='New Request'
							WHERE EmployeeId=@bigEmployeeId 
									AND Closed=0 
									--AND RequisitionService=@vcRequisitionService
									AND(RequisitionFromDate BETWEEN @dtRequisitionFromDate AND @dtRequisitionToDate)
					END
				ELSE IF EXISTS(SELECT RequisitionId FROM rvlfScheduledVehicleRequisition 
								WHERE EmployeeId=@bigEmployeeId 
									AND Closed=0 
									--AND RequisitionService=@vcRequisitionService
									AND(RequisitionToDate BETWEEN @dtRequisitionFromDate AND @dtRequisitionToDate))							
					BEGIN
						UPDATE rvlfScheduledVehicleRequisition  SET Closed=1,DateOfClosed=GETDATE(),ClosedComments='New Request'
							WHERE EmployeeId=@bigEmployeeId 
									AND Closed=0 
									--AND RequisitionService=@vcRequisitionService
									AND(RequisitionToDate BETWEEN @dtRequisitionFromDate AND @dtRequisitionToDate)
					END
				ELSE IF EXISTS(SELECT RequisitionId FROM rvlfScheduledVehicleRequisition 
								WHERE EmployeeId=@bigEmployeeId 
									AND Closed=0 
									--AND RequisitionService=@vcRequisitionService
									AND(RequisitionFromDate >@dtRequisitionFromDate AND RequisitionToDate<@dtRequisitionToDate))
					BEGIN
						UPDATE rvlfScheduledVehicleRequisition  SET Closed=1,DateOfClosed=GETDATE(),ClosedComments='New Request'
							WHERE EmployeeId=@bigEmployeeId 
									AND Closed=0 
									--AND RequisitionService=@vcRequisitionService
									AND(RequisitionFromDate >@dtRequisitionFromDate AND RequisitionToDate<@dtRequisitionToDate)
					END
						INSERT INTO rvlfScheduledVehicleRequisition(EmployeeId,RequisitionDate,FromAddress,ToAddress,
									DistanceKM,RequisitionService,RequisitionFromDate,RequisitionToDate,Purpose,Comments,Approval,Closed,Latitude,Longitude)
							   VALUES(@bigEmployeeId,@dtRequisitionDate,@vcFromAddress,@vcToAddress,@intDistanceKM,@vcRequisitionService,
									  @dtRequisitionFromDate,@dtRequisitionToDate,@vcPurpose,@vcComments,@cApproval,0,@nuLatitude,@nuLongitude)  
									  
					WHILE @dtRequisitionFromDate <=@dtRequisitionToDate 
						
						BEGIN
														
							SET @vcDayName=(SELECT DATENAME(DW,@dtRequisitionFromDate) AS Name)
							
								IF(@vcDayName='Monday')
									BEGIN
										IF(@dtMondayShiftIn!='00:00:00' AND @dtMondayShiftOut!='00:00:00')
											BEGIN
												IF EXISTS(SELECT ShiftDate FROM rvlfEmployeeShifts WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate)
													BEGIN																											
														UPDATE rvlfEmployeeShifts SET ShiftIn=@dtMondayShiftIn,ShiftOut=@dtMondayShiftOut,Leave=0,Tracking='Update,' 
															WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate AND ShiftDay=@vcDayName  
													END
												ELSE
													BEGIN
														INSERT INTO rvlfEmployeeShifts(EmployeeId,ShiftDate,ShiftDay,ShiftIn,ShiftOut,Leave,Tracking)
															VALUES(@bigEmployeeId,@dtRequisitionFromDate,@vcDayName,@dtMondayShiftIn,@dtMondayShiftOut,0,'Update,')
													END	
											END		
									END
								
								IF(@vcDayName='Tuesday')
									BEGIN
										IF(@dtTuesdayShiftIn!='00:00:00' AND @dtTuesdayShiftOut!='00:00:00')
											BEGIN
												IF EXISTS(SELECT ShiftDate FROM rvlfEmployeeShifts WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate)
													BEGIN														
														UPDATE rvlfEmployeeShifts SET ShiftIn=@dtTuesdayShiftIn,ShiftOut=@dtTuesdayShiftOut,Leave=0,Tracking='Update,'  
															WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate AND ShiftDay=@vcDayName  
													END
												ELSE
													BEGIN
														INSERT INTO rvlfEmployeeShifts(EmployeeId,ShiftDate,ShiftDay,ShiftIn,ShiftOut,Leave,Tracking)
															VALUES(@bigEmployeeId,@dtRequisitionFromDate,@vcDayName,@dtTuesdayShiftIn,@dtTuesdayShiftOut,0,'Update,')
													END
											END
									END
								
								IF(@vcDayName='Wednesday')
									BEGIN
										IF(@dtWednesdayShiftIn!='00:00:00' AND @dtWednesdayShiftOut!='00:00:00')
											BEGIN
												IF EXISTS(SELECT ShiftDate FROM rvlfEmployeeShifts WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate)
													BEGIN												
														UPDATE rvlfEmployeeShifts SET ShiftIn=@dtWednesdayShiftIn,ShiftOut=@dtWednesdayShiftOut,Leave=0,Tracking='Update,'  
															WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate AND ShiftDay=@vcDayName  
													END
												ELSE
													BEGIN
														INSERT INTO rvlfEmployeeShifts(EmployeeId,ShiftDate,ShiftDay,ShiftIn,ShiftOut,Leave,Tracking)
															VALUES(@bigEmployeeId,@dtRequisitionFromDate,@vcDayName,@dtWednesdayShiftIn,@dtWednesdayShiftOut,0,'Update,')
													END
											END
									END
									
								IF(@vcDayName='Thursday')
									BEGIN
										IF(@dtTuesdayShiftIn!='00:00:00' AND @dtTuesdayShiftOut!='00:00:00')
											BEGIN
												IF EXISTS(SELECT ShiftDate FROM rvlfEmployeeShifts WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate)
													BEGIN														
														UPDATE rvlfEmployeeShifts SET ShiftIn=@dtTuesdayShiftIn,ShiftOut=@dtTuesdayShiftOut,Leave=0,Tracking='Update,'  
															WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate AND ShiftDay=@vcDayName  
													END
												ELSE
													BEGIN
														INSERT INTO rvlfEmployeeShifts(EmployeeId,ShiftDate,ShiftDay,ShiftIn,ShiftOut,Leave,Tracking)
															VALUES(@bigEmployeeId,@dtRequisitionFromDate,@vcDayName,@dtThursdayShiftIn,@dtThursdayShiftOut,0,'Update,')
													END
											END
									END
									
								IF(@vcDayName='Friday')
									BEGIN
										IF(@dtFridayShiftIn!='00:00:00' AND @dtFridayShiftOut!='00:00:00')
											BEGIN
												IF EXISTS(SELECT ShiftDate FROM rvlfEmployeeShifts WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate)
													BEGIN														
														UPDATE rvlfEmployeeShifts SET ShiftIn=@dtFridayShiftIn,ShiftOut=@dtFridayShiftOut,Leave=0,Tracking='Update,'  
															WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate AND ShiftDay=@vcDayName  
													END
												ELSE
													BEGIN
														INSERT INTO rvlfEmployeeShifts(EmployeeId,ShiftDate,ShiftDay,ShiftIn,ShiftOut,Leave,Tracking)
															VALUES(@bigEmployeeId,@dtRequisitionFromDate,@vcDayName,@dtFridayShiftIn,@dtFridayShiftOut,0,'Update,')
													END
											END
									END
									
								IF(@vcDayName='Saturday')
									BEGIN
										IF(@dtSaturdayShiftIn!='00:00:00' AND @dtSaturdayShiftOut!='00:00:00')
											BEGIN
												IF EXISTS(SELECT ShiftDate FROM rvlfEmployeeShifts WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate)
													BEGIN											
														UPDATE rvlfEmployeeShifts SET ShiftIn=@dtSaturdayShiftIn,ShiftOut=@dtSaturdayShiftOut,Leave=0,Tracking='Update,'  
															WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate AND ShiftDay=@vcDayName  
													END
												ELSE
													BEGIN
														INSERT INTO rvlfEmployeeShifts(EmployeeId,ShiftDate,ShiftDay,ShiftIn,ShiftOut,Leave,Tracking)
															VALUES(@bigEmployeeId,@dtRequisitionFromDate,@vcDayName,@dtSaturdayShiftIn,@dtSaturdayShiftOut,0,'Update,')
													END
											END
									END
									
								IF(@vcDayName='Sunday')
									BEGIN
										IF(@dtSundayShiftIn!='00:00:00' AND @dtSundayShiftOut!='00:00:00')
											BEGIN
												IF EXISTS(SELECT ShiftDate FROM rvlfEmployeeShifts WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate)
													BEGIN													
														UPDATE rvlfEmployeeShifts SET ShiftIn=@dtSundayShiftIn,ShiftOut=@dtSundayShiftOut,Leave=0,Tracking='Update,'  
															WHERE EmployeeId=@bigEmployeeId AND ShiftDate=@dtRequisitionFromDate AND ShiftDay=@vcDayName  
													END
												ELSE
													BEGIN
														INSERT INTO rvlfEmployeeShifts(EmployeeId,ShiftDate,ShiftDay,ShiftIn,ShiftOut,Leave,Tracking)
															VALUES(@bigEmployeeId,@dtRequisitionFromDate,@vcDayName,@dtSundayShiftIn,@dtSundayShiftOut,0,'Update,')
													END
											END
									END	 
									
							SET @dtRequisitionFromDate =DATEADD(D,1,@dtRequisitionFromDate)
							
						END
		
	
		

END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveScheduleReportsSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

    
CREATE Procedure [dbo].[rvlf_sp_SaveScheduleReportsSettings]    
    
    
 @bigReportScheduleId bigint = NULL,    
 @bigOrganizationID bigint,    
 @bigReportTypesId bigint,    
 @bigFleetId bigint,    
 @bigVehicleId VARCHAR(500) = NULL,    
 @dtEffectiveFrom datetime,    
 @dtEffectiveTo datetime = NULL,    
 @dtReportFrom datetime,    
 @dtReportTo datetime,    
 @dtGenerateReportOn datetime,    
 @dtReportStartDate datetime,    
 @dtReportEndDate datetime,    
 @bitIsSummaryVisible bit = 0,    
 @bitIsDetailsVisible bit = 0,    
 @vcShowHideOptions varchar(1000) = NULL,    
 @vcReportParameters varchar(1000) = NULL,    
 @vcSortBy varchar(30),    
 @intSortDirection tinyint = 0,    
 @intFileExtension tinyint = 0,    
 @intFrequency tinyint = 0,    
 @dtNextGenerationDateTime datetime,    
 @dtCreatedDateTime datetime,    
 @bigCreatedBy bigint,    
 @ModifiedDateTime datetime = NULL,    
 @bigModifiedBy bigint = NULL,    
 @tiWeekDayFrom tinyint =  NULL,    
 @tiWeekDayTo tinyint =  NULL,    
 @tiWeekDayOn tinyint =  NULL,    
 @tiDayOfMonth tinyint =  NULL,    
 --@tblNotificationsList as NotificaitonUserList READONLY,    
 @tblNotificationsList XML = null,    
 @bitIsScheduled bit =NULL    
AS    
    
/******************************************************************************/    
-- Name  : rvlf_sp_SaveScheduleReportsSettings    
-- Description : To insert / update the Schedule Reports Settings    
-- Author  : Kumuthini. L    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>>   Initial Reason    
--    : 02-Mar-2010 Kumuthini Created Intial Version     
--    : 13-Mar-2010 MJJC  Set the Can generate to true.    
--    : 19-Mar-2010 MJJC  Handled the exceptions properly and started the transactions    
--    : 07-JAN-2011 VN   Included the isscheduled functionlities.    
/******************************************************************************/    
BEGIN    
 SET NOCOUNT ON     
  /****************************Reading XML File and Store into Temp table**************/       
   DECLARE @vcError varchar(max)  
   DECLARE @docHandle int         
   DECLARE  @temptable TABLE (UserID Bigint,Email bit,SMS bit)            
    IF @tblNotificationsList IS NOT NULL       
  BEGIN                      
   EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblNotificationsList                               
  INSERT INTO @tempTable                                            
   SELECT * FROM OPENXML(@docHandle, '/DocumentElement/Notification')     
   WITH       
   (               
  UserID bigint 'UserID'                
  ,Email  bit  'Email'                                          
  ,SMS bit  'SMS'      
   )            
 END      
 declare @tblNotificationsListTmp As NotificaitonUserList     
 insert into  @tblNotificationsListTmp    
 select * from @temptable       
 /**************************************************************************************/    
                    
  BEGIN TRY    
   BEGIN TRANSACTION ScheduleReport  
   if(@bigVehicleId='0,')
   set @bigVehicleId='0'  
    --Checks whether to insert or update by checking the Report Schedule ID    
   IF @bigReportScheduleId IS NOT NULL AND @bigReportScheduleId > 0    
    BEGIN    
     -- Checks whether the Report Schedule exists    
     IF EXISTS(SELECT ReportScheduleId FROM rvlfSchedulingReport WHERE ReportScheduleId = @bigReportScheduleId)    
      BEGIN 
      if not exists(select * from rvlfNotificationList where NotificationType=5 and TypeID in (select ReportScheduleId from rvlfSchedulingReport where         
        ReportTypesId = @bigReportTypesId and FleetId = @bigFleetId and VehicleId = @bigVehicleId and EffectiveFrom = @dtEffectiveFrom and EffectiveTo = @dtEffectiveTo and        
        ReportFrom = @dtReportFrom and ReportTo = @dtReportTo and WeekDayFrom = @tiWeekDayFrom and WeekDayTo = @tiWeekDayTo and WeekDayOn = @tiWeekDayOn and        
        DayOfMonth = @tiDayOfMonth and Frequency = @intFrequency and IsDeleted <>1 and ReportScheduleId <> @bigReportScheduleId and OrganizationId=@bigOrganizationID) and   
        UserID in (SELECT x.d.value('UserID[1]','bigint') AS UserID FROM @tblNotificationsList.nodes('/DocumentElement/Notification') x(d)) )         
   BEGIN     
       UPDATE rvlfSchedulingReport SET    
        ReportTypesId = @bigReportTypesId,    
        FleetId = @bigFleetId,    
        VehicleId = @bigVehicleId,    
        EffectiveFrom = @dtEffectiveFrom,    
        EffectiveTo = @dtEffectiveTo,    
        ReportFrom = @dtReportFrom,    
        ReportTo = @dtReportTo,    
        WeekDayFrom = @tiWeekDayFrom,    
        WeekDayTo = @tiWeekDayTo,    
        WeekDayOn = @tiWeekDayOn,    
        DayOfMonth = @tiDayOfMonth,    
        GenerateReportOn = @dtGenerateReportOn,    
        ReportStartDate = @dtReportStartDate,     
        ReportEndDate = @dtReportEndDate,    
        IsSummaryVisible = @bitIsSummaryVisible,    
        IsDetailsVisible = @bitIsDetailsVisible,    
ShowHideOptions = @vcShowHideOptions,    
        ReportParameters = @vcReportParameters,    
        SortBy = @vcSortBy,    
        SortDirection = @intSortDirection,    
        FileExtension = @intFileExtension,    
        Frequency = @intFrequency,    
        NextGenerationDateTime = @dtNextGenerationDateTime,    
        ModifiedDateTime = @ModifiedDateTime,    
        ModifiedBy = @bigModifiedBy,    
        CanGenerate = 1    
       WHERE ReportScheduleId = @bigReportScheduleId    
           
       DELETE FROM rvlfNotificationList WHERE NotificationType = 5 AND TypeID = @bigReportScheduleId    
                    
                EXEC rvlf_sp_Save_notificationsList @tblNotificationsListTmp, 5 , @bigReportScheduleId    
                    
               --COMMIT       
          END      
          else      
             raiserror('The schedule you have created already exists!',16,1);       
      END            
    END  
  ELSE if not exists(select * from rvlfNotificationList where NotificationType=5 and TypeID in (select ReportScheduleId from rvlfSchedulingReport where         
    ReportTypesId = @bigReportTypesId and FleetId = @bigFleetId and VehicleId = @bigVehicleId and EffectiveFrom = @dtEffectiveFrom and EffectiveTo = @dtEffectiveTo and        
        ReportFrom = @dtReportFrom and ReportTo = @dtReportTo and WeekDayFrom = @tiWeekDayFrom and WeekDayTo = @tiWeekDayTo and WeekDayOn = @tiWeekDayOn and        
        DayOfMonth = @tiDayOfMonth and Frequency = @intFrequency and IsDeleted <>1 and OrganizationId=@bigOrganizationID) and   
        UserID in (SELECT x.d.value('UserID[1]','bigint') AS UserID FROM @tblNotificationsList.nodes('/DocumentElement/Notification') x(d))                        
    )   
    BEGIN    
    --print 2    
      --Inserts the new scheduling reports settings    
     INSERT INTO rvlfSchedulingReport     
      (     
       OrganizationId, ReportTypesId, FleetId, VehicleId, EffectiveFrom,     
       EffectiveTo, ReportFrom, ReportTo,    
       GenerateReportOn, ReportStartDate,     
       ReportEndDate, IsSummaryVisible,     
       IsDetailsVisible, ShowHideOptions, ReportParameters, SortBy, SortDirection, FileExtension, Frequency,    
       IsLocked, LockedDateTime, NextGenerationDateTime, CanGenerate,     
       CreatedDateTime, CreatedBy, ModifiedDateTime,    
       ModifiedBy, IsDeleted, WeekDayFrom, WeekDayTo, WeekDayOn,    
        DayOfMonth,IsScheduled    
      )    
     VALUES    
      (     
          @bigOrganizationID, @bigReportTypesId, @bigFleetId, @bigVehicleId, @dtEffectiveFrom,    
                         @dtEffectiveTo, @dtReportFrom, @dtReportTo,    
                          @dtGenerateReportOn, @dtReportStartDate,    
                         @dtReportEndDate, @bitIsSummaryVisible,     
                         @bitIsDetailsVisible, @vcShowHideOptions,    
          @vcReportParameters, @vcSortBy, @intSortDirection, @intFileExtension, @intFrequency,    
       0, NULL, @dtNextGenerationDateTime, 1,    
       @dtCreatedDateTime, @bigCreatedBy, @ModifiedDateTime, @bigModifiedBy, 0, @tiWeekDayFrom,    
          @tiWeekDayTo, @tiWeekDayOn,     
          @tiDayOfMonth,@bitIsScheduled    
      )    
     -- print 1    
        SET @bigReportScheduleId = @@IDENTITY    
            
           EXEC rvlf_sp_Save_notificationsList @tblNotificationsListTmp, 5 , @bigReportScheduleId    
           --COMMIT    
       END
       ELSE      
       BEGIN      
   --Select 0         
   raiserror('The schedule you have created already exists!',16,1);      
       END      
       Commit      
  END TRY    
  BEGIN CATCH    
   ROLLBACK    
   --DECLARE @vcError varchar(max) = 'Error in saving the Scheduling Reports Settings. Try Again !'    
    set @vcError = case when (select ERROR_MESSAGE())='The schedule you have created already exists!' then (select ERROR_MESSAGE())      
   else 'Error in saving the Scheduling Reports Settings. Try Again !' end            
   
   raiserror(@vcError,16,1);    
  END CATCH    
     
 SET NOCOUNT OFF    
END 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveSeverityTemplate]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveSeverityTemplate]
(  
	@vcSeverityTemplateName nvarchar(50)=Null,
	@vcSensorIds varchar(Max) = null,
	@vcOutputIds varchar(Max) = null
)

AS

/********************************************************************************************/
--	Name		:	rvlf_sp_SaveSeverityTemplate
--	Description	:	To Add and Edit the Box Details
--	Author		:	S.Jeyanthi
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	23-Oct-2010		Created Intial Version 
/********************************************************************************************/

BEGIN
SET NOCOUNT ON    	   
	 
	  INSERT INTO rvlfSeverityTemplate(SeverityTempName, SensorIds, OutputIds)
	  VALUES(@vcSeverityTemplateName, @vcSensorIds,@vcOutputIds)				
					
  SET NOCOUNT OFF	

END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveTimeBasedGeozone]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================        
-- Author:  Vijay.N        
-- Create date: 20-Apr-2012        
-- Description: Initial Version         
--    : Vijay.N - To Save the Time based Geozone ID        
-- rvlf_sp_SaveTimeBasedGeozone 999983,'13,21',null,null,null,null,null,null,null,1,0,NULL    
-- =============================================        
CREATE PROCEDURE [dbo].[rvlf_sp_SaveTimeBasedGeozone]        
 -- Add the parameters for the stored procedure here        
 --@VehicleId BIGINT,        
 @BoxId BIGINT,        
 @GeozoneId Varchar(500),    
 --@IsReccurence BIT,        
 @FromDate DATETIME = NULL,        
 @Todate DATETIME = NULL,        
 @FromTime VARCHAR(5) = NULL,        
 @ToTime VARCHAR(5) = NULL,        
 @FromTime1 VARCHAR(5) = NULL,        
 @ToTime1 VARCHAR(5) = NULL,        
 @FromTime2 VARCHAR(5) = NULL,        
 @ToTime2 VARCHAR(5) = NULL,        
 @RecurrenceDays VARCHAR(15) = NULL,        
 @IsFromGeozoneVehicle BIT = 1,        
 @IsAssign BIT = 1,    
 @IsGeozoneVehicle BIT = NULL        
         
AS        
BEGIN        
 -- SET NOCOUNT ON added to prevent extra result sets from        
 -- interfering with SELECT statements.        
 SET NOCOUNT ON;        
        
    -- Insert statements for procedure here        
    DECLARE @geoId BIGINT = 0    
            
IF (@IsAssign = 1)        
BEGIN        
        
  IF (@IsGeozoneVehicle IS NOT NULL)    
  BEGIN    
   SELECT @geoId = GeozoneId from rvlfOrganizationGeozone where GeozoneNo IN (SELECT * FROM DBO.rvlf_fn_ConvertArrayToTable(@GeozoneId,','))    
  END    
  ELSE    
  BEGIN    
   SET @geoId = CAST(@GeozoneId AS BIGINT)    
  END        
	IF EXISTS(SELECT * FROM DBO.rvlfTimeBasedGeozone WHERE BoxId = @BoxId AND GeozoneId = @geoId)
	BEGIN 
		DELETE FROM DBO.rvlfTimeBasedGeozone WHERE BoxId = @BoxId AND GeozoneId = @geoId
	END
        
  INSERT INTO DBO.rvlfTimeBasedGeozone (BoxId,GeozoneId,FromDate,Todate,FromTime,ToTime,FromTime1,ToTime1,FromTime2,ToTime2, RecurrenceDays)        
  VALUES(@BoxId,@geoId,@FromDate,@Todate,@FromTime,@ToTime,@FromTime1,@ToTime1,@FromTime2,@ToTime2,@RecurrenceDays)                  
 END        
 ELSE        
 BEGIN        
     
 IF (@IsGeozoneVehicle IS NOT NULL)    
  BEGIN    
   SELECT @geoId= GeozoneId from rvlfOrganizationGeozone where GeozoneNo IN (SELECT * FROM DBO.rvlf_fn_ConvertArrayToTable(@GeozoneId,','))    
       
   DELETE rvlfTimeBasedGeozone WHERE  BoxId = @BoxId AND GeozoneId = @geoId    
  END    
  ELSE    
  BEGIN     
   DELETE rvlfTimeBasedGeozone WHERE  BoxId = @BoxId AND GeozoneId IN (SELECT * FROM DBO.rvlf_fn_ConvertArrayToTable(@GeozoneId,','))    
   --SET @GeozoneId = CAST(@GeozoneId AS BIGINT)    
  END    
      
 END        
         
 SET NOCOUNT OFF;         
END     


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveTripSheet]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[rvlf_sp_SaveTripSheet]
	@dtTripDateTime datetime=null,
	@bigGeneratedBy bigint=null,
	@sintNoOfEmployees int=null,
	@vcTripType varchar(7)=null,
	@dtTripGeneratedDate datetime=null	
	

AS
/******************************************************************************/
--	Name		:	rvlf_sp_SaveTripSheet
--	Description	:	To save the trip sheet generation details.
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	04-Jan-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN
	
	INSERT INTO rvlfTripSheetGeneration(TripDate,TripGeneratedBy,NoEmpTravelled,TripType,TripGeneratedDate)
		VALUES(@dtTripDateTime,@bigGeneratedBy,@sintNoOfEmployees,@vcTripType,@dtTripGeneratedDate)
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveTyreMakeSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_SaveTyreMakeSettings]
	@CarId bigint=null,
	@MakeId bigint=null,
	@CarMakeName varchar(50)=null, 
	@bigOrganizationID int = null,
	@Benefits varchar(100) = null
	
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_SaveTyreMakeSettings]
--	Description	:	To save the Car Make setting details
--	Author		:	Kapil
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	05-Mar-2014	Created Intial Version 
/******************************************************************************/
BEGIN
		
	IF(@CarId >0)
		BEGIN
			UPDATE rvlfTyreMake SET BrandName=@CarMakeName,Benefits = @Benefits
			WHERE BrandID=@MakeId and OrganizationId = @bigOrganizationID		
		END
	ELSE
		BEGIN
			INSERT INTO rvlfTyreMake(BrandName,OrganizationId,Benefits)
				VALUES(@CarMakeName,@bigOrganizationID,@Benefits)
		END
		
    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveTyreModelSettings]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_SaveTyreModelSettings]  
 @CarId bigint=null,  
 @ModelId bigint=null,  
 @CarModelName varchar(50)=null,  
 @MakeId int=null,  
 @bigVehicleId bigint=null,  
 @Size varchar(50)=null,
 @Width varchar(50)=null,
 @Remarks Varchar(50)=null
   
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_SaveTyreModelSettings]  
-- Description : To save the Car Model setting details  
-- Author  :kapil.k
-- Company : Angler Technologies  
-- History : <<Date(dd-MON-yyyy)>> Initial Reason  
--         : 05-Mar-2014 Created Intial Version   

/******************************************************************************/  
BEGIN  
    
 IF(@CarId >0)  
  BEGIN  
   UPDATE rvlfTyreModel SET ModelName=@CarModelName,BrandID=@MakeId,Size=@Size,Width=@Width,Remarks = @Remarks
   WHERE ModelID=@ModelId      
  END  
 ELSE  
  BEGIN  
   INSERT INTO rvlfTyreModel(ModelName,BrandID,Size,Width,Remarks,CreatedDateTime)  
    VALUES(@CarModelName,@MakeId,@Size,@Width,@Remarks,GETUTCDATE())  
  END  
    
      
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveUdpateManageFuel]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveUdpateManageFuel] 
@Mode TINYINT,    
@Sno INT,    
@RefID INT,    
@Odometer bigint,    
@Date datetime = NULL,    
@FuelQty varchar(50) = NULL,    
@Value varchar(50) = NULL,    
@AvgConsumption FLOAT = NULL,    
@CurrConsumption FLOAT = NULL,     
@Variance FLOAT = NULL,    
@ExsLessQty FLOAT= NULL,    
@CreatedBy INT = NULL,    
@CreateDate DATETIME = NULL,    
@ModifiedBy INT = NULL,    
@ModifiedDate DATETIME = NULL,    
@Price FLOAT,     
@Mileage FLOAT 
AS  
-- =============================================                
-- Author:  Kapilraj           
-- Created date: 07-May-2014
-- Description: Fuel Details               
-- =============================================                
BEGIN                 
 SET NOCOUNT ON; 
 IF(@Sno =0) 
  BEGIN  
  INSERT INTO [rvlfFuelContainer]    
    ([RefgId]    
    ,[Odometer]    
    ,[Date]    
    ,[FuelQty]    
    ,[Value]    
    ,[AvgConsumption]    
    ,[CurrConsumption]    
    ,[Variance]    
    ,[ExsLessQty]    
    ,[CreatedBy]    
    ,[CreatedDate]    
    ,[IsDelete]    
    ,[Price]    
    ,[Mileage])    
               
    VALUES (@RefID,@Odometer,@Date,@FuelQty,CASE when @Value ='' then NULL else @Value  end,@AvgConsumption,@CurrConsumption,@Variance,@ExsLessQty,@CreatedBy,GETUTCDATE(),'0',@Price,@Mileage)                                   
           --   substring(@IDNo,2,LEN(@IDNo)-1)    
   END 
  ELSE 
  BEGIN   
   UPDATE [rvlfFuelContainer]    
    SET     
   [RefgId] = @RefID    
   ,[Odometer] = @Odometer    
   ,[Date] = @Date    
   ,[FuelQty] = @FuelQty    
   ,[Value] = CASE when @Value ='' then NULL else @Value  end    
   ,[AvgConsumption] = @AvgConsumption    
   ,[CurrConsumption] = @CurrConsumption    
   ,[Variance] = @Variance    
   ,[ExsLessQty] = @ExsLessQty            
   ,[ModifiedBy] = @ModifiedBy    
   ,[ModifiedDate] = @ModifiedDate     
   ,[Price] = @Price    
      ,[Mileage] = @Mileage                 
   WHERE Sno = @Sno 
  END  
END            
    
    
           

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveUdpateRefrigerationDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveUdpateRefrigerationDetails]                                
@RefrigerationId bigint,                  
@RefrigerationName nvarchar(50)=null,          
@RefrigerationMake varchar(50) =NULL,          
@ModalNo varchar(35) = NULL,          
@EngineNo varchar(35) = NULL,          
@CompressorNo varchar(50) = NULL,          
@AvgFuel varchar(25) = NULL,           
@Assessedvalue varchar(50) = NULL,          
@ModeOfPurchase varchar(50) = NULL,          
@PurchaseValue varchar(50) = NULL,          
@PurchaseDate datetime = NULL,          
@Year varchar(4) =NULL ,          
@AssessedDate datetime = NULL,          
@TechDetails varchar(150) = NULL,          
@CreatedBy bigint=0,          
@ModifiedBy bigint=0,          
@Active bit=NULL,      
@bigOrganizationId bigint,    
@VehicleId bigint = NULL                  
AS          
-- =============================================                      
-- Author:  Kapilraj                 
-- Created date: 7-May-2014                     
-- Description: Refrigeration Details                     
-- =============================================                       
BEGIN                       
 SET NOCOUNT ON;                      
          
             
IF(@RefrigerationId=0)           
           
 BEGIN            
                   
INSERT INTO [rvlfRefrigeration]          
           ([RefgName]          
           ,[RefgMake]          
           ,[Year]          
           ,[ModelNo]          
           ,[EngineNo]          
           ,[CompressorNo]          
           ,[DateOfPurchase]          
           ,[PurchaseValue]          
           ,[AssessedDate]          
           ,[AssessedValue]          
           ,[AvgFuel]          
           ,[ModeOfPurchase]          
           ,[TechDetails]          
           ,[CreatedBy]          
           ,[CreatedDate]                    
           ,[IsDelete]          
           ,[IsActive],      
           OrganizationId) VALUES (@RefrigerationName,@RefrigerationMake,@Year,@ModalNo,@EngineNo,@CompressorNo,@PurchaseDate,          
           @PurchaseValue,@AssessedDate,@Assessedvalue,@AvgFuel,@ModeOfPurchase,@TechDetails,@CreatedBy,GETUTCDATE(),'0',@Active,@bigOrganizationId)                                         
declare @identityValue  bigint    
set @identityValue =IDENT_CURRENT('rvlfRefrigeration')  
if(@VehicleId is not null)  
begin    
update rvlfrefrigeratorassignmt set UnAssignDate=GETUTCDATE() where UnAssignDate is null and VehicleId=@VehicleId    
insert into rvlfrefrigeratorassignmt values(@identityValue,@VehicleId,GETutcDATE(),null)      
     end              
END                    
ELSE                 
 BEGIN                 
            
  UPDATE [rvlfRefrigeration]          
   SET [RefgName] = @RefrigerationName          
      ,[RefgMake] = @RefrigerationMake          
      ,[Year] =@Year          
      ,[ModelNo] = @ModalNo          
      ,[EngineNo] = @EngineNo          
      ,[CompressorNo] = @CompressorNo          
      ,[DateOfPurchase] = @PurchaseDate          
      ,[PurchaseValue] = @PurchaseValue          
      ,[AssessedDate] = @AssessedDate          
      ,[AssessedValue] = @Assessedvalue          
      ,[AvgFuel] = @AvgFuel          
      ,[ModeOfPurchase] = @ModeOfPurchase          
      ,[TechDetails] = @TechDetails               
      ,[ModifiedBy] = @ModifiedBy          
      ,[ModifiedDate] =GETUTCDATE()          
      ,[IsDelete] = '0'          
      ,[IsActive]=@Active          
 WHERE RefgId = @RefrigerationId and  OrganizationId= @bigOrganizationId   
 if(@VehicleId is not null)  
 begin     
 if not exists (select * from rvlfrefrigeratorassignmt where vehicleid=@VehicleId and refgid=@RefrigerationId and unassigndate is null)    
 begin    
 update rvlfrefrigeratorassignmt set UnAssignDate=GETUTCDATE() where UnAssignDate is null and VehicleId=@VehicleId     
 update rvlfrefrigeratorassignmt set UnAssignDate=GETUTCDATE() where UnAssignDate is null and RefgId=@RefrigerationId     
 Insert into rvlfrefrigeratorassignmt values(@RefrigerationId,@VehicleId,GETutcDATE(),null)      
 end    
      end     
 END          
             
          
END                  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveUnregisteredUsers]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_SaveUnregisteredUsers]
/******************************************************                
Stored Procedure Name : rvlf_sp_SaveUnregisteredUsers
Purpose				  : Insert / Update Unregistered Users
Created by			  : Kumuthini. L
Created date		  : 08-Jan-11
Updated History : <<Date>> <<Author>> <<Reason>>
*******************************************************/

@vcUserName varchar(50) = Null,
@vcFirstName varchar(50) = Null,
@vcLastName varchar(50) = Null,
@bigOrganizationId bigint = Null,
@vcDisplayName varchar(100)= Null,
@vcEmail varchar(200) = Null,
@vcMobile varchar(15) = Null,
@bigCreatedBy bigint = Null,
@dtCreatedDateTime DateTime,
@bigModifiedBy bigint = Null,
@dtModifiedDateTime DateTime

AS

BEGIN

   IF EXISTS (SELECT UserId FROM rvlfUser WHERE UserName = @vcUserName AND IsRegisteredUser = 0 AND OrganizationId = @bigOrganizationId)
   BEGIN
   
		UPDATE rvlfUser SET FirstName = @vcFirstName, LastName = @vcLastName, DisplayName = @vcDisplayName, Email = @vcEmail, MobileNo = @vcMobile
		WHERE UserName = @vcUserName AND IsRegisteredUser = 0 AND OrganizationId = @bigOrganizationId
   
   END
   ELSE IF EXISTS (SELECT UserId FROM rvlfUser WHERE UserName = @vcUserName AND IsRegisteredUser IS NULL AND OrganizationId = @bigOrganizationId)
   BEGIN
   
		 raiserror('User Name already exists.', 16,1)
   
   END
   ELSE
   BEGIN
   
	   INSERT INTO rvlfUser (UserName, FirstName, LastName, OrganizationId, DisplayName, Email, MobileNo, IsLocked, IsDelete, IsPwdChanged, IsRegisteredUser,
			CreatedBy, CreatedDateTime)
	   VALUES (@vcUserName, @vcFirstName, @vcLastName, @bigOrganizationId, @vcDisplayName, @vcEmail, @vcMobile, 0, 0, 1, 0, @bigCreatedBy, @dtCreatedDateTime)
	   
   END
    
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveUpdateAndDeleteParentNotification]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 27-06-2015
-- Description:	Save,Update and Delete query for Parent Notifications
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_SaveUpdateAndDeleteParentNotification]
	-- Add the parameters for the stored procedure here
	@bigNotificationId				bigint = NULL,
	@nvcNotificationName			nvarchar(50) = NULL,
	@nvcDescription					nvarchar(2500) = NULL,
	@dtExpiryDate					datetime = NULL,
	@tintNotificationType			tinyint = NULL,	
	@nvcharStudentIDs				varchar(max) = NULL,
	@bigOrganizationId				bigint = NULL,
	@bigUserId						bigint = NULL,
	@bitIsDelete					bit = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF(@bitIsDelete = 0)    
	BEGIN    
		IF @bigNotificationId > 0 
		BEGIN
			UPDATE	rvlfNotificationToParents
			SET		NotificationName = @nvcNotificationName,
					Description = @nvcDescription,					
					ExpiryDate = @dtExpiryDate,
					NotificationType = @tintNotificationType,
					OrganizationId = @bigOrganizationId,
					ModifiedBy = @bigUserId,
					ModifiedDate = GETDATE()
			WHERE	NotificationId = @bigNotificationId	
			DELETE FROM rvlfNotificationToParentsLog WHERE NotificationId = @bigNotificationId
			IF @tintNotificationType = 0
				INSERT INTO rvlfNotificationToParentsLog (StudentId,NotificationId)
					SELECT Element,@bigNotificationId From dbo.func_Split(@nvcharStudentIDs,',')
		END
		ELSE
		BEGIN
			DECLARE @TableID TABLE(NotificationID bigint)
			INSERT INTO rvlfNotificationToParents (NotificationName, Description, ExpiryDate, NotificationType, OrganizationId, CreatedBy, CreatedDate)			
			OUTPUT INSERTED.NotificationId INTO @TableID 
			VALUES (@nvcNotificationName, @nvcDescription, @dtExpiryDate, @tintNotificationType, @bigOrganizationId, @bigUserId, GETDATE())
			IF @tintNotificationType = 0
				INSERT INTO rvlfNotificationToParentsLog (StudentId,NotificationId)
				SELECT Element,(Select NotificationID From @TableID) FROM dbo.func_Split(@nvcharStudentIDs,',') 
		END
	END
	ELSE
	BEGIN
		DELETE	FROM rvlfNotificationToParents
		WHERE	NotificationId = @bigNotificationId
	END
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveUpdateAndDeletePreCanMsgs]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_SaveUpdateAndDeletePreCanMsgs]     
 @bigCannedId bigint=null,  
 @vcMsg varchar(50) = null,    
 @bitIsDelete bit=null,  
 @tiMsgType tinyint = null,    
 @bigOrganizationID bigint = null    
AS    
/******************************************************************************/    
-- Name   : [rvlf_sp_SaveUpdateAndDeletePreCanMsgs] null,'h',0,1,6  
-- Description : To save,Update and delete the precanned messages    
-- Author  : V.Narayanasamy   
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 13-Aug-2011 VN Created Intial Version     
/******************************************************************************/    
BEGIN  
 IF(@bitIsDelete=0)  
  BEGIN  
   IF(@bigCannedId>0)  
    BEGIN  
     UPDATE rvlfPrecannedMessages SET MsgName=@vcMsg,IsServerMsg=@tiMsgType   
      WHERE CannedMsgId=@bigCannedId   
    END  
   ELSE  
    BEGIN  
     DECLARE @tinyPreCannedMsgid TINYINT=(SELECT dbo.rvlf_fn_GetMDTIds(@bigOrganizationID,@tiMsgType))  
       
     IF(@tinyPreCannedMsgid>99)   
      BEGIN  
       DECLARE @vcErrorMsg VARCHAR(200)='Already this organization reached the maximum limit of creating'+CASE WHEN @tiMsgType=0 THEN ' device' ELSE ' server' END+' messages'  
       RAISERROR(@vcErrorMsg,15,0)  
       RETURN  
      END  
     ELSE  
      BEGIN       
--SELECT @vcMsg,@tiMsgType,@bigOrganizationID,@tinyPreCannedMsgid        
       INSERT INTO rvlfPrecannedMessages(MsgName,IsServerMsg,OrganizationId,PrecannedMsgId)  
        VALUES(@vcMsg,@tiMsgType,@bigOrganizationID,@tinyPreCannedMsgid)  
      END  
    END  
  END  
 ELSE  
  BEGIN  
   DELETE FROM rvlfPrecannedMessages WHERE CannedMsgId =@bigCannedId  
  END  
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveUpdateDelete_KPI]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveUpdateDelete_KPI]
@nKpiId INT = NULL,
@vCustTitle VARCHAR(75) = NULL,
@vCustDesc VARCHAR(500) = NULL,
@vTitleColor VARCHAR(10) = NULL,
@bfleetId BIGINT = NULL,
@cBoxIds VARCHAR(75) = NULL,
@tDispTypeId TINYINT = NULL,
@dcCostKPIsValue DECIMAL(18,2) = NULL,
@tnTemperatureType TINYINT = NULL,
@nRefFrequency INT = NULL,
@nDuration INT = NULL,
@nMinRange INT = NULL,
@nMaxRange INT = NULL,
--@TableXML XML = NULL,
@isBitUserGroup BIT = NULL,
@cUserIds VARCHAR(1500)= NULL,
@cFilterIds VARCHAR(30)= NULL,
@nOrganizationId INT = NULL,
@nUserId INT = NULL,
@nOperation TINYINT  = 1, --1 for new, 2 for update, 3 for assign un assign, 4 delete
@nAssignmentId INT = NULL,
@isReversed BIT = 0
AS
/***********************************************************************************************************************
-- PROCEDURE NAME	: rvlf_sp_SaveUpdateDelete_KPI 1,'TEST','TEST','#FF00FF',321,'4107,4129,4000,4116,4123',1,4,8,2,10,0,902,'',902,183,1
-- DESCRIPTION		: TO Save KPI WITH USER ASSIGNMENT Details
-- AUTHOR			: S SAKTHI GOPINATH
-- COMPANY			: TRINETRA WIRELESS (P) LTD
-- HISTORY			: <<DATE(DD-MON-YYYY)>> INITIAL REASON
--					: 12-NOV-2015 SS CREATED INTIAL VERSION
***********************************************************************************************************************/
BEGIN
SET NOCOUNT ON
	
	DECLARE @AlertMessage VARCHAR(350) = '';
	IF @nOperation = 1 AND @nAssignmentId IS NULL
	BEGIN
		--DECLARE @tblName varchar(30) = '/NewDataSet/Table';
		--DECLARE @Index AS INT;
		PRINT '1'
		DECLARE @TemptblUsers TABLE                            
		(                
			id bigint identity(1,1),UserId INT,UserGroupId INT,UserName Varchar(250),OrgID INT
		)   

		--SET	@Index = 0;
		--EXEC SP_XML_PREPAREDOCUMENT @Index OUTPUT,@TableXML

		INSERT INTO @TemptblUsers (UserId,UserGroupId,UserName,OrgID)
		SELECT u.UserId,ug.UserGroupId,u.UserName,u.OrganizationId FROM rvlfUser u INNER JOIN rvlfUserGroupAssignment ug ON ug.UserId=u.userId
		where u.OrganizationId=@nOrganizationId AND
		((@cUserIds = '' OR @cUserIds = '0') OR (@isBitUserGroup = 1 AND (ug.UserGroupId IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cUserIds,',')))))
		OR ((@isBitUserGroup IS NULL OR @isBitUserGroup = 0) AND (u.UserId IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cUserIds,','))))
		--(@isBitUserGroup = 1 AND (ug.UserGroupId IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cUserIds,','))))
		--OR ((@isBitUserGroup IS NULL OR @isBitUserGroup = 0) AND (u.UserId IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cUserIds,','))))
		PRINT '2'
		--SELECT UserId,UserGroupId,UserName,@nOrganizationId          
		--FROM OPENXML (@Index, @tblName) WITH (UserId INT 'UserId', UserGroupId INT 'UserGroupId', UserName VARCHAR(25) 'UserName') SA    

		IF EXISTS (SELECT 1 FROM RVLFKPIUSERASSIGNMENT ku INNER JOIN @TemptblUsers u ON u.UserId=ku.USERID
		WHERE ku.KPIID=@nKpiId AND ( --(ku.FLEETID=@bfleetId AND ku.BOXID='0') OR
		(ku.FLEETID=@bfleetId AND (SELECT COUNT(B.FieldValue) FROM (select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(ku.BOXID,',') EXCEPT 
		select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cBoxIds,',')) AS B) = 0)) AND ku.ISASSIGN=1 AND ku.IsDelete=0)
		BEGIN
			PRINT '8'
			DECLARE @usersName VARCHAR(1500) = ''
			SET @AlertMessage = 'Selected Fleet / Vehicle(s) are already applied to the following users with selected KPI,'
			SELECT @usersName += '* '+u.UserName +'</br>' FROM RVLFKPIUSERASSIGNMENT ku INNER JOIN @TemptblUsers u ON u.UserId=ku.USERID
			WHERE ku.KPIID=@nKpiId AND (--(ku.FLEETID=@bfleetId AND ku.BOXID='0') OR 
			(ku.FLEETID=@bfleetId AND (SELECT COUNT(B.FieldValue) FROM (select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(ku.BOXID,',') EXCEPT 
			select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cBoxIds,',')) AS B) = 0))
			AND ku.ISASSIGN=1 AND ku.IsDelete=0
			SET @AlertMessage = @AlertMessage + '</br>' + @usersName
		END
		ELSE
		BEGIN
		PRINT '3'
			IF @cFilterIDs = '0'
			BEGIN
				SELECT @cFilterIDs = @cFilterIDs + CAST(FilterId AS VARCHAR(3))+',' FROM rvlfKPIFilters WHERE IsDelete=0
				SELECT @cFilterIDs = LEFT(@cFilterIDs, LEN(@cFilterIDs) - 1)
			END

			DECLARE @nReferenceId INT 
			INSERT INTO RVLFKPIREFERENCE_LOG(KPIId,KPITITLE,UserId,UserGroupId,FilterId) VALUES
			(@nKpiId,@vCustTitle,(CASE WHEN @isBitUserGroup = 0 THEN @cUserIds ELSE NULL END),(CASE WHEN @isBitUserGroup = 1 THEN @cUserIds ELSE NULL END),@cFilterIDs)
			SET @nReferenceId = @@IDENTITY;
			PRINT '4'
			INSERT INTO dbo.RVLFKPIUSERASSIGNMENT (KPIID,USERID,ASSIGNEDBY,ASSIGNDDATE,MODIFIEDBY,MODIFIEDDATE,CUSTOMTITLE,CUSTOMDESC,FLEETID,
			BOXID,TITLECLRCODE,DISPTYPEID,CostKPIsValue,TemperatureType,REFRESHFREQUENCY,DURATION,MINRANGE,MAXRANGE,ISASSIGN,ReferenceId,IsDelete,IsReversed)
			SELECT @nKpiId,UserId,@nUserId,GETUTCDATE(),NULL,NULL, @vCustTitle,@vCustDesc,@bfleetId,@cBoxIds,@vTitleColor,@tDispTypeId,
			@dcCostKPIsValue,@tnTemperatureType,@nRefFrequency,@nDuration,@nMinRange,@nMaxRange,1,@nReferenceId,0,@IsReversed
			FROM @TemptblUsers WHERE UserId > 0

			--SET @AlertMessage = 'KPI Details are saved successfully'
			PRINT '5'
			IF @cFilterIDs IS NOT NULL
			BEGIN
			PRINT '6'
				INSERT INTO dbo.RVLFKPIFILTERUSERASSIGNMENT(FILTERID,USERID)
				SELECT KF.FILTERID,U.UserId FROM dbo.RVLFKPIFILTERS KF 
				CROSS APPLY (SELECT UserId FROM @TemptblUsers WHERE UserId > 0) U WHERE
				@cFilterIDs='0' OR FILTERID IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cFilterIDs,','))
			END
		END
		PRINT '7'
	END
	ELSE IF @nOperation = 2 AND @nAssignmentId IS NOT NULL
	BEGIN
		IF EXISTS (SELECT 1 FROM RVLFKPIUSERASSIGNMENT ku INNER JOIN rvlfUser u ON u.UserId=ku.USERID
		WHERE ku.KPIID=@nKpiId AND ku.UserId IN (SELECT UserId FROM rvlfKPIUserAssignment WHERE AssignmentId=@nAssignmentId) AND ( --(ku.FLEETID=@bfleetId AND ku.BOXID='0') OR
		(ku.FLEETID=@bfleetId AND (SELECT COUNT(B.FieldValue) FROM (select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(ku.BOXID,',') EXCEPT 
		select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cBoxIds,',')) AS B) = 0)) AND ku.ISASSIGN=1 AND ku.IsDelete=0 AND ku.AssignmentId <> @nAssignmentId)
		BEGIN
			DECLARE @usersNames VARCHAR(1500) = ''
			SET @AlertMessage = 'Selected Fleet / Vehicle(s) are already applied to the following users with selected KPI,'
			SELECT @usersNames += '* '+u.UserName +'</br>' FROM RVLFKPIUSERASSIGNMENT ku INNER JOIN rvlfUser u ON u.UserId=ku.USERID
			WHERE ku.KPIID=@nKpiId AND ku.UserId IN (SELECT UserId FROM rvlfKPIUserAssignment WHERE AssignmentId=@nAssignmentId) AND (--(ku.FLEETID=@bfleetId AND ku.BOXID='0') OR 
			(ku.FLEETID=@bfleetId AND (SELECT COUNT(B.FieldValue) FROM (select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(ku.BOXID,',') EXCEPT 
			select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cBoxIds,',')) AS B) = 0))
			AND ku.ISASSIGN=1 AND ku.IsDelete=0 AND ku.AssignmentId <> @nAssignmentId
			SET @AlertMessage = @AlertMessage + '</br>' + @usersNames
		END
		ELSE
		BEGIN
			UPDATE dbo.RVLFKPIUSERASSIGNMENT SET MODIFIEDBY=@nUserId,MODIFIEDDATE=GETUTCDATE(),CUSTOMTITLE=@vCustTitle,CUSTOMDESC=@vCustDesc,FLEETID=@bfleetId,
			BOXID=@cBoxIds,TITLECLRCODE=@vTitleColor,DISPTYPEID=@tDispTypeId,CostKPIsValue = @dcCostKPIsValue,TemperatureType = @tnTemperatureType,
			REFRESHFREQUENCY=@nRefFrequency,DURATION=@nDuration,IsReversed=@IsReversed,MINRANGE=@nMinRange,MAXRANGE=@nMaxRange WHERE AssignmentID=@nAssignmentId
			SET @AlertMessage = 'KPI Details are updated successfully'
		END
	END
	ELSE IF @nOperation = 3 AND @nAssignmentId IS NOT NULL
	BEGIN
		DECLARE @cStatus VARCHAR(20) = 'activated'
		UPDATE dbo.RVLFKPIUSERASSIGNMENT SET MODIFIEDBY=@nUserId,MODIFIEDDATE=GETUTCDATE(),ISASSIGN=(CASE WHEN ISASSIGN =0 THEN 1 ELSE 0 END),
		@cStatus = (CASE WHEN ISASSIGN =0 THEN 'activated' ELSE 'deactivated' END) WHERE AssignmentID=@nAssignmentId
		SET @AlertMessage = 'Selected KPI is '+@cStatus+' successfully'
	END
	ELSE IF @nOperation = 4 AND @nAssignmentId IS NOT NULL
	BEGIN
		UPDATE dbo.RVLFKPIUSERASSIGNMENT SET MODIFIEDBY=@nUserId,MODIFIEDDATE=GETUTCDATE(),ISDELETE=1 WHERE AssignmentID=@nAssignmentId
		SET @AlertMessage = 'Selected KPI deleted successfully'
	END

	IF LEN(@AlertMessage) > 1
	BEGIN
		RAISERROR(@AlertMessage,15,0)      
	END
	
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveUpdateDelete_KPI_Test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveUpdateDelete_KPI_Test]
@nKpiId INT = NULL,
@vCustTitle VARCHAR(75) = NULL,
@vCustDesc VARCHAR(500) = NULL,
@vTitleColor VARCHAR(10) = NULL,
@bfleetId BIGINT = NULL,
@cBoxIds VARCHAR(75) = NULL,
@tDispTypeId TINYINT = NULL,
@dcCostKPIsValue DECIMAL(18,2) = NULL,
@tnTemperatureType TINYINT = NULL,
@nRefFrequency INT = NULL,
@nDuration INT = NULL,
@nMinRange INT = NULL,
@nMaxRange INT = NULL,
--@TableXML XML = NULL,
@isBitUserGroup BIT = NULL,
@cUserIds VARCHAR(1500)= NULL,
@cFilterIds VARCHAR(30)= NULL,
@nOrganizationId INT = NULL,
@nUserId INT = NULL,
@nOperation TINYINT  = 1, --1 for new, 2 for update, 3 for assign un assign, 4 delete
@nAssignmentId INT = NULL,
@isReversed BIT = 0,
@Esptype TINYINT =NULL,
@IsAdmin bit = 0,
@Curenergytype INT = NULL
AS
/***********************************************************************************************************************
-- PROCEDURE NAME	: rvlf_sp_SaveUpdateDelete_KPI 1,'TEST','TEST','#FF00FF',321,'4107,4129,4000,4116,4123',1,4,8,2,10,0,902,'',902,183,1
-- DESCRIPTION		: TO Save KPI WITH USER ASSIGNMENT Details
-- AUTHOR			: S SAKTHI GOPINATH
-- COMPANY			: TRINETRA WIRELESS (P) LTD
-- HISTORY			: <<DATE(DD-MON-YYYY)>> INITIAL REASON
--					: 12-NOV-2015 SS CREATED INTIAL VERSION
--					: 09-May-2018 ASAN Changed Fleet and Vehicles to(Site/ESP(s)) AlertMessage
***********************************************************************************************************************/
BEGIN
SET NOCOUNT ON
	DECLARE @nReferenceId INT 
	DECLARE @AlertMessage VARCHAR(350) = '';
	DECLARE @TemptblUsers TABLE                            
		(                
			id bigint identity(1,1),UserId INT,UserGroupId INT,UserName Varchar(250),OrgID INT
		)
 
	IF @nOperation = 1 AND @nAssignmentId IS NULL
	BEGIN
		--DECLARE @tblName varchar(30) = '/NewDataSet/Table';
		--DECLARE @Index AS INT;
		--PRINT '1'	
		--SET	@Index = 0;
		--EXEC SP_XML_PREPAREDOCUMENT @Index OUTPUT,@TableXML

		INSERT INTO @TemptblUsers (UserId,UserGroupId,UserName,OrgID)
		SELECT u.UserId,ug.UserGroupId,u.UserName,u.OrganizationId FROM rvlfUser u INNER JOIN rvlfUserGroupAssignment ug ON ug.UserId=u.userId
		where u.OrganizationId=@nOrganizationId AND
		((@cUserIds = '' OR @cUserIds = '0') OR (@isBitUserGroup = 1 AND (ug.UserGroupId IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cUserIds,',')))))
		OR ((@isBitUserGroup IS NULL OR @isBitUserGroup = 0) AND (u.UserId IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cUserIds,','))))
		--(@isBitUserGroup = 1 AND (ug.UserGroupId IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cUserIds,','))))
		--OR ((@isBitUserGroup IS NULL OR @isBitUserGroup = 0) AND (u.UserId IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cUserIds,','))))
		--PRINT '2'
		--SELECT UserId,UserGroupId,UserName,@nOrganizationId          
		--FROM OPENXML (@Index, @tblName) WITH (UserId INT 'UserId', UserGroupId INT 'UserGroupId', UserName VARCHAR(25) 'UserName') SA    

		IF EXISTS (SELECT 1 FROM RVLFKPIUSERASSIGNMENT ku INNER JOIN @TemptblUsers u ON u.UserId=ku.USERID
		WHERE ku.KPIID=@nKpiId and ISNULL(ku.CurrEnergytype,0)=
		 case when (@nKpiId=1 or @nKpiId=2) then 
			@Curenergytype 
		else 
			ISNULL(ku.CurrEnergytype,0) end and ( --(ku.FLEETID=@bfleetId AND ku.BOXID='0') OR 
		ku.TemperatureType = @Esptype AND
		(ku.FLEETID=@bfleetId AND (SELECT COUNT(B.FieldValue) FROM (select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(ku.BOXID,',') EXCEPT 
		select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cBoxIds,',')) AS B) = 0)) AND ku.ISASSIGN=1 AND ku.IsDelete=0)
		BEGIN
			--PRINT '8'
			DECLARE @usersName VARCHAR(1500) = ''
			SET @AlertMessage = 'Selected Site / Devies(s) are already applied to the following users with selected KPI,'
			SELECT @usersName += '* '+u.UserName +'</br>' FROM RVLFKPIUSERASSIGNMENT ku INNER JOIN @TemptblUsers u ON u.UserId=ku.USERID
			WHERE ku.KPIID=@nKpiId AND (--(ku.FLEETID=@bfleetId AND ku.BOXID='0') OR 
			(ku.FLEETID=@bfleetId AND (SELECT COUNT(B.FieldValue) FROM (select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(ku.BOXID,',') EXCEPT 
			select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cBoxIds,',')) AS B) = 0))
			AND ku.ISASSIGN=1 AND ku.IsDelete=0
			SET @AlertMessage = @AlertMessage + '</br>' + @usersName
		END
		ELSE
		BEGIN
		--PRINT '3'
			IF @cFilterIDs = '0'
			BEGIN
				--SELECT @cFilterIDs = @cFilterIDs + CAST(FilterId AS VARCHAR(3))+',' FROM rvlfKPIFilters WHERE IsDelete=0 @cFilterIDs+ ',' + CAST(FilterId AS VARCHAR(3))
				SELECT @cFilterIDs = @cFilterIDs+ ',' + CAST(FilterId AS VARCHAR(3)) FROM rvlfKPIFilters WHERE IsDelete=0
				SELECT @cFilterIDs = LEFT(@cFilterIDs, LEN(@cFilterIDs) - 1)
			END			
			INSERT INTO RVLFKPIREFERENCE_LOG(KPIId,KPITITLE,UserId,UserGroupId,FilterId) VALUES
			(@nKpiId,@vCustTitle,(CASE WHEN @isBitUserGroup = 0 THEN @cUserIds ELSE NULL END),(CASE WHEN @isBitUserGroup = 1 THEN @cUserIds ELSE NULL END),@cFilterIDs)
			SET @nReferenceId = @@IDENTITY;
			--PRINT '4'
			INSERT INTO dbo.RVLFKPIUSERASSIGNMENT (KPIID,USERID,ASSIGNEDBY,ASSIGNDDATE,MODIFIEDBY,MODIFIEDDATE,CUSTOMTITLE,CUSTOMDESC,FLEETID,
			BOXID,TITLECLRCODE,DISPTYPEID,CostKPIsValue,TemperatureType,REFRESHFREQUENCY,DURATION,MINRANGE,MAXRANGE,ISASSIGN,ReferenceId,IsDelete,IsReversed,CurrEnergytype)
			SELECT @nKpiId,UserId,@nUserId,GETUTCDATE(),NULL,NULL, @vCustTitle,@vCustDesc,@bfleetId,@cBoxIds,@vTitleColor,@tDispTypeId,
			@dcCostKPIsValue,@tnTemperatureType,@nRefFrequency,@nDuration,@nMinRange,@nMaxRange,1,@nReferenceId,0,@IsReversed,@Curenergytype
			FROM @TemptblUsers WHERE UserId > 0

			--SET @AlertMessage = 'KPI Details are saved successfully'
			--PRINT '5'
			IF @cFilterIDs IS NOT NULL
			BEGIN
			--PRINT '6'
				INSERT INTO dbo.RVLFKPIFILTERUSERASSIGNMENT(FILTERID,USERID)
				SELECT KF.FILTERID,U.UserId FROM dbo.RVLFKPIFILTERS KF 
				CROSS APPLY (SELECT UserId FROM @TemptblUsers WHERE UserId > 0) U WHERE
				@cFilterIDs='0' OR FILTERID IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cFilterIDs,','))
			END
		END
		--PRINT '7'
	END
	ELSE IF @nOperation = 2 AND @nAssignmentId IS NOT NULL
	BEGIN
	   
	   INSERT INTO @TemptblUsers (UserId,UserGroupId,UserName,OrgID)
		SELECT u.UserId,ug.UserGroupId,u.UserName,u.OrganizationId FROM rvlfUser u INNER JOIN rvlfUserGroupAssignment ug ON ug.UserId=u.userId
		where u.OrganizationId=@nOrganizationId AND
		((@cUserIds = '' OR @cUserIds = '0') OR (@isBitUserGroup = 1 AND (ug.UserGroupId IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cUserIds,',')))))
		OR ((@isBitUserGroup IS NULL OR @isBitUserGroup = 0) AND (u.UserId IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cUserIds,','))))

		--IF EXISTS (SELECT 1 FROM RVLFKPIUSERASSIGNMENT ku INNER JOIN rvlfUser u ON u.UserId=ku.USERID
		IF EXISTS (SELECT 1 FROM RVLFKPIUSERASSIGNMENT ku INNER JOIN @TemptblUsers u ON u.UserId=ku.USERID
		WHERE ku.KPIID=@nKpiId and ISNULL(ku.CurrEnergytype,0)=
		 case when (@nKpiId=1 or @nKpiId=2) then 
			@Curenergytype 
		else 
			ISNULL(ku.CurrEnergytype,0) END
		AND ku.TemperatureType = @Esptype AND ku.UserId IN (SELECT UserId FROM rvlfKPIUserAssignment WHERE AssignmentId=@nAssignmentId) AND ( --(ku.FLEETID=@bfleetId AND ku.BOXID='0') OR
		(ku.FLEETID=@bfleetId AND (SELECT COUNT(B.FieldValue) FROM (select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(ku.BOXID,',') EXCEPT 
		select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cBoxIds,',')) AS B) = 0)) AND ku.ISASSIGN=1 AND ku.IsDelete=0 AND ku.AssignmentId <> @nAssignmentId)
		BEGIN
			DECLARE @usersNames VARCHAR(1500) = ''
			SET @AlertMessage = 'Selected Site / Devies(s) are already applied to the following users with selected KPI,'
			SELECT @usersNames += '* '+u.UserName +'</br>' FROM RVLFKPIUSERASSIGNMENT ku INNER JOIN rvlfUser u ON u.UserId=ku.USERID
			WHERE ku.KPIID=@nKpiId AND ku.UserId IN (SELECT UserId FROM rvlfKPIUserAssignment WHERE AssignmentId=@nAssignmentId) AND (--(ku.FLEETID=@bfleetId AND ku.BOXID='0') OR 
			(ku.FLEETID=@bfleetId AND (SELECT COUNT(B.FieldValue) FROM (select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(ku.BOXID,',') EXCEPT 
			select FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cBoxIds,',')) AS B) = 0))
			AND ku.ISASSIGN=1 AND ku.IsDelete=0 AND ku.AssignmentId <> @nAssignmentId
			SET @AlertMessage = @AlertMessage + '</br>' + @usersNames
		END
		ELSE
		BEGIN
		   IF @cFilterIDs = '0'
			BEGIN
				--SELECT @cFilterIDs = @cFilterIDs + CAST(FilterId AS VARCHAR(3))+',' FROM rvlfKPIFilters WHERE IsDelete=0
				--SELECT @cFilterIDs = LEFT(@cFilterIDs, LEN(@cFilterIDs) - 1)	
				SELECT @cFilterIDs = @cFilterIDs+ ',' + CAST(FilterId AS VARCHAR(3)) FROM rvlfKPIFilters WHERE IsDelete=0
				SELECT @cFilterIDs = LEFT(@cFilterIDs, LEN(@cFilterIDs) - 1)		
			END
			DECLARE @AssignedBy INT 

			SELECT @nReferenceId= REFERENCEID,@AssignedBy =ASSIGNEDBY  from RVLFKPIUSERASSIGNMENT WHERE ASSIGNMENTID =@nAssignmentId

			IF(@nUserId = @AssignedBy)
			BEGIN
			   -- PRINT 'Yes'			   
			   --UPDATE dbo.RVLFKPIUSERASSIGNMENT SET ISDELETE=1 WHERE REFERENCEID=@nReferenceId
			    IF @cFilterIDs = '0'
			    BEGIN
				 SELECT @cFilterIDs = @cFilterIDs + CAST(FilterId AS VARCHAR(3))+',' FROM rvlfKPIFilters WHERE IsDelete=0
				 SELECT @cFilterIDs = LEFT(@cFilterIDs, LEN(@cFilterIDs) - 1)				
			    END	
			      DELETE FROM dbo.RVLFKPIUSERASSIGNMENT WHERE REFERENCEID=@nReferenceId

			      UPDATE RVLFKPIREFERENCE_LOG SET UserId = (CASE WHEN @isBitUserGroup = 0 THEN @cUserIds ELSE NULL END),UserGroupId = (CASE WHEN @isBitUserGroup = 1 THEN @cUserIds ELSE NULL END),
				  FilterId =@cFilterIDs WHERE REFERENCEID=@nReferenceId		
			  		
			      INSERT INTO dbo.RVLFKPIUSERASSIGNMENT (KPIID,USERID,ASSIGNEDBY,ASSIGNDDATE,MODIFIEDBY,MODIFIEDDATE,CUSTOMTITLE,CUSTOMDESC,FLEETID,
			      BOXID,TITLECLRCODE,DISPTYPEID,CostKPIsValue,TemperatureType,REFRESHFREQUENCY,DURATION,MINRANGE,MAXRANGE,ISASSIGN,ReferenceId,IsDelete,IsReversed,CurrEnergytype)
			      SELECT @nKpiId,UserId,@nUserId,GETUTCDATE(),NULL,NULL, @vCustTitle,@vCustDesc,@bfleetId,@cBoxIds,@vTitleColor,@tDispTypeId,
			      @dcCostKPIsValue,@tnTemperatureType,@nRefFrequency,@nDuration,@nMinRange,@nMaxRange,1,@nReferenceId,0,@IsReversed,@Curenergytype
			      FROM @TemptblUsers WHERE UserId > 0	
				  	
				  SET @AlertMessage = 'KPI Details are updated successfully'
			   --UPDATE RVLFKPIREFERENCE_LOG SET UserId = (CASE WHEN @isBitUserGroup = 0 THEN @cUserIds ELSE NULL END),UserGroupId = (CASE WHEN @isBitUserGroup = 1 THEN @cUserIds ELSE NULL END),FilterId =@cFilterIDs WHERE REFERENCEID=@nReferenceId		
			   
			   --UPDATE dbo.RVLFKPIUSERASSIGNMENT SET ISDELETE =(CASE WHEN @isBitUserGroup = 0 THEN 1 ELSE 0 END) WHERE REFERENCEID=@nReferenceId and UserId NOT IN (SELECT FieldValue from dbo.rvlf_fn_ConvertArrayToTable(@cUserIds,','))
			END

			ELSE
			 BEGIN
			   UPDATE dbo.RVLFKPIUSERASSIGNMENT SET MODIFIEDBY=@nUserId,MODIFIEDDATE=GETUTCDATE(),CUSTOMTITLE=@vCustTitle,CUSTOMDESC=@vCustDesc,FLEETID=@bfleetId,
			   BOXID=@cBoxIds,TITLECLRCODE=@vTitleColor,DISPTYPEID=@tDispTypeId,CostKPIsValue = @dcCostKPIsValue,TemperatureType = @tnTemperatureType,
			   REFRESHFREQUENCY=@nRefFrequency,DURATION=@nDuration,IsReversed=@IsReversed,MINRANGE=@nMinRange,MAXRANGE=@nMaxRange,CurrEnergytype =@Curenergytype WHERE AssignmentID=@nAssignmentId
			   SET @AlertMessage = 'KPI Details are updated successfully'
			END
		END
	END
	ELSE IF @nOperation = 3 AND @nAssignmentId IS NOT NULL
	BEGIN
		DECLARE @cStatus VARCHAR(20) = 'activated'
		UPDATE dbo.RVLFKPIUSERASSIGNMENT SET MODIFIEDBY=@nUserId,MODIFIEDDATE=GETUTCDATE(),ISASSIGN=(CASE WHEN ISASSIGN =0 THEN 1 ELSE 0 END),
		@cStatus = (CASE WHEN ISASSIGN =0 THEN 'activated' ELSE 'deactivated' END) WHERE AssignmentID=@nAssignmentId
		SET @AlertMessage = 'Selected KPI is '+@cStatus+' successfully'
	END
	ELSE IF @nOperation = 4 AND @nAssignmentId IS NOT NULL
	BEGIN
		UPDATE dbo.RVLFKPIUSERASSIGNMENT SET MODIFIEDBY=@nUserId,MODIFIEDDATE=GETUTCDATE(),ISDELETE=1 WHERE AssignmentID=@nAssignmentId
		SET @AlertMessage = 'Selected KPI deleted successfully'
	END
	ELSE IF @nOperation = 5 AND @nAssignmentId IS NOT NULL
	BEGIN
	    
		DECLARE @RefId INT =  NULL

		SET @RefId = (Select Top 1 REFERENCEID from dbo.RVLFKPIUSERASSIGNMENT WHERE AssignmentID=@nAssignmentId)
		
		UPDATE dbo.RVLFKPIUSERASSIGNMENT SET MODIFIEDBY=@nUserId,MODIFIEDDATE=GETUTCDATE(),ISDELETE=1 WHERE REFERENCEID=@RefId
		SET @AlertMessage = 'Selected KPI deleted successfully'

	END
	IF LEN(@AlertMessage) > 1
	BEGIN
		RAISERROR(@AlertMessage,15,0)      
	END
	
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveUser]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_SaveUser]    
/******************************************************                    
Stored Procedure Name : rvlf_sp_SaveUser    
Purpose     : Insert/Update User    
Created by    : N.Uma Maheswari    
Created date   : 17-Jul-09    
Updated History : <<Date>> <<Author>> <<Reason>>    
      10-Sep-2009 Jaya Chitra To have the default prefrences when the new user is added.    
      10-OCT-2009 Mohanaraj to insert new fleet if not present in the Fleet user table.    
      30-July-2011 Ranjith - Added new Column IsHidden in insert and update    
      10-Sep-2011  Ranjith - ExpiryDate Parameter added  
*******************************************************/    
    
@UserID  bigint  = Null,    
@TitleId int = Null,    
@FirstName  varchar(50) = Null,    
@LastName   varchar(50) = Null,    
@UserName   varchar(50) = Null,    
@DispName   varchar(100)= Null,    
@Pwd  varchar(100) = Null,    
@Phone  varchar(15) = Null,    
@Mobile  varchar(15) = Null,    
@Email  varchar(200)= Null,    
@OrgnID  int   = Null,    
@IsLocked bit   = Null,    
@IsSMS varchar(5) = Null,  
@IsActive bit = Null,    
@UserGroups Varchar(500) = Null,    
@CreatedBy  bigint  = Null,    
@CreatedDateTime DateTime,    
@ModifiedBy bigint  = Null,    
@ModifiedDateTime DateTime,    
@bigTimeZoneID bigint = null,    
@bigDefaultFleetID bigint = null,    
@intRefreshFrequencyId int = null,    
@intDistance int = null,  
@IsHidden bit =Null,  
@ExpiryDate datetime = Null,
@CustomerID bigint=null  
    
AS    
    
BEGIN    
    
IF(@bigDefaultFleetID = 0)    
BEGIN     
    
 SET @bigDefaultFleetID = NULL    
    
END    
    
DECLARE @UID AS BIGINT = 0    
    
IF (@UserID > 0 )    
 BEGIN    
       
    SET @UID = @UserID    
     
    UPDATE rvlfUser SET    
    FirstName=@FirstName,        
    LastName=@LastName,    
    TitleId=@TitleId,    
    UserName=@UserName,    
    DisplayName =@DispName,    
    PhoneNo=@Phone,    
    MobileNo=@Mobile,    
    Email=@Email,    
    OrganizationId=@OrgnID,    
    IsLocked=@IsLocked,    
    IsActive=@IsActive,    
    ModifiedBy=@ModifiedBy,    
    ModifiedDateTime=@ModifiedDateTime,  
    IsHidden=@IsHidden,
	CustomerID=@CustomerID
    WHERE UserId=@UserID    
        
    UPDATE rvlfUserPreferences SET     
  DefaultFleetId = @bigDefaultFleetID ,    
  TimezoneId = @bigTimeZoneID,    
  Distance = @intDistance,    
  RefreshFrequencyId = @intRefreshFrequencyId  WHERE UserId = @UserID    
        
    IF(@UserGroups <> '' AND @UserGroups IS NOT NULL)    
    BEGIN    
    
  INSERT INTO rvlfUserGroupAssignment(UserId,UserGroupId,AssignedBy,AssignedDate)    
     SELECT @UserID AS UserId, FieldValue AS UserGroupId, @ModifiedBy AS 'AssignedBy', @ModifiedDateTime AS 'AssignedDate'     
     FROM rvlf_fn_ConvertArrayToTable(@UserGroups,',')     
     WHERE FieldValue NOT IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @UserID)    
    
     DELETE FROM rvlfUserGroupAssignment WHERE UserId = @UserID AND UserGroupId NOT IN    
           (SELECT FieldValue FROM rvlf_fn_ConvertArrayToTable(@UserGroups,','))    
 END    
 END    
ELSE    
 BEGIN    
   INSERT INTO rvlfUser    
   (FirstName,    
   LastName,    
   TitleId,    
   UserName,    
   DisplayName,    
   Password,    
   PhoneNo,    
   MobileNo,    
   Email,    
   OrganizationId,    
   IsLocked,    
   IsActive,    
   IsPwdChanged,    
   CreatedBy,    
   CreatedDateTime,    
   ISDELETE,  
   IsHidden,
   CustomerID)    
   VALUES    
   (@FirstName,    
    @LastName,    
    @TitleId,    
    @UserName,    
    @DispName,    
    @Pwd,    
    @Phone,    
    @Mobile,    
    @Email,    
    @OrgnID,    
    @IsLocked,    
    @IsActive,    
    0,    
    @CreatedBy,    
    @CreatedDateTime,    
    0,  
    @IsHidden,@CustomerID)    
        
	SET @UID = (SELECT IDENT_CURRENT('rvlfUser'))

    INSERT INTO rvlfUserPreferences (UserId, TimezoneId, RefreshFrequencyId, Distance, DefaultFleetId,ORGANIZATIONID,UserPreferedChart)    
  VALUES (@UID, @bigTimeZoneID, @intRefreshFrequencyId , @intDistance, @bigDefaultFleetID,0,'1,3,287,373')    
        
    IF(@UID > 0)    
    BEGIN    
    
  INSERT INTO rvlfUserGroupAssignment(UserId,UserGroupId,AssignedBy,AssignedDate)    
     SELECT @UID AS UserId, FieldValue AS UserGroupId, @ModifiedBy AS 'AssignedBy', @ModifiedDateTime AS 'AssignedDate'     
     FROM rvlf_fn_ConvertArrayToTable(@UserGroups,',')    
    END             
 END    
     
 IF(@bigDefaultFleetID IS NOT NULL)    
 BEGIN    
     
  DECLARE @FleetCount AS BIGINT = 0;    
       
  Select @FleetCount = count(*) from rvlfFleetUsers where UserId = @UID and FleetId = @bigDefaultFleetID    
      
  if (@FleetCount=0)    
  BEGIN    
 INSERT INTO rvlfFleetUsers (FleetId,UserId,AssignedBy,AssignedDate) values (@bigDefaultFleetID,@UID,@ModifiedBy,@ModifiedDateTime)    
  END    
     
 END     
	
	SELECT OrganizationId,OrganizationCode,OrganizationDisplayName FROM rvlfOrganization WHERE OrganizationId = @OrgnID
    
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveUserFeedback]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	Saves User Feedbacks.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_SaveUserFeedback]
	-- Add the parameters for the stored procedure here
	 @intUserid int =null,      
	 @bigOrganizationID int = null,
     @IsPushNotfication int = null,
     @FeedbackText nvarchar(350) = null,
     @FeedbackDate datetime =null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	INSERT INTO dbo.rvlfUserFeedback (UserId, OrganizationId, FeedbackText, FeedbackDate, IsPushNotification, Status)
	VALUES(@intUserid, @bigOrganizationID, @FeedbackText, @FeedbackDate, @IsPushNotfication, 0)
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveUserGroup]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[rvlf_sp_SaveUserGroup]
	@userGroupId INT = NULL,
	@userGroupName VARCHAR(30),
	@userGroupDescription VARCHAR(250),
	@isDefault BIT,
	@organizationId	INT,
	@createdBy BIGINT = NULL,
	@createdDate DATETIME = NULL,
	@modifiedBy BIGINT = NULL,
	@modifiedDate DATETIME = NULL,
	@vcModuleIDs VARCHAR(250) = NULL,
	@vcOperationIDs VARCHAR(1000) = NULL,  
    @LockUserTries tinyint=null   
		
AS

/**************************************************************************************************/
--	Name		:	[rvlf_sp_SaveUserGroup]
--	Description	:	To insert/Update user group details.
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	23-Nov-2009	VN	Created Intial Version 
--              :   01-Dec-09 Kumuthini. L Updated for User Group Modules & Operations Assignment
--				:	04-Dec-2009 MJJC	Code to add the rights for the parent modules
--				:   20-May-2010 LK      Increased the size of the parameter @vcOperationIDs
/**************************************************************************************************/

BEGIN
	IF(@userGroupId > 0)
		BEGIN
			UPDATE rvlfUserGroup  SET UserGroupName=@userGroupName ,UserGroupDesc=@userGroupDescription,
									  OrganizationId=@organizationId,ModifiedBy =@modifiedBy,
									  ModifiedDate=@modifiedDate,LockUserTries=@LockUserTries 
								WHERE UserGroupId =@userGroupId 
								
			DELETE FROM rvlfUserGroupSecurity WHERE UserGroupId = @userGroupId
		END
	ELSE
		BEGIN
	
			INSERT INTO rvlfUserGroup(UserGroupName,UserGroupDesc,IsDefaultUserGroup,OrganizationId,CreatedBy,
									  CreatedDate,ModifiedBy,ModifiedDate,LockUserTries)
							  VALUES(@userGroupName,@userGroupDescription,@isDefault,@organizationId,@createdBy,
									 @createdDate,null,null,@LockUserTries)
									 
			SET @userGroupId = @@IDENTITY
		END
	
	DECLARE @BigCreatedBy BIGINT
	DECLARE @dtCreatedDate DATETIME
	
	IF(@createdBy IS NOT NULL OR @createdBy !='')
	BEGIN
		SET @BigCreatedBy = @createdBy
		SET @dtCreatedDate = @createdDate
	END
	
	IF(@modifiedBy IS NOT NULL OR @modifiedBy !='')
	BEGIN
		SET @BigCreatedBy = @modifiedBy
		SET @dtCreatedDate = @modifiedDate
	END
		
    IF CHARINDEX('175', @vcOperationIDs, 1) > 0 OR CHARINDEX('177', @vcOperationIDs, 1) > 0 OR CHARINDEX('178', @vcOperationIDs, 1) > 0
	   BEGIN
	      SET @vcOperationIDs = @vcOperationIDs + ',144'
	   END
	   
	-- Insert the Operations for the User Group
	INSERT INTO rvlfUserGroupSecurity(UserGroupId, ModuleId, OperationTypeId, CreatedBy, CreatedDateTime) 
			 (SELECT @userGroupId, OT.ModuleID, OT.OperationTypeId, @BigCreatedBy, @dtCreatedDate FROM rvlfOperationType OT
			  WHERE OT.OperationTypeId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcOperationIDs,','))
			 )
	
	-- Insert the Modules for the User Group
	INSERT INTO rvlfUserGroupSecurity(UserGroupId, ModuleId, OperationTypeId, CreatedBy, CreatedDateTime) 
		 (SELECT @userGroupId, ModuleID, NULL AS OperationID, @BigCreatedBy, @dtCreatedDate FROM rvlfModule
			  WHERE ModuleID IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcModuleIDs,','))
		 )
	INSERT INTO rvlfUserGroupSecurity (ModuleId,UserGroupId, CreatedBy, CreatedDateTime) 
		SELECT distinct ParentModuleId , @userGroupId,CreatedBy,CreatedDate FROM rvlfModule 
			WHERE ModuleID IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@vcModuleIDs,','))
		AND ParentModuleId IS NOT NULL
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveUserLoginDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveUserLoginDetails]     
/******************************************************    
Stored Procedure Name : rvlf_sp_SaveUserLoginDetails    
Purpose     : To save the Login Details with Session Id  
Created by    : Kumuthini. L    
Created date   : 15-Oct-09    
Updated by    :     
Updated date   :     
*******************************************************/    
  
@Type nvarchar(15) = Null,  
@SessionId  nvarchar(500) = Null,    
@UserId  bigint  = Null,    
@OrgId  int  = Null,  
@LoginId  bigint  = Null,  
@UserName nvarchar(50) = Null,  
@DisplayName nvarchar(50) = Null,  
@OrgName nvarchar(50) = Null,  
@IsAnglerAdmin bit = 0,  
@LastLoginDateTime datetime = Null,  
@LastLoginUser nvarchar(50) = Null,  
@TimeZoneHours int = Null,   
@TimeZoneMins int = Null,  
@DistanceSpeedUnit int = Null  
  
AS    
    
BEGIN
--set @IsAnglerAdmin= case when @OrgId=1 then 1 else @IsAnglerAdmin end     
  
  DECLARE @HasPackage AS BIT = 0  
  IF EXISTS(SELECT PackageId FROM rvlfOrganizationPackage WHERE OrganizationID = @OrgId)  
 BEGIN  
  SET @HasPackage = 1  
 END  
    
  IF(@Type = 'UpdateOrg')  
  BEGIN  
  UPDATE rvlfUserLoginDetails SET OrgId = @OrgId, HasPackageId = @HasPackage WHERE SessionId = @SessionId  
  END  
  ELSE  
  BEGIN  
    
   UPDATE rvlfUser SET IsPwdChanged = 1 WHERE UserId = @UserId  
    
   DECLARE @Count as int = 0  
     
   SET @Count = (SELECT Count(*) FROM rvlfUserLoginDetails WHERE SessionId = @SessionId)  
     
   IF (@Count > 0)   
   BEGIN  
   UPDATE rvlfUserLoginDetails SET UserId = @UserId, OrgId = @OrgId, LoginId = @LoginId, UserName = @UserName,  
   DisplayName = @DisplayName, OrgName = @OrgName, IsAnglerAdmin = @IsAnglerAdmin,   
   LastLoginDateTime = @LastLoginDateTime, LastLoginUser = @LastLoginUser, TimeZoneHours = @TimeZoneHours,  
   TimeZoneMins = @TimeZoneMins, DistanceSpeedUnit = @DistanceSpeedUnit, HasPackageId = @HasPackage  
   WHERE SessionId = @SessionId  
   END  
   ELSE  
   BEGIN  
   INSERT INTO rvlfUserLoginDetails (SessionId, UserId, OrgId, LoginId, UserName, DisplayName, OrgName,   
   IsAnglerAdmin, LastLoginDateTime, LastLoginUser, TimeZoneHours, TimeZoneMins, DistanceSpeedUnit, HasPackageId)  
   VALUES (@SessionId, @UserId, @OrgId, @LoginId, @UserName, @DisplayName, @OrgName,   
   @IsAnglerAdmin, @LastLoginDateTime, @LastLoginUser, @TimeZoneHours, @TimeZoneMins, @DistanceSpeedUnit, @HasPackage)    
   END  
  END  
      
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveVehicleCost]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveVehicleCost]
@bigFleetId int = null,
@VehicleId int = null,
@TableXML XML = NULL ,
@bigOrganizationID bigint = null,
@bigQueryingUser bigint = 0
AS
/********************************************************************************************  
Stored Procedure Name : rvlf_sp_SaveVehicleCost
Purpose       : Insert / Update the vehicle cost
Created by    : S. Sakthi Gopinath
Created date  : 17-Jul-13
*********************************************************************************************/    
BEGIN
SET NOCOUNT ON

    DECLARE @tblName varchar(30) = 'DocumentElement/ServiceDetails/'
    DECLARE @Index AS INT;        
    SET @Index = 0;                                            
    EXEC Sp_xml_preparedocument  @Index OUTPUT,@TableXML         
    
    INSERT INTO rvlfVehicleCost(CostType,VehicleId,Cost,CreatedBy,CreatedDate,EffectiveFrom,EffectiveTo)        
    SELECT CostId,@VehicleId,PlannedCost,@bigQueryingUser,GETUTCDATE(),GETUTCDATE(),DATEADD(YEAR,1,GETUTCDATE())
     FROM OPENXML (@Index, @tblName)        
    WITH (CostId int 'CostId',  
    CostType int 'CostType',  
    PlannedCost  DECIMAL(10,2) 'PlannedCost') ROI

SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveVehicleDocuments]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasu.E
-- Create date: 03-08-2016
-- Description:	<Save Uploaded vehicle documents in rvlfVehicleDocuments table>.
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_SaveVehicleDocuments]
	-- Add the parameters for the stored procedure here
	@bigVehicleId			bigint			= null,
	@vcDocumentName			nvarchar(50)	= null,
	@vcDocumentPath			nvarchar(MAX)	= null,	
	@bigProcessedBy			bigint			= null,
	@dtProcessedDateTime	datetime		= null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF (Select UploadID From rvlfVehicleDocuments Where VehicleId = @bigVehicleId and DocumentName = @vcDocumentName and IsDeleted <> 1) > 0
	BEGIN
		Update rvlfVehicleDocuments Set IsDeleted = 1 Where VehicleId = @bigVehicleId and DocumentName = @vcDocumentName and IsDeleted <> 1
	END

	INSERT INTO rvlfVehicleDocuments(VehicleId, DocumentName, DocumentPath, UploadedBy, UploadedDate, IsDeleted)
		VALUES (@bigVehicleId, @vcDocumentName, @vcDocumentPath, @bigProcessedBy, @dtProcessedDateTime, 0)
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveVehicleInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveVehicleInfo]  
/******************************************************************************/  
-- Name  : rvlf_sp_SaveVehicleInfo  
-- Description : To insert / update the vehicle information  
-- Author  : M. Jebamalai Jaya Chitra.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 28-Sep-2009 MJJC Created Intial Version   
-- Updated by : V.Narayanasamy / Adding display name    
--              :   Kumuthini. L / 20-Nov-09 / Inserting the vehicles into the   
--                  default Fleet of an Organization  
--    : 16-Jan-10 MJJC To have the default values in the rvlfMsgInHst and rvlfBoxID  
--    :  in order to show the same in the monitor and dashboard pages  
--    : 06-Feb-2010 MJJC To have N/A for the Street Address and Landmark  
--    : 18-Mar-2010 VN To add the sensor details  
--    : 30-Mar-2010 MJJC To include the message severity for the vehicles to have default values  
--    : 22-July-2010 VN Added the vehicle category field.  
--    : 28-july-2010 VN Added the vehicle insurance,permit and fc expired dates.  
--              : 23-Jan-2012 Sakthi - Add internal number for vehicle information    
/******************************************************************************/  
 @intBoxId           int      = Null,  
 @bigVehicleId  bigint   = Null,  
 @tiVehicleTypeID tinyint   = Null,  
 @vcVehicleName  varchar(20)  = Null,  
 @siMakeID   smallint  = Null,  
 @vcIntNo    varchar(20)  = Null,    
 @vcVIN    varchar(20)  = Null,  
 @siModelID   smallint  = Null,  
 @vcLicensePlate  varchar(20)  = Null,  
 @siYear    smallint  = Null,  
 @bigTimeZoneId  bigint = 3,  
 @vcColor   varchar(20) = Null,  
 @bitNotify   bit = 0,  
 @bitWarning   bit = 0,  
 @bitCritical  bit = 0,  
 @bigProcessedBy  bigint = Null,  
 @dtProcessedDateTime DateTime,  
 @bigOrganizationId bigint,  
 @tblNotificationsList As NotificaitonUserList READONLY,  
 @displayName  varchar(10)=Null,  
 @vcLocation   varchar(200)=null,  
 @vcCategory   varchar(5)=null,  
 @dtInsuranceExpired datetime=null,  
 @dtPermitExpired datetime=null,  
 @dtFcExpired datetime=null,  
 @dtPurchasedDate datetime=null,  
 @intOpeningEngineHrs int=null,  
 @intFuelTankCapacity int=null  
AS        
  
BEGIN         
  
 SET NOCOUNT ON  
   
 IF @intFuelTankCapacity = 0  
 BEGIN  
   
  SET @intFuelTankCapacity = NULL  
   
 END  
   
 IF @bigVehicleId IS NOT NULL  
 BEGIN  
  IF EXISTS(SELECT * FROM rvlfVehicle WHERE VehicleId=@bigVehicleId AND OrganizationId= @bigOrganizationId)  
  BEGIN  
   UPDATE rvlfVehicle SET  
    VehicleTypeId =@tiVehicleTypeID,  
    VehicleDescription=@vcVehicleName,  
    MakeId=@siMakeID,  
    InternalNo=@vcIntNo,  
    Vin=@vcVIN,  
    ModelId=@siModelID,  
    LicensePlate=@vcLicensePlate,  
    ModelYear= @siYear,  
    TimeZone=@bigTimeZoneId,  
    Color=@vcColor,  
    Notify=@bitNotify,  
    Warning=@bitWarning,  
    Critical=@bitCritical,  
    OrganizationId= @bigOrganizationId,  
    ModifiedBy=@bigProcessedBy,  
    DisplayName=@displayName,   
    [Modified DateTime] = @dtProcessedDateTime,  
    location=@vcLocation,  
    category=@vcCategory,  
    LastInsuranceExpired =@dtInsuranceExpired,  
    LastFCDate=@dtFcExpired,  
    LastPermitExpired =@dtPermitExpired,  
    PurchasedDate =@dtPurchasedDate,  
    OpeningEngineHours =@intOpeningEngineHrs,  
    TankCapacity =@intFuelTankCapacity  
   WHERE VehicleId = @bigVehicleId  
     
   DELETE FROM rvlfNotificationList WHERE TypeID = @bigVehicleId AND NotificationType = 4  
   exec rvlf_sp_Save_notificationsList @tblNotificationsList,4,@bigVehicleId  
     
  END  
  ELSE  
  BEGIN  
   raiserror('Vehicle information dosen''t exists !',16,1)  
  END  
 END  
 ELSE  
  BEGIN  
         
        -- Insert the Vehicle informations into the Vehicle Table  
        INSERT INTO rvlfVehicle (InternalNo, Vin, LicensePlate, MakeId, ModelId, VehicleTypeId, StateProvince, ModelYear, Color, VehicleDescription, OrganizationId, IconTypeId, TimeZone, DayLightSaving, Notify, Critical, Warning, AutoAdjustDayLightSaving,
 CreatedBy, CreatedDateTime,DisplayName,location,category,LastFCDate,LastInsuranceExpired,LastPermitExpired,IsEmailSent,IsSMSSent,PurchasedDate,OpeningEngineHours,TankCapacity,RptInterval,SpdThreshold)   
        VALUES (@vcIntNo, @vcVIN, @vcLicensePlate, @siMakeID, @siModelID, @tiVehicleTypeID, 'Tamil Nadu', @siYear, @vcColor, @vcVehicleName, @bigOrganizationId, 1, @bigTimeZoneId, 0, @bitNotify, @bitCritical, @bitWarning, 0, @bigProcessedBy, @dtProcessedDateTime,@displayName,@vcLocation,@vcCategory,@dtFcExpired,@dtInsuranceExpired,@dtPermitExpired,0,0,@dtPurchasedDate,@intOpeningEngineHrs,@intFuelTankCapacity,'00:10:00',100)  
          
        SET @bigVehicleId = (SELECT @@IDENTITY)  
          
        EXEC rvlf_sp_Save_notificationsList @tblNotificationsList,4,@bigVehicleId  
          
        -- Insert the created vehicle with its Box Id in the Vehicle Assignment Table  
        INSERT INTO rvlfVehicleAssignment (BoxId, VehicleId, AssingedBy, AssignedDateTime, ServiceID)  
        VALUES (@intBoxId, @bigVehicleId, @bigProcessedBy, @dtProcessedDateTime, 1)  
          
        -- Select the Default Fleet Id for the particular Organization  
          
        DECLARE @bigDefaultFleetId AS BIGINT = 0  
          
        SELECT @bigDefaultFleetId = FleetId FROM rvlfFleet WHERE OrganizationId = @bigOrganizationId AND IsDefault = 1  
          
        -- Assign the created vehicle into default fleet of the particular Organization  
          
         INSERT INTO rvlfFleetVehicles (FleetId, VehicleId, IsActive, AssignedBy, AssignedDate)  
        VALUES (@bigDefaultFleetId, @bigVehicleId, 1 , @bigProcessedBy, @dtProcessedDateTime)  
          
        DECLARE @uiMsgInID uniqueidentifier = NEWID()  
  
   INSERT INTO rvlfMsgInHst (MessageInID, BoxId, OriginDateTime, DateTimeReceived,ServiceID, BoxMsgInTypeId,  
   BoxProtocolTypeId, CommInfo1, CommInfo2, ValidGps, Latitude, Longitude, Speed, Heading, SensorMask, CustomProp,  
   StreetAddress, SequenceNum, IsArmed, NearestLandmark, Priority, IsNotificationSent, LandMarkID ) VALUES   
   ( @uiMsgInID , @intBoxID, SYSUTCDATETIME(), SYSUTCDATETIME(),1,1,  
    1,NULL,NULL,1,0.000000,0.000000,0,0,'00000000','Odometer=1;Fuel%=0','N/A',NULL,0,'N/A',0,0,NULL)  
    
   INSERT INTO rvlfBoxId 
   
(BoxId,FwChId,BoxArmed,LastValidDateTime,LastLatitude,LastLongitude,LastSpeed
   ,LastStreetAddress,LastCommunicatedDateTime,LastSensorMask,OrganizationId,LastStatusDateTime,NearestLandmark,Heading,MessageInId)
   VALUES (@intBoxID,NULL,0,SYSUTCDATETIME(),10.997237,76.987802,0,'N/A',  
    DATEADD(MI,3,SYSUTCDATETIME()),'00000000', @bigOrganizationID, DATEADD(MI,1,SYSUTCDATETIME()),  
    'N/A', 0, @uiMsgInID)  
      
   INSERT INTO rvlfBoxMsgSeverity   
    SELECT @intBoxID,b.BoxMsgInTypeId, p.DefaultAlarmLevel FROM rvlfBoxMsgInType b   
     INNER JOIN rvlfBoxProtocolMsgInType p ON b.BoxMsgInTypeId = p.BoxMsgInTypeId  
    WHERE b.OperationTypeID IN   
    (SELECT OperationID FROM rvlfPackageOperations WHERE PackageId =   
    (SELECT PackageId FROM rvlfOrganizationPackage WHERE OrganizationID = (SELECT OrganizationID   
    FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID   
     WHERE va.BoxID = @intBoxID) AND IsActive=1))  
    AND b.CanSeveritySet = 1 AND b.BoxMsgInTypeId NOT IN   
    (SELECT BoxMsgInTypeId FROM rvlfBoxMsgSeverity WHERE BoxId = @intBoxID)  
     
   --insert into boxsettings   
   IF NOT EXISTS(SELECT BoxId FROM rvlfBoxSettings WHERE BoxId=@intBoxId)  
    BEGIN  
     INSERT INTO rvlfBoxSettings(BoxId, BoxProtocolTypeId, CommModeId, FwID)  
      VALUES(@intBoxId,NULL,NULL,NULL)       
    END  
     END  
END  
  
  
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveVehicleInfo_New]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
      
      
CREATE PROCEDURE [dbo].[rvlf_sp_SaveVehicleInfo_New]                
/*************************************************************************************************************/                
-- Name     : rvlf_sp_SaveVehicleInfo                
-- Description : To insert / update the vehicle information                
-- Author      : M. Jebamalai Jaya Chitra.                
-- Company     : Angler Technologies                
-- History     : <<Date(dd-MON-yyyy)>> Initial Reason                
--      : 28-Sep-2009 MJJC Created Intial Version                 
-- Updated by  : V.Narayanasamy / Adding display name                  
--             : Kumuthini. L / 20-Nov-09 / Inserting the vehicles into the                 
--               default Fleet of an Organization                
--      : 16-Jan-10 MJJC To have the default values in the rvlfMsgInHst and rvlfBoxID                
--             : In order to show the same in the monitor and dashboard pages                
--      : 06-Feb-2010 MJJC To have N/A for the Street Address and Landmark                
--      : 18-Mar-2010 VN To add the sensor details                
--      : 30-Mar-2010 MJJC To include the message severity for the vehicles to have default values                
--             : 22-July-2010 VN Added the vehicle category field.                
--             : 28-july-2010 VN Added the vehicle insurance,permit and fc expired dates.                
--             : 14-Oct-2011 Sakthi - Add Maximum SMS Limit              
--             : 19-Dec-2011 Sakthi - Change datatype varchar to nvarchar for vehiclename            
--             : 23-Jan-2012 Sakthi - Add internal number for vehicle information          
--             : 11-Sep-2013 Gopal  - Add installed date for vehicle information      
/*************************************************************************************************************/                
 @intBoxId           int      = Null,                
 @bigVehicleId  bigint   = Null,                
 @tiVehicleTypeID tinyint   = Null,                
 @vcVehicleName  nvarchar(20)  = Null,                
 @siMakeID   smallint  = Null,                
 @vcIntNo    varchar(20)  = Null,            
 @vcVIN    varchar(20)  = Null,                
 @siModelID   smallint  = Null,                
 @vcLicensePlate  varchar(20)  = Null,                
 @siYear    smallint  = Null,                
 @bigTimeZoneId  bigint = 3,                
 @vcColor   varchar(20) = Null,                
 @bitNotify   bit = 0,                
 @bitWarning   bit = 0,                
 @bitCritical  bit = 0,                
 @bigProcessedBy  bigint = Null,                
 @dtProcessedDateTime DateTime,                
 @bigOrganizationId bigint,                
 @tblNotificationsList XML = null,                
 @displayName  varchar(10)=Null,                
 @vcLocation   varchar(200)=null,                
 @vcCategory   varchar(5)=null,                
 @dtInsuranceExpired datetime=null,                
 @dtPermitExpired datetime=null,                
 @dtFcExpired datetime=null,                
 @dtPurchasedDate datetime=null,                
 @intOpeningEngineHrs int=null,                
 @intFuelTankCapacity int=null,              
 @maxSMSLimit tinyint = null,      
 @vcVehicleName_ar nvarchar(20)  = Null,  
 @installeddate datetime=null ,
 @intVehicleOwnership int = null,
 @intCapacityValue bigint = null,
 @intCapacityUnit int =null,
 @intFuelTankCapcityUnits int = null,
 @intLifeSpan int = null,
 @dtInsuranceExpiryDate datetime = null,
 @dtLeaseExpiryDate datetime = null,
 @bitIsUnderWarranty bit = null,
 @dtWarrantyExpiryDate datetime = null,
 @IsDocumentsUploaded	bit = null
AS                      
                
BEGIN                       
                
 SET NOCOUNT ON                
                 
 IF @intFuelTankCapacity = 0                
 BEGIN                
                 
  SET @intFuelTankCapacity = NULL                
                 
 END                
                 
 IF @bigVehicleId IS NOT NULL                
 BEGIN                
  IF EXISTS(SELECT * FROM rvlfVehicle WHERE VehicleId=@bigVehicleId AND OrganizationId= @bigOrganizationId)                
  BEGIN                
   UPDATE rvlfVehicle SET                
    VehicleTypeId =@tiVehicleTypeID,                
    VehicleDescription=@vcVehicleName,                
    MakeId=@siMakeID,          
    InternalNo=@vcIntNo,                
    Vin=@vcVIN,                
    ModelId=@siModelID,                
    LicensePlate=@vcLicensePlate,                
    ModelYear= @siYear,                
	TimeZone=@bigTimeZoneId,                
    Color=@vcColor,                
    Notify=@bitNotify,                
    Warning=@bitWarning,                
    Critical=@bitCritical,                
    OrganizationId= @bigOrganizationId,                
    ModifiedBy=@bigProcessedBy,                
    DisplayName=@displayName,                 
    [Modified DateTime] = @dtProcessedDateTime,                
	location=@vcLocation,                
    category=@vcCategory,                
    LastInsuranceExpired =@dtInsuranceExpired,                
    LastFCDate=@dtFcExpired,                
	LastPermitExpired =@dtPermitExpired,                
    PurchasedDate =@dtPurchasedDate,                
    OpeningEngineHours =@intOpeningEngineHrs,                
    TankCapacity =@intFuelTankCapacity,  
    CapacityUnits = @intFuelTankCapcityUnits,
	InstalledDate =ISNULL(@installeddate,InstalledDate) , 
	VehicleOwnership=@intVehicleOwnership,
	CapacityValue=@intCapacityValue,
	CapacityUnit=@intCapacityUnit,
	LifeSpan = @intLifeSpan,
	InsuranceExpiryDate = @dtInsuranceExpiryDate,
	LeaseExpiryDate = @dtLeaseExpiryDate,
	IsUnderWarranty = @bitIsUnderWarranty,
	WarrantyExpiryDate = @dtWarrantyExpiryDate,
	IsDocumentsUploaded = @IsDocumentsUploaded  
    --VehicleDescription_Ar=@vcVehicleName_ar                
   WHERE VehicleId = @bigVehicleId            
   DECLARE @docHandle int           
   DECLARE  @temptable TABLE (UserID Bigint,Email bit,SMS bit)        
            
    IF @tblNotificationsList IS NOT NULL         
  BEGIN                        
        
   EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblNotificationsList                                 
        
  INSERT INTO @tempTable                                              
        
   SELECT * FROM OPENXML(@docHandle, '/DocumentElement/Notification')       
   WITH         
   (                 
        
 UserID bigint 'UserID'                
        
   ,Email  bit  'Email'                                          
        
   ,SMS bit  'SMS'        
   )              
END        
 declare @tblNotificationsListTmp As NotificaitonUserList       
 insert into  @tblNotificationsListTmp      
 select * from @temptable         
       
   --F @maxSMSLimit IS NOT NULL               
   --BEGIN              
  --Update rvlfBoxId SET MaxSMSLimit=@maxSMSLimit WHERE BoxId=@intBoxId and OrganizationId= @bigOrganizationId              
  -- END              
                   
   DELETE FROM rvlfNotificationList WHERE TypeID = @bigVehicleId AND NotificationType = 4                
   exec rvlf_sp_Save_notificationsList @tblNotificationsListTmp,4,@bigVehicleId            
                   
  END                
  ELSE                
  BEGIN                
   raiserror('Vehicle information dosen''t exists !',16,1)                
  END                
 END                
 ELSE                
  BEGIN                
                       
        -- Insert the Vehicle informations into the Vehicle Table                
  INSERT INTO rvlfVehicle (InternalNo, Vin, LicensePlate, MakeId, ModelId, VehicleTypeId, StateProvince, ModelYear, Color, VehicleDescription, OrganizationId, 
							IconTypeId, TimeZone, DayLightSaving, Notify, Critical, Warning, AutoAdjustDayLightSaving, CreatedBy,CreatedDateTime,DisplayName,
							location,category,LastFCDate,LastInsuranceExpired,LastPermitExpired,IsEmailSent,IsSMSSent,PurchasedDate,OpeningEngineHours,
							TankCapacity,CapacityUnits,RptInterval,SpdThreshold,InstalledDate,VehicleOwnership,CapacityValue,CapacityUnit, 
							LifeSpan, InsuranceExpiryDate, LeaseExpiryDate, IsUnderWarranty, WarrantyExpiryDate, IsDocumentsUploaded)                 
  VALUES (@vcIntNo, @vcVIN, @vcLicensePlate, @siMakeID, @siModelID, @tiVehicleTypeID, 'Tamil Nadu', @siYear, @vcColor, @vcVehicleName, @bigOrganizationId,
		 1, @bigTimeZoneId, 0, @bitNotify, @bitCritical, @bitWarning, 0, @bigProcessedBy, @dtProcessedDateTime,@displayName,@vcLocation,@vcCategory,
		 @dtFcExpired,@dtInsuranceExpired,@dtPermitExpired,0,0,@dtPurchasedDate,@intOpeningEngineHrs,@intFuelTankCapacity,@intFuelTankCapcityUnits,
		 '00:10:00',100,@installeddate,@intVehicleOwnership,@intCapacityValue,@intCapacityUnit,@intLifeSpan, @dtInsuranceExpiryDate,@dtLeaseExpiryDate, 
		 @bitIsUnderWarranty, @dtWarrantyExpiryDate, @IsDocumentsUploaded)                

                        
        SET @bigVehicleId = (SELECT IDENT_CURRENT('rvlfVehicle'))                
                        
        EXEC rvlf_sp_Save_notificationsList @tblNotificationsListTmp,4,@bigVehicleId                
                        
        -- Insert the created vehicle with its Box Id in the Vehicle Assignment Table                
        INSERT INTO rvlfVehicleAssignment (BoxId, VehicleId, AssingedBy, AssignedDateTime, ServiceID)                
        VALUES (@intBoxId, @bigVehicleId, @bigProcessedBy, @dtProcessedDateTime, 1)                
                        
        -- Select the Default Fleet Id for the particular Organization                
      
        DECLARE @bigDefaultFleetId AS BIGINT = 0                
                        
        SELECT @bigDefaultFleetId = FleetId FROM rvlfFleet WHERE OrganizationId = @bigOrganizationId AND IsDefault = 1                
                        
        -- Assign the created vehicle into default fleet of the particular Organization                
                        
         INSERT INTO rvlfFleetVehicles (FleetId, VehicleId, IsActive, AssignedBy, AssignedDate)                
        VALUES (@bigDefaultFleetId, @bigVehicleId, 1 , @bigProcessedBy, @dtProcessedDateTime)                
                        
        DECLARE @uiMsgInID uniqueidentifier = NEWID()                
                
   INSERT INTO rvlfMsgInHst (MessageInID, BoxId, OriginDateTime, DateTimeReceived,ServiceID, BoxMsgInTypeId,                
   BoxProtocolTypeId, CommInfo1, CommInfo2, ValidGps, Latitude, Longitude, Speed, Heading, SensorMask, CustomProp,                
   StreetAddress, SequenceNum, IsArmed, NearestLandmark, Priority, IsNotificationSent, LandMarkID ) VALUES                 
   ( @uiMsgInID , @intBoxID, SYSUTCDATETIME(), SYSUTCDATETIME(),1,1,                
    1,NULL,NULL,1,0.000000,0.000000,0,0,'00000000','Odometer=1;Fuel%=0','N/A',NULL,0,'N/A',0,0,NULL)                
   
   IF NOT Exists(Select Boxid from rvlfBoxId where BoxId = @intBoxId)
	Begin      
   INSERT INTO rvlfBoxId (BoxId,FwChId,BoxArmed,LastValidDateTime,LastLatitude,LastLongitude,LastSpeed  
   ,LastStreetAddress,LastCommunicatedDateTime,LastSensorMask,OrganizationId,LastStatusDateTime,NearestLandmark,Heading,MessageInId)  
    VALUES (@intBoxID,NULL,0,SYSUTCDATETIME(),10.997237,76.987802,0,'N/A',                
    DATEADD(MI,3,SYSUTCDATETIME()),'00000000', @bigOrganizationID, DATEADD(MI,1,SYSUTCDATETIME()),                
    'N/A', 0, @uiMsgInID)                
    End                  
   
   INSERT INTO rvlfBoxMsgSeverity                 
    SELECT @intBoxID,b.BoxMsgInTypeId, p.DefaultAlarmLevel FROM rvlfBoxMsgInType b                 
     INNER JOIN rvlfBoxProtocolMsgInType p ON b.BoxMsgInTypeId = p.BoxMsgInTypeId                
    WHERE b.OperationTypeID IN                 
    (SELECT OperationID FROM rvlfPackageOperations WHERE PackageId =                 
    (SELECT PackageId FROM rvlfOrganizationPackage WHERE OrganizationID = (SELECT OrganizationID                 
    FROM rvlfVehicle v INNER JOIN rvlfVehicleAssignment va ON v.VehicleID = va.VehicleID                 
     WHERE va.BoxID = @intBoxID) AND IsActive=1))                
    AND b.CanSeveritySet = 1 AND b.BoxMsgInTypeId NOT IN                 
    (SELECT BoxMsgInTypeId FROM rvlfBoxMsgSeverity WHERE BoxId = @intBoxID)                
                    
     END                

	 SELECT @bigVehicleId

END 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SaveWidgets]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_SaveWidgets]  
@UserId int,  
@ColumnId int,  
@SortNo int,  
@Collapsed int,  
@Title varchar(100)  
AS  
/******************************************************    
Stored Procedure Name : rvlf_sp_SaveWidgets
Purpose     : Retrieve the column id for configuration panel  
Created by    : Sakthi Gopinath S  
*******************************************************/
BEGIN  
SET NOCOUNT ON  
 IF NOT EXISTS(SELECT ColumnId FROM rvlfWidgets WHERE Title=@Title and UserId = @UserId)  
 BEGIN  
  INSERT INTO rvlfWidgets(UserId,ColumnId,SortNo,Collapsed,Title)   
  VALUES(@UserId,@ColumnId,@SortNo,@Collapsed,@Title)  
 END  
 ELSE  
 BEGIN  
  UPDATE rvlfWidgets SET ColumnId=@ColumnId,SortNo=@SortNo,Collapsed=@Collapsed WHERE Title=@Title and UserId = @UserId  
 END  
SET NOCOUNT OFF  
END  


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ScheduledReqReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_ScheduledReqReport]  
   
 @dtRequisitionDate datetime=null,  
 @vcReportType varchar(7)=null,  
 @bigEmployeeId bigint=null,  
 @bigBranchId bigint=null,  
 @vcEmpidS varchar(max)=null  
  
AS  
/******************************************************************************/  
-- Name  : [rvlf_sp_ScheduledReqReport] '5/27/2010','pickup',961,1,'1196,1083,1086'  
-- Description : To get the scheduled vehicle requisition details.  
-- Author  : V.Narayanasamy  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 29-Dec-2009 VN Created Intial Version   
/******************************************************************************/  
BEGIN  
    
 DECLARE @tblTripSheetDetails TABLE  
(  
 EmployeeId bigint,  
 RouteId bigint,  
 OfficeAddressId bigint,  
 LocalityId bigint,  
 Distance numeric(10,6),  
 EmpDistance numeric(10,6),  
 OfficeLocationId bigint,  
 CabStartTime time(7),  
 PickupTimeForIntimation time(7),  
 DisplayName varchar(100),  
 RequisitionService bigint,  
 LoginTime time(7),  
 FromAddress varchar(200),  
 LandmarkName varchar(100),  
 MobileNo varchar(15),  
 PickupTime time(7),  
 TripId bigint,  
 Assign int,  
 Tracking varchar(100),  
 TrackingDetails varchar(100),  
 VehicleName varchar(100),  
 SequenceNo int  
   
   
)  
 IF(@vcReportType='Pickup')  
  BEGIN  
     
   INSERT INTO @tblTripSheetDetails(EmployeeId,DisplayName,RequisitionService,LoginTime,FromAddress,LandmarkName,  
      MobileNo,TripId,LocalityId,OfficeLocationId,OfficeAddressId,Tracking,TrackingDetails)  
   SELECT  sv.EmployeeId,e.DisplayName, sv.RequisitionId,es.ShiftIn,sv.FromAddress,l.LocalityName AS LandmarkName ,  
     e.MobileNo,(SELECT MAX(TripSheetId)FROM rvlfTripSheetGeneration   
     WHERE TripDate=@dtRequisitionDate AND TripType=@vcReportType AND TripGeneratedBy=@bigEmployeeId    
      AND CONVERT(DATE,TripGeneratedDate)=CONVERT(DATE,GETDATE())),e.LocalityId,ol.LocationId,oa.AddressId,  
      LEFT(es.Tracking,CHARINDEX(',',ES.Tracking)-1),SUBSTRING(es.Tracking,CHARINDEX(',',ES.Tracking)+1,LEN(ES.Tracking))  
      
    FROM rvlfScheduledVehicleRequisition sv   
     INNER JOIN rvlfEmployeeShifts es on es.EmployeeId =sv.EmployeeId        
     INNER JOIN rvlfEmployee e on e.EmployeeID=sv.EmployeeId   
     INNER JOIN rvlfOfficeAddress oa on oa.AddressId =e.OrgId     
     LEFT OUTER JOIN rvlfLocalityMaster l ON l.LocalityId=sv.LocalityId    
     LEFT OUTER JOIN rvlfOfficeLocation ol ON ol.LocationId=oa.LocationId     
    WHERE (@vcEmpidS IS NULL OR e.EmployeeID IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcEmpidS,',')))    
     AND (@dtRequisitionDate IS NULL OR (@dtRequisitionDate>=RequisitionFromDate and @dtRequisitionDate<=RequisitionToDate))  
     AND Approval!='R'  
     AND es.ShiftDate =@dtRequisitionDate  
     AND sv.Closed=0  
     AND (sv.RequisitionService='Both' OR sv.RequisitionService='Pickup')  
     AND es.Leave=0   
     AND (@bigBranchId IS NULL OR @bigBranchId='' OR e.OrgId =@bigBranchId)  
     AND(ISDELETED=0)  
     AND(Available=1)  
    ORDER BY e.DisplayName          
       
  END  
  ELSE  
   BEGIN  
    --INSERT INTO @tblTripSheetDetails(EmployeeId,DisplayName,RequisitionService,LoginTime,FromAddress,LandmarkName,  
    --  MobileNo,TripId,Tracking,TrackingDetails)  
    --SELECT  sv.EmployeeId,e.DisplayName, sv.RequisitionId as RequisitionService,es.ShiftOut as LoginTime,  
    --  sv.FromAddress,l.LocalityName AS LandmarkName,e.MobileNo,(SELECT MAX(TripSheetId)FROM rvlfTripSheetGeneration   
    --   WHERE TripDate=@dtRequisitionDate AND TripType=@vcReportType   
    --    AND CONVERT(DATE,TripGeneratedDate)=CONVERT(DATE,GETDATE())) AS TripId,  
    --   LEFT(es.Tracking,CHARINDEX(',',ES.Tracking)-1),SUBSTRING(es.Tracking,CHARINDEX(',',ES.Tracking)+1,LEN(ES.Tracking))  
    --  FROM rvlfScheduledVehicleRequisition sv   
    --   INNER JOIN rvlfEmployeeShifts es on es.EmployeeId =sv.EmployeeId  
    --   INNER JOIN rvlfOfficeAddress oa on oa.AddressId =sv.ToAddress    
    --   INNER JOIN rvlfEmployee e on e.EmployeeID=sv.EmployeeId   
    --   LEFT OUTER JOIN rvlfLocalityMaster  l ON l.LocalityId=e.LocalityId    
         
    --  WHERE (@dtRequisitionDate IS NULL OR (@dtRequisitionDate>=RequisitionFromDate and @dtRequisitionDate<=RequisitionToDate))  
    --   AND Approval!='R'  
    --   AND es.ShiftDate =@dtRequisitionDate  
    --   AND sv.Closed=0  
    --   AND (sv.RequisitionService='Both' OR sv.RequisitionService='Drop')  
    --   AND es.Leave=0  
    --   AND (@bigBranchId IS NULL OR e.OfficeAddress=@bigBranchId)  
    --   AND(ISDELETED=0)  
    --   AND(Available=1)  
         
    --  ORDER BY e.DisplayName   
   INSERT INTO @tblTripSheetDetails(EmployeeId,DisplayName,RequisitionService,LoginTime,FromAddress,LandmarkName,  
      MobileNo,TripId,LocalityId,OfficeLocationId,OfficeAddressId,Tracking,TrackingDetails)  
   SELECT  sv.EmployeeId,e.DisplayName, sv.RequisitionId,es.ShiftOut,sv.FromAddress,l.LocalityName AS LandmarkName ,  
     e.MobileNo,(SELECT MAX(TripSheetId)FROM rvlfTripSheetGeneration   
     WHERE TripDate=@dtRequisitionDate AND TripType=@vcReportType AND TripGeneratedBy=@bigEmployeeId    
      AND CONVERT(DATE,TripGeneratedDate)=CONVERT(DATE,GETDATE())),e.LocalityId,ol.LocationId,oa.AddressId,  
      LEFT(es.Tracking,CHARINDEX(',',ES.Tracking)-1),SUBSTRING(es.Tracking,CHARINDEX(',',ES.Tracking)+1,LEN(ES.Tracking))  
      
    FROM rvlfScheduledVehicleRequisition sv   
     INNER JOIN rvlfEmployeeShifts es on es.EmployeeId =sv.EmployeeId        
     INNER JOIN rvlfEmployee e on e.EmployeeID=sv.EmployeeId   
     INNER JOIN rvlfOfficeAddress oa on oa.AddressId =e.OrgId     
     LEFT OUTER JOIN rvlfLocalityMaster l ON l.LocalityId=sv.LocalityId    
     LEFT OUTER JOIN rvlfOfficeLocation ol ON ol.LocationId=oa.LocationId     
    WHERE (@vcEmpidS IS NULL OR e.EmployeeID IN(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcEmpidS,',')))    
     AND (@dtRequisitionDate IS NULL OR (@dtRequisitionDate>=RequisitionFromDate and @dtRequisitionDate<=RequisitionToDate))  
     AND Approval!='R'  
     AND es.ShiftDate =@dtRequisitionDate  
     AND sv.Closed=0  
     AND (sv.RequisitionService='Both' OR sv.RequisitionService='Drop')  
     AND es.Leave=0   
     AND (@bigBranchId IS NULL OR e.OrgId =@bigBranchId)  
     AND(ISDELETED=0)  
     AND(Available=1)  
    ORDER BY e.DisplayName    
   END  
     
SELECT * FROM @tblTripSheetDetails order by PickupTime -- where RouteId=2 order by Distance desc   
   
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_SearchEmployee]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[rvlf_sp_SearchEmployee]
	@bigEmployeeID bigint=null, 
	@vcEmployeeName varchar(50)=null,
	@bigOrganizationID bigint=null,
	@bigDivisionID bigint=null,
	@bigDepartmentID bigint=null,
	@bigShiftID bigint=null
AS
/******************************************************************************/
--	Name		:	rvlf_sp_SearchEmployee  null, null, 3
--	Description	:	To get the employee details based on the search criteria
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	27-Oct-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
	SELECT  e.EmployeeID,CASE WHEN e.Sex = 1 THEN 'MALE' ELSE 'FEMALE ' END as Gender, e.DisplayName,e.UserName , e.Latitude, e.Longitude, e.StreetAddress,e.EmailId ,
		dv.OrgDivisionName, d.DepartmentName,cast(e.Latitude as varchar) + ',' + cast(e.Longitude as varchar) as LatLng
		--lm.LocalityId,lm.LocalityName,lm.Latitude as LocalityLat,lm.Longitude as LocalityLong
	FROM rvlfEmployee e
		LEFT OUTER JOIN rvlfOrgDivision dv ON e.DivisionID = dv.OrgDivisionID
		LEFT OUTER JOIN rvlfOrgDepartment d ON e.DepartmentID = d.DepartmentID
		LEFT OUTER JOIN rvlfOrgShifts s ON e.ShiftID = s.ShiftID
		--LEFT OUTER JOIN rvlfLocalityMaster lm ON lm.LocalityId=e.LocalityId 
	WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID = '' OR orgid=@bigOrganizationID)
		--and EmployeeID=285
		AND(isdeleted=0)
		
	
	--SELECT DISTINCT lm.LocalityId,lm.LocalityName,lm.Latitude as LocalityLat,lm.Longitude as LocalityLong,null as UserName,null as StreetAddress,null as Gender
	--FROM rvlfEmployee e
	--	INNER JOIN rvlfOrgDivision dv ON e.DivisionID = dv.OrgDivisionID
	--	INNER JOIN rvlfOrgDepartment d ON e.DepartmentID = d.DepartmentID
	--	INNER JOIN rvlfOrgShifts s ON e.ShiftID = s.ShiftID
	--	LEFT OUTER JOIN rvlfLocalityMaster lm ON lm.LocalityId=e.LocalityId 
	--WHERE (@bigBranchId IS NULL OR OfficeAddress=@bigBranchId)
	--	AND(isdeleted=0)
	--ORDER BY lm.LocalityId 
	
	--SELECT LocalityId,LocalityName,Latitude as LocalityLat,Longitude as LocalityLong,null as UserName,null as StreetAddress,null as Gender
	--  FROM rvlfLocalityMaster 
	--  WHERE (@bigBranchId IS NULL OR BranchId=@bigBranchId)		
	--	ORDER BY LocalityId
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_StockIssuedDtlsReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================            
-- Author:  Anbarasu.E            
-- Create date: 12-09-2015            
-- Description: Stock Issued Details Report Query            
-- rvlf_sp_StockIssuedDtlsReport      2,null,'2015-01-06','2015-09-01',6,1      
-- rvlf_sp_StockIssuedDtlsReport      2,null,null,null,6,1      
-- =============================================            
CREATE PROCEDURE [dbo].[rvlf_sp_StockIssuedDtlsReport]      
 -- Add the parameters for the stored procedure here            
 @bigFleetID			BIGINT = NULL,                          
 @intBoxID				VARCHAR(MAX) = NULL,  
 @dtStartDate			DATETIME = NULL,  
 @dtEndDate				DATETIME = NULL,  
 @bigOrganizationID		BIGINT = NULL,  
 @bigQueryingUser		BIGINT = NULL  
AS            
BEGIN            
 -- SET NOCOUNT ON added to prevent extra result sets from            
 -- interfering with SELECT statements.            
 SET NOCOUNT ON;            
             
 DECLARE @dtFDate   datetime =@dtStartDate               
 DECLARE @dtEDate   datetime =@dtEndDate               
 DECLARE @HoursToBeAdded  INT = 0               
 DECLARE @MinsToBeAdded  INT = 0               
 DECLARE @DefaultDateFormat INT = 0               
                             
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                                                      
		@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	(@bigQueryingUser IS NULL OR @bigQueryingUser='' OR up.UserId = @bigQueryingUser)                                              
 SET	@dtStartDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtStartDate))                     
 SET	@dtEndDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@dtEndDate))               
            
 --Report Details  
 DECLARE @OrderRequest Table(ItemCode varchar(50), ItemName varchar(150), AvailQty int,           
   ItemCategoryName varchar(150), RequestQty int, IssuedQty int, OrderNo bigint)          
           
 INSERT INTO @OrderRequest          
 SELECT IM.ItemCode, IM.ItemName, IM.AvailQty, IC.ItemCategoryName,           
		ISNULL(ORI.ReqQty,0) RequestQty, ISNULL(ORI.IssuedQty,0) IssuedQty,          
		ORQ.OrderNo
 FROM	rvlfInvItemMaster IM          
 INNER	JOIN rvlfItemCategory IC ON IM.ItemCatID = IC.ItemCatID          
 INNER	JOIN rvlfInvOrderReqItems ORI ON IM.Itemcode = ORI.Itemcode          
 INNER	JOIN rvlfInvOrderRequest ORQ ON ORI.OrderNo = ORQ.OrderNo          
 WHERE	ORI.IsDelete = 0	and		ORQ.Status = 'A'
 and	(@bigOrganizationID IS NULL OR @bigOrganizationID='' OR ORQ.OrganizationID=@bigOrganizationID)          
 and	(@bigFleetID IS NULL OR @bigFleetID=0 OR IM.ItemCatID=@bigFleetID)       
 and	(@dtStartDate IS NULL OR @dtStartDate='' OR @dtEndDate IS NULL OR @dtEndDate='' OR ORQ.OrderDate BETWEEN @dtStartDate AND @dtEndDate)           
     
 SELECT ItemCode, ItemName, ItemCategoryName, COUNT(OrderNo) NoofORNs, SUM(RequestQty) NoofReqQty,SUM(IssuedQty) NoofIssuedQty,      
		Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,cast(@dtFDate as time),22) as PasStartDate,               
		Convert(varchar,@dtEDate,@DefaultDateFormat)+ ' ' + Convert(varchar,cast(@dtEDate as Time),22) as PasEndDate,           
		AvailQty CurrentStock,Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '       
		+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate        
 FROM	@OrderRequest        
 GROUP	BY ItemCode,ItemName,ItemCategoryName,AvailQty    
   
 ------------------------------------------------------------------------------------------------------------------------------------  
 --Report Summary  
   
 --DECLARE @ItemWise Table (ItemCategoryName varchar(150), NoofORNs int, NoofReqQty int, NoofIssuedQty int, CurrentStock int)          
  
 --Insert into @ItemWise      
 --SELECT ItemCategoryName,COUNT(OrderNo) NoofORNs, SUM(RequestQty) NoofReqQty,SUM(IssuedQty) NoofIssuedQty, AvailQty CurrentStock  
 --FROM @OrderRequest     
 --GROUP BY ItemCategoryName,AvailQty  
   
 --SELECT ItemCategoryName,COUNT(NoofORNs) TotalNoofORNs, SUM(NoofReqQty) TotalNoofReqQty,SUM(NoofIssuedQty) TotalNoofIssuedQty, Sum(CurrentStock) TotalCurrentStock  
 --FROM @ItemWise          
 --Group BY ItemCategoryName          

 ------------------------------------------------------------------------------------------------------------------------------------  
       
            
  --Select * from rvlfInvOrderReqItems Where Itemcode = 'TOO00003'      
  --Select * from rvlfInvOrderRequest   orq   inner join     rvlfInvOrderReqItems ori on orq.OrderNo = ori.OrderNo Where orq.Status='A'
  --Select * from rvlfInvItemMaster        
  --Select * from rvlfItemCategory     
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_StudentsTravelledReport]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==========================================================================================
-- Author:		Anbarasu.E
-- Create date: 04-03-2016
-- Description:	Get data for Travelled Students Head Count Report
--				rvlf_sp_StudentsTravelledReport 480,'0','2016-01-09 08:00:00','2016-01-18 20:00:00',230,576
-- ==========================================================================================
CREATE PROCEDURE [dbo].[rvlf_sp_StudentsTravelledReport] 
	-- Add the parameters for the stored procedure here
	@bigFleetID			bigint = NULL,                        
	@intBoxID			varchar(max) = NULL,
	@dtStartDate		datetime = NULL,
	@dtEndDate			datetime = NULL,
	@bigOrganizationID  bigint = NULL,
	@bigQueryingUser	bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    DECLARE @dtFDate   datetime = @dtStartDate
	DECLARE @dtEDate   datetime = @dtEndDate
	DECLARE @HoursToBeAdded  INT = 0
	DECLARE @MinsToBeAdded  INT = 0
	DECLARE @DefaultDateFormat INT = 0

	SELECT	@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                                                      
			@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		(@bigQueryingUser IS NULL OR @bigQueryingUser='' OR up.UserId = @bigQueryingUser)                                              

	SET		@dtStartDate = DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),@dtStartDate))                     
	SET		@dtEndDate = DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),@dtEndDate))

	--SELECT @dtFDate,@dtEDate,@dtStartDate,@dtEndDate,@HoursToBeAdded,@MinsToBeAdded

	DECLARE @TblStudHeadCount TABLE (SNo bigint PRIMARY KEY, StudentId bigint, VehicleId bigint, BoxId bigint, EntryExitTime Datetime, GeozoneId bigint,
									 TripDesc varchar(10), RFID nvarchar(40), MsgType int, TotalTravelledHeadCount int, AssignedStatus int, 
									 AssignedTravelled int, UnAssignedTravelled int, VehicleDescription Varchar(20),Vin Varchar(20),LicensePlate Varchar(20))

	Insert	Into @TblStudHeadCount
	Select	SNo,StudentId, rfid.VehicleID, BoxId, DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),EntryExitTime)), 
			GeozoneID, NULL, RFID, MsgType, HeadCount, CASE WHEN StudentMasterId IS NULL THEN 0 ELSE 1 END, NULL, NULL, 
			V.VehicleDescription, V.Vin, V.LicensePlate 
	From	rvlfRFIDSchoolSMSNotification rfid
	Left	Outer Join rvlfStudentVehicleAssignment sva On rfid.VehicleID = sva.VehicleId and rfid.StudentID = sva.StudentMasterId
	Inner	Join rvlfFleetVehicles FV On rfid.VehicleId = FV.VehicleId
	Inner	Join rvlfVehicle V On rfid.VehicleID = V.VehicleId
	Where	--EntryExitTime Between @dtFDate and @dtEDate
	DATEADD(HOUR,(@HoursToBeAdded*1),DATEADD(MINUTE,(@MinsToBeAdded*1),EntryExitTime)) Between @dtFDate and @dtEDate
	--Between '2015-09-01' /*CAST(GETUTCDATE()-150 AS DATE)*/ and CAST(GETUTCDATE() AS DATE) 
	--and	MsgType = 7
	and		(@bigFleetID IS NULL OR @bigFleetID=0 OR FV.FleetId = @bigFleetID) 
	and		(@intBoxID IS NULL OR @intBoxID = '' OR @intBoxID = '0'  or BoxId in (select * from rvlf_fn_ConvertArrayToTable(@intBoxID,',')))
	and     (@bigOrganizationID IS NULL OR @bigOrganizationID = '' OR rfid.OrganizationId=@bigOrganizationID)

	DECLARE @minSno bigint, @prev bigint, @AssignedTravelled int, @UnAssignedTravelled int, @TripDesc Varchar(10)
	
	SELECT	@minSno = MIN(Sno) From @TblStudHeadCount Where MsgType = 7
	WHILE @minSno IS NOT NULL
	BEGIN

		Select	@TripDesc = CASE MsgType WHEN 1 THEN 'IN' WHEN 2 THEN 'OUT' END From @TblStudHeadCount 
		Where	SNo Between @prev and @minSno and MsgType IN (1,2) Group By MsgType
		
		Select	@AssignedTravelled = Count(*) From @TblStudHeadCount
		Where	SNo Between @prev and @minSno and MsgType IN (1,2) and AssignedStatus = 1
		Select	@UnAssignedTravelled = Count(*) From @TblStudHeadCount
		Where	SNo Between @prev and @minSno and MsgType IN (1,2) and AssignedStatus = 0	

		Update	@TblStudHeadCount 
		Set		AssignedTravelled = (TotalTravelledHeadCount - @UnAssignedTravelled), 
				UnAssignedTravelled = @UnAssignedTravelled, TripDesc = ISNULL(@TripDesc,'IN')
		Where	Sno = @minSno

		SET		@prev = @minSno
		SELECT	@minSno = MIN(SNo) From @TblStudHeadCount Where MsgType = 7 and SNo > @minSno

	END

	Select	ROW_NUMBER() OVER (ORDER BY SNO) TripNo, *, (NoofAssignedStudents - AssignedTravelled) as AssignedButNotTravelled FROM 
	(Select	SNo, StudentId, VehicleId, BoxId, EntryExitTime EntryExit, Convert(varchar,sth.EntryExitTime) EntryExitTime, GeozoneId, TripDesc, RFID, MsgType,
			TotalTravelledHeadCount, AssignedTravelled, UnAssignedTravelled, VehicleDescription, Vin, LicensePlate,
			(Select GeozoneName + ' ' + TripDesc From rvlfOrganizationGeozone Where GeozoneId = sth.GeozoneId and OrganizationId = @bigOrganizationID) TripDetails,
			(Select Count(StudentMasterId) From rvlfStudentVehicleAssignment Where VehicleId = sth.VehicleId) NoofAssignedStudents,
			Convert(varchar,@dtFDate,@DefaultDateFormat) + ' ' + Convert(varchar,CAST(@dtFDate as time),22) as PasStartDate,       
			Convert(varchar,@dtEDate,@DefaultDateFormat) + ' ' + Convert(varchar,CAST(@dtEDate as Time),22) as PasEndDate,       
			Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat) + ' ' + 
			Convert(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate 
	From	@TblStudHeadCount sth
	Where	MsgType = 7) tblTempStudCount
	Order	By	EntryExitTime

END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_TestPaging]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_TestPaging]
	@intPageNo int,
	@maxRows int,
	@vcsortColumn varchar(30) = 'Autoid',
	@vcDirection varchar(5) = 'A'
AS
BEGIN
	DECLARE @HoursToBeAdded INT = 0
	DECLARE @MinsToBeAdded INT = 0
	DECLARE @ConversionFactor numeric (10,2) = 1.0
	DECLARE @startdate datetime = '2009-08-01'
	DECLARE @enddate datetime = '2009-08-20'
	--DECLARE @intPageNo int = 1
	--DECLARE @intSortColumn int = 3
	DECLARE @intType int =0
	
	select top (@maxRows) *
	FROM (
	select ROW_NUMBER() over(Order by [TIMESTAMP] DESC) as  Autoid, * from (
	select H.MessageInID, VA.BoxID as DeviceID, ValidGPS, cast(H.Latitude as decimal(14,6)) as Latitude, cast(H.Longitude as decimal(14,6)) as Longitude,                
    H.NearestLandMark as Distance, 
    CAST((CAST(Speed as int) * @ConversionFactor) as varchar) + CASE WHEN  @ConversionFactor = 0.62 THEN ' miles/hr' ELSE ' km/hr' END as Speed, 
    Heading, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [Timestamp], 
    VehicleDescription, BoxMsgInTypeName as Message, H.BoxMsgInTypeId as BoxMsgInTypeId ,
		CASE WHEN H.BoxMsgInTypeID in (11 , 2 , 3 , 13 , 9 , 14 , 15 , 16 , 17 , 24 , 18)
				THEN dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId ,H.MessageInId ,H.OriginDateTime)
				WHEN H.BoxMsgInTypeId IN (5,6) THEN
					dbo.rvlf_fn_GetAlarmDetails(CAST( SUBSTRING(H.CustomProp,
					CHARINDEX('=',H.CustomProp,1)+1,(CHARINDEX(';',H.CustomProp,1)
					- CHARINDEX('=',H.CustomProp,1))-1) as bigint), H.BoxMsgInTypeId,H.BoxId ,H.MessageInId ,H.OriginDateTime)
			ELSE CT.BoxMsgInTypeDesc 
			END as MessageDetails,	CASE 
				WHEN H.ValidGps > 1 OR H.BoxMsgInTypeId IN (9, 14,15,16,17,24) then '-'
				WHEN H.Heading between 335 and 360 THEN 'N' 
				 WHEN H.Heading between 0 and 25 THEN 'N' 
				WHEN H.Heading between 25 and 65 THEN 'NE' 
				WHEN H.Heading between 65 and 115 THEN 'E' 
				WHEN H.Heading between 115 and 155 THEN 'SE' 
				WHEN H.Heading between 155 and 210 THEN 'S' 
				WHEN H.Heading between 210 and 245 THEN 'SW' 
				WHEN H.Heading between 245 and 300 THEN 'W' 
				WHEN H.Heading between 300 and 335 THEN 'NW' END as Direction,
				0 as UserID,0 as Priority,NULL as Acknowledged, case WHEN (H.LandMarkID IS NULL or H.LandMarkID = 0) THEN H.StreetAddress ELSE L.LandmarkName END as Address
from rvlfMsgInHst H LEFT OUTER JOIN rvlfLandmark L on H.LandMarkID = L.LandmarkID INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = H.BoxID         
    INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID          
    INNER JOIN rvlfBoxMsgInType CT on CT.BoxMsgInTypeId = H.BoxMsgInTypeID   
    where /*VA.VehicleId = @VehicleID and OriginDateTime between CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109)    
    and */ H.BoxMsgInTypeID NOT in (/*19,*/20,35,34,31) -- and datediff(ss, convert(datetime,'''+ CAST(@startdate as varchar) + '''), convert(datetime,OriginDateTime))%' + cast(@interval as varchar)+' = 0     
    UNION ALL    
		select '00000000-0000-0000-0000-000000000000'  as MessageInID,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,'' as Speed, 0 as Heading,
		DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [Timestamp], 
		V.VehicleDescription,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId ,BoxcmdTypeDesc as MessageDetails,'' as Direction, UserID,Priority,Acknowledged,'N/A' as Address --into #tblFinal    
		from rvlfMsgOutHst OH        
		INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID        
		INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId     
		/*WHERE VA.VehicleID = @VehicleID and SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109) */) as a 
/*CASE WHEN @OrderBy = 'State'
AND @OrderByDirection = 'D'
THEN StateProvinceID END DESC,
CASE WHEN @OrderBy = 'State'
AND @OrderByDirection != 'D'
THEN StateProvinceID END,
CASE WHEN @OrderBy = 'City'
AND @OrderByDirection = 'D'
THEN City END DESC,
CASE WHEN @OrderBy = 'City'
AND @OrderByDirection != 'D'
THEN City END*/

		) as b

		where 
			(@intType=1  AND b.MessageInID = '00000000-0000-0000-0000-000000000000') or 
			(@intType = 2 AND b.MessageInID <> '00000000-0000-0000-0000-000000000000') or
			(@intType=3 AND (b.BoxMsgInTypeId = 11 and b.MessageInID <> '00000000-0000-0000-0000-000000000000')) or
			(@intType = 0) AND b.Autoid >=@intPageNo/*(100*)*/
							ORDER BY
								CASE WHEN @vcsortColumn  = 'TimeStamp' AND @vcDirection = 'D' THEN b.Timestamp  END DESC,
								CASE WHEN @vcsortColumn = 'TimeStamp' AND @vcDirection != 'A' THEN b.Timestamp END
		
		
	select SUM(a.dt) FROM 
		(select COUNT(OriginDateTime) as dt  FROM rvlfMsgInHst WHERE /*BoxId = 999222 and OriginDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109) and */BoxMsgInTypeID NOT in (/*19,*/20,35,34,31)
		union 
		select COUNT(SentDateTime) as dt FROM rvlfMsgOutHst -- WHERE BoxId = 999222 and SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)
		) as a
END

--rvlf_sp_TestPaging 0


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_TestWithoutPaging]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlf_sp_TestWithoutPaging]
	@intPageNo int = 0,
	@maxRows int = 0,
	@vcsortColumn varchar(30) = 'Autoid',
	@vcDirection varchar(5) = 'A'
AS
BEGIN
	DECLARE @HoursToBeAdded INT = 0
	DECLARE @MinsToBeAdded INT = 0
	DECLARE @ConversionFactor numeric (10,2) = 1.0
	DECLARE @startdate datetime = '2009-08-01'
	DECLARE @enddate datetime = '2009-08-20'
	--DECLARE @intPageNo int = 1
	--DECLARE @intSortColumn int = 3
	DECLARE @intType int =0
	
	select  *
	FROM (
	select ROW_NUMBER() over(Order by [TIMESTAMP] DESC) as  Autoid, * from (
	select H.MessageInID, VA.BoxID as DeviceID, ValidGPS, cast(H.Latitude as decimal(14,6)) as Latitude, cast(H.Longitude as decimal(14,6)) as Longitude,                
    H.NearestLandMark as Distance, 
    CAST((CAST(Speed as int) * @ConversionFactor) as varchar) + CASE WHEN  @ConversionFactor = 0.62 THEN ' miles/hr' ELSE ' km/hr' END as Speed, 
    Heading, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [Timestamp], 
    VehicleDescription, BoxMsgInTypeName as Message, H.BoxMsgInTypeId as BoxMsgInTypeId ,
		CASE WHEN H.BoxMsgInTypeID in (11 , 2 , 3 , 13 , 9 , 14 , 15 , 16 , 17 , 24 , 18)
				THEN dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId ,H.MessageInId ,H.OriginDateTime)
				WHEN H.BoxMsgInTypeId IN (5,6) THEN
					dbo.rvlf_fn_GetAlarmDetails(CAST( SUBSTRING(H.CustomProp,
					CHARINDEX('=',H.CustomProp,1)+1,(CHARINDEX(';',H.CustomProp,1)
					- CHARINDEX('=',H.CustomProp,1))-1) as bigint), H.BoxMsgInTypeId,H.BoxId ,H.MessageInId ,H.OriginDateTime)
			ELSE CT.BoxMsgInTypeDesc 
			END as MessageDetails,	CASE 
				WHEN H.ValidGps > 1 OR H.BoxMsgInTypeId IN (9, 14,15,16,17,24) then '-'
				WHEN H.Heading between 335 and 360 THEN 'N' 
				 WHEN H.Heading between 0 and 25 THEN 'N' 
				WHEN H.Heading between 25 and 65 THEN 'NE' 
				WHEN H.Heading between 65 and 115 THEN 'E' 
				WHEN H.Heading between 115 and 155 THEN 'SE' 
				WHEN H.Heading between 155 and 210 THEN 'S' 
				WHEN H.Heading between 210 and 245 THEN 'SW' 
				WHEN H.Heading between 245 and 300 THEN 'W' 
				WHEN H.Heading between 300 and 335 THEN 'NW' END as Direction,
				0 as UserID,0 as Priority,NULL as Acknowledged, case WHEN (H.LandMarkID IS NULL or H.LandMarkID = 0) THEN H.StreetAddress ELSE L.LandmarkName END as Address
from rvlfMsgInHst H LEFT OUTER JOIN rvlfLandmark L on H.LandMarkID = L.LandmarkID INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = H.BoxID         
    INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID          
    INNER JOIN rvlfBoxMsgInType CT on CT.BoxMsgInTypeId = H.BoxMsgInTypeID   
    where /*VA.VehicleId = @VehicleID and OriginDateTime between CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109)    
    and */ H.BoxMsgInTypeID NOT in (/*19,*/20,35,34,31) -- and datediff(ss, convert(datetime,'''+ CAST(@startdate as varchar) + '''), convert(datetime,OriginDateTime))%' + cast(@interval as varchar)+' = 0     
    UNION ALL    
		select '00000000-0000-0000-0000-000000000000'  as MessageInID,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,'' as Speed, 0 as Heading,
		DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [Timestamp], 
		V.VehicleDescription,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId ,BoxcmdTypeDesc as MessageDetails,'' as Direction, UserID,Priority,Acknowledged,'N/A' as Address --into #tblFinal    
		from rvlfMsgOutHst OH        
		INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID        
		INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId     
		/*WHERE VA.VehicleID = @VehicleID and SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109) */) as a 
/*CASE WHEN @OrderBy = 'State'
AND @OrderByDirection = 'D'
THEN StateProvinceID END DESC,
CASE WHEN @OrderBy = 'State'
AND @OrderByDirection != 'D'
THEN StateProvinceID END,
CASE WHEN @OrderBy = 'City'
AND @OrderByDirection = 'D'
THEN City END DESC,
CASE WHEN @OrderBy = 'City'
AND @OrderByDirection != 'D'
THEN City END*/

		) as b

		where 
			(@intType=1  AND b.MessageInID = '00000000-0000-0000-0000-000000000000') or 
			(@intType = 2 AND b.MessageInID <> '00000000-0000-0000-0000-000000000000') or
			(@intType=3 AND (b.BoxMsgInTypeId = 11 and b.MessageInID <> '00000000-0000-0000-0000-000000000000')) or
			(@intType = 0) /*AND b.Autoid >= @intPageNo(100*)*/
							ORDER BY
								CASE WHEN @vcsortColumn  = 'TimeStamp' AND @vcDirection = 'D' THEN b.Timestamp  END DESC,
								CASE WHEN @vcsortColumn = 'TimeStamp' AND @vcDirection != 'A' THEN b.Timestamp END
								
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_TriggerSMSBfrStops]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

                
CREATE Proc [dbo].[rvlf_sp_TriggerSMSBfrStops]    
 @intBoxID bigint,                       
  @dtOriginDateTime datetime,                         
  @vcCustomProp varchar(max)=null                      
as                      
BEGIN                      
--declare @intBoxID bigint=999983,                       
--  @dtOriginDateTime datetime= '2015-06-13 08:21:28.000',                       
-- -- @tiBoxMsgInTypeId TINYINT =114,                       
--  @vcCustomProp varchar(max)= '34;RouteID=114;StopID=64;NxtStopID=65;Duration(Mints)=5;Distance=3;AlertMsg=011'                      
                        
--if exists(select * from rvlfBoxId b inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId                      
--inner join rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1                      
--inner join rvlfPackageOperations po on op.PackageId=po.PackageId                      
--inner join rvlfOperationType ot on po.OperationID=ot.OperationTypeId                      
--where b.BoxId=@intBoxID and charindex('Pickup & Drop from unassigned',ot.OperationTypeName,1)>0 )                      
--begiN                      
--if(@tiBoxMsgInTypeId=114 and charindex('34;Routeid',@vcCustomProp,1)<>0)                      
--Begin  
   
declare @LiveRoute table (MessageInID uniqueidentifier,Boxid bigint,OriginDateTime datetime,CustomProp varchar(max), RouteId bigint,StopID bigint,NxtStopID bigint,AlertMsg varchar(3))              
                 
 INSERT INTO @LiveRoute                
 SELECT MessageInID,BoxId,OriginDateTime,CustomProp,                
 dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'RouteID=',';'), dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'StopID=',';'),                 
 dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'NxtStopID=',';'),dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'AlertMsg=',';')   
 FROM rvlfMsgInHst WHERE OriginDateTime > (                
SELECT MAX(OriginDateTime) FROM rvlfMsgInHst WHERE BoxId=@intBoxID and CustomProp like '%AlertMsg=100'                 
) and BoxId=@intBoxID and CustomProp like '%34;route%' and OriginDateTime < @dtOriginDateTime                
                
DECLARE @RouteId bigint,@stopID bigint,@NxtStop bigint,@duration bigint,@buffr bigint,@DestID bigint,@destdur bigint,@destbuff bigint,   
@seq int                
SELECT @RouteId=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RouteID=',';'),                
@stopID=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'StopID=',';'),                
@NxtStop=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'NxtStopID=',';'),                
@duration=cast(dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'Duration(Mints)=',';') as bigint)*60                
       
--select * from @LiveRoute       
           
if not exists (select * from @LiveRoute where RouteId=@RouteId and StopID=@stopID AND AlertMsg IN ('001','011'))                      
BegiN                
DECLARE @RouteTbl table (RouteDetailsId int,RouteID smallint,LndID int,SeqID tinyint,Distance varchar(100),                      
BufferTime int,DurationSec int)                      
                      
insert into @RouteTbl                      
select RouteDetailsId,RouteID,LndID,SeqID,Distance,BufferTime,DurationSec from rvlfRouteDetails where  RouteID=@RouteId                      
                      
select  @seq=SeqID from @RouteTbl where LndID=@NxtStop and RouteID=@RouteId                      
  --select * from @RouteTbl                    
--select * from @RouteTbl where SeqID in (@seq,@seq+1) and RouteID=@RouteId                      
Declare @MaxNextStop bigint                       
Select top 1 @MaxNextStop= LndID from @RouteTbl where SeqID in (@seq+1) and RouteID=@RouteId order by SeqID desc                      
Declare @TotStop table (Totval bigint,NextStop bigint)                
                
INSERT INTO @TotStop                    
SELECT SUM(cast(BufferTime as int)+cast(DurationSec as  int)) as Totval,@MaxNextStop from (                      
SELECT BufferTime,DurationSec,LndID,SeqID from @RouteTbl where SeqID in (@seq,@seq+1) and RouteID=@RouteId                      
) as A               
  --select * from @TotStop                
                   
if(dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'AlertMsg=',';')=001)           
BEGIN                    
INSERT INTO @TotStop                    
SELECT CAST(BufferTime as bigint)+CAST(DurationSec as bigint),LndID from @RouteTbl where LndID=@NxtStop and RouteID=@RouteId                    
end                    
                      
 INSERT INTO rvlfRFIDSchoolSMSNotification                  
SELECT s.StudentMasterID,SVA.VehicleId,VA.BoxId,@stopID,s.OrganizationID,@dtOriginDateTime,s.RFID,s.StudentFirstName + ' ' + s.StudentLastName ,s.ContactNo,                
('Dear Parent, \n ' + 'Name: '+ s.StudentFirstName +' '+ s.StudentLastName + ' \n Info: Bus will reach your stop '+OG.GeozoneName+' at '+ CAST((dbo.rvlf_fn_DayLightSavings_Date(DATEADD(SECOND,B.Totval,@dtOriginDateTime),                    
s.OrganizationID,TZ.HoursToBeAdded,TZ.MinToBeAdded,DATEADD(SECOND,B.Totval,@dtOriginDateTime))) as varchar(20))+' \n -Trinetra'),5,0,null,null
FROM rvlfStudentMaster s                       
inner join rvlfStudentVehicleAssignment SVA on s.StudentMasterID=SVA.StudentMasterId                      
inner join rvlfVehicleAssignment VA on SVA.VehicleId=VA.VehicleId                      
inner join @TotStop as B on s.GeozoneId=B.NextStop                    
inner join rvlfOrganizationGeozone OG on s.GeozoneId=OG.GeozoneId and OG.OrganizationId = S.OrganizationID                         
inner join rvlfOrganization O on O.OrganizationId = S.OrganizationID                                               
inner join rvlfTimeZones TZ on TZ.TimeZoneID = O.CountryId                  
--left join rvlfRFIDSchoolSMSNotification SN on (s.StudentMasterID = SN.StudentID and SN.EntryExitTime > DATEADD(MINUTE,-60,@dtOriginDateTime))                
WHERE VA.BoxId=@intBoxID and s.SMSSettings<>0 --and SN.Sno is null                
   EnD                
--End                      
--enD                      
END     
    
    

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_TriggerSMSforStudentRFIDSwipes]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Anbarasu.E	
-- Create date: 17-Jul-2015
-- Description:	Inserts RFID swipes of the students in Nofitication and Log tables for Sending SMS Notifications to registered Mobiles.
-- [rvlf_sp_TriggerSMSforStudentRFIDSwipes] 999990,'2015-07-18 12:20:47.000','Punch:000;RF_ID=0000004d0084c9ef;Odometer=1;','4ADF3A28-482D-E511-9A73-00219B712B2E'
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_TriggerSMSforStudentRFIDSwipes]
	-- Add the parameters for the stored procedure here
	@bigBoxID			BIGINT,               
	@dtOriginDateTime	DATETIME,                 
	@vcCustomProp		VARCHAR(MAX) = NULL,
	@uiMsgInID			UNIQUEIDENTIFIER
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT OFF;
	
	DECLARE	@RFID VARCHAR(1000)
	SET		@RFID = dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RF_ID=',';')
    -- Insert statements for procedure here
	INSERT	INTO	rvlfRFIDSchoolSMSNotification
			SELECT	s.StudentMasterID,SVA.VehicleId,VA.BoxId,S.GeozoneId,s.OrganizationID,@dtOriginDateTime,@RFID,s.StudentFirstName + ' ' + s.StudentLastName,
					s.ContactNo,('Dear Parent, \n' + s.StudentFirstName + ' ' + s.StudentLastName + ' made an entry in ' + OG.GeozoneName
					+ ' at '+ CAST((dbo.rvlf_fn_DayLightSavings_Date(DATEADD(SECOND,0,@dtOriginDateTime),s.OrganizationID,TZ.HoursToBeAdded,
					TZ.MinToBeAdded,DATEADD(SECOND,0,@dtOriginDateTime))) as varchar(20))+' \n -Trinetra'),6,0,null,null
			FROM	rvlfStudentMaster s               
			inner	join rvlfStudentVehicleAssignment SVA on s.StudentMasterID=SVA.StudentMasterId
			inner	join rvlfVehicleAssignment VA on SVA.VehicleId=VA.VehicleId
			inner	join rvlfOrganizationGeozone OG on s.GeozoneId=OG.GeozoneId and s.OrganizationId = OG.OrganizationID
			inner	join rvlfOrganization O on s.OrganizationId = O.OrganizationID
			inner	join rvlfTimeZones TZ on O.CountryId = TZ.TimeZoneID
			WHERE	VA.BoxId=@bigBoxID and s.RFID = @RFID and s.SMSSettings<>0 
	
	INSERT	INTO rvlf_StudentRFIDSMSMessegeInIDLog(StudentID,BoxiD,VehicleID,GeozoneId,OrganizationID,StatusType,EntryExit,RFID,MessageInID)
			SELECT	s.StudentMasterID,VA.BoxId,SVA.VehicleId,S.GeozoneId,s.OrganizationID,3,@dtOriginDateTime,@RFID,@uiMsgInID
			FROM	rvlfStudentMaster s
			inner	join rvlfStudentVehicleAssignment SVA on s.StudentMasterID=SVA.StudentMasterId
			inner	join rvlfVehicleAssignment VA on SVA.VehicleId=VA.VehicleId
			inner	join rvlfOrganizationGeozone OG on s.GeozoneId=OG.GeozoneId and s.OrganizationId = OG.OrganizationID
			inner	join rvlfOrganization O on s.OrganizationId = O.OrganizationID
			WHERE	VA.BoxId=@bigBoxID and s.RFID = @RFID and s.SMSSettings<>0	
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_TripDetails_adr]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author	  : Kalaivanan.E
-- Create date: 24-01-2018
-- Description:	To Log the Details For KPI Calculations(Contractor Open / HT_ON_OFF start and End Dates ) to [adr_rvlfTripDetails] Table
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_TripDetails_adr]
@BoxID varchar(20),
@ControllerID int,
@ControllerName varchar(50),
@BoxMsgInTypeId int,
@AlarmName varchar(50),
@dtOriginDateTime datetime,
@Status int
AS
BEGIN
	SET NOCOUNT ON;
	IF Exists(Select * From [dbo].[adr_rvlfTripDetails] Where BoxId = @BoxID AND ControllerID = @ControllerID AND BoxMsgInTypeId = @BoxMsgInTypeId AND ControllerName=@ControllerName AND AlarmName = @AlarmName)
	Begin
		IF (@Status=0)
		BEGIN
			Update [dbo].[adr_rvlfTripDetails] SET StartDate=@dtOriginDateTime WHERE BoxId = @BoxID AND ControllerID = @ControllerID AND BoxMsgInTypeId = @BoxMsgInTypeId AND ControllerName=@ControllerName And AlarmName = @AlarmName
		END
		ELSE
		BEGIN
			Update [dbo].[adr_rvlfTripDetails] SET EndDate=@dtOriginDateTime WHERE BoxId = @BoxID AND ControllerID = @ControllerID AND BoxMsgInTypeId = @BoxMsgInTypeId AND ControllerName=@ControllerName And AlarmName = @AlarmName
		END
	End
	Else
	Begin		
		IF (@Status=0)
		BEGIN
			Insert into [dbo].[adr_rvlfTripDetails](BoxId,ControllerID,ControllerName,BoxMsgInTypeId,AlarmName,StartDate) Values(@BoxID,@ControllerID,@ControllerName,@BoxMsgInTypeId,@AlarmName,@dtOriginDateTime)
		END
		ELSE
		BEGIN
			Insert into [dbo].[adr_rvlfTripDetails](BoxId,ControllerID,ControllerName,BoxMsgInTypeId,AlarmName,EndDate) Values(@BoxID,@ControllerID,@ControllerName,@BoxMsgInTypeId,@AlarmName,@dtOriginDateTime)
		END
	End
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UnAssignFleetUser]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UnAssignFleetUser]
	@bigFleetID bigint ,
	@vcUserIDs varchar(250)
AS
/******************************************************************************/
--	Name		:	rvlf_sp_UnAssignFleetUser
--	Description	:	To unassign users to the fleet.
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	24-Jul-2009	MJJC	Created Intial Version 
--              :   12-Apr-2010 LK      Removed the deletion from user preferences
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
	
	BEGIN TRAN MessageOutTransaction
	BEGIN TRY
		DELETE FROM rvlfFleetUsers WHERE FleetId = @bigFleetID and UserId in 
			(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcUserIDs,','))
		
		--DELETE FROM rvlfUserPreferences WHERE DefaultFleetId = @bigFleetID AND UserId IN 
		--	(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcUserIDs,','))
	COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during unassigning users to the fleet : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UnAssignFleetVehicle]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_UnAssignFleetVehicle]
	@bigFleetID bigint ,
	@vcVehicleIDs varchar(250) = null,
	@bitIsAll bit = null,
	@bigOrganizationID bigint = null,
	@siAssignedMakeID smallint = null,
	@siAssignedModelID smallint = null,
	@intAssignedVehicleTypeID int = null,
	@vcAssignedVehicleDesc varchar = null

AS
/******************************************************************************/
--	Name		:	rvlf_sp_UnAssignFleetVehicle
--	Description	:	To unassign users to the fleet.
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	24-Jul-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
	
	BEGIN TRAN MessageOutTransaction
	BEGIN TRY
		IF @bitIsAll IS NULL OR @bitIsAll = 0  OR @bitIsAll = ''
		BEGIN
		print 1
			DELETE FROM rvlfFleetVehicles WHERE FleetId = @bigFleetID and VehicleId in 
				(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcVehicleIDs,','))
		END
		ELSE
		BEGIN
		print 2 
			DELETE FROM rvlfFleetVehicles WHERE FleetId = @bigFleetID and VehicleId in 
				(SELECT v.VehicleId FROM rvlfVehicle v 
						INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId 
						INNER JOIN rvlfFleet f ON fv.FleetId = f.FleetId
						INNER JOIN rvlfModel m ON v.ModelId = m.ModelId
						INNER JOIN rvlfMake k ON v.MakeId = k.MakeId
						INNER JOIN rvlfVehicleType t ON v.VehicleTypeId = t.VehicleTypeId
						WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID = '' OR v.OrganizationId = @bigOrganizationID)
							AND ((@vcAssignedVehicleDesc is null or v.VehicleDescription LIKE '%'+@vcAssignedVehicleDesc+'%') OR v.VehicleTypeId = @intAssignedVehicleTypeID OR v.MakeId = @siAssignedMakeID OR v.ModelId = @siAssignedModelID)
							AND v.VehicleId IN
							( SELECT rfv.VehicleId FROM rvlfFleetVehicles rfv WHERE FleetId = @bigFleetID))
		END
	COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during unassigning vehicles to the fleet : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UnAssignTempUserVehicle]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UnAssignTempUserVehicle]    
 @UniTokenId varchar(max) = null,     
 @bitOperation int = null,      
 @bigOperationBy		bigint = null,
 @dtOperationDateTime datetime = null,
 @vcOperationRemarks varchar(500) = null
AS    
/******************************************************************************/    
-- Name  : [rvlf_sp_UnAssignTempUserVehicle] null,1,322,'7/25/2016 5:43:03 AM',null  
-- Description : To unassign vehicles to the Vendor.    
-- Author  : N.Ranjith
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--21-Jul-2016
/******************************************************************************/    
BEGIN    
SET NOCOUNT ON     
 -- Local variables to hold the intermediate results    
 DECLARE @ErrorMessage varchar(3000)    
     
 BEGIN TRAN MessageOutTransaction    
 BEGIN TRY    
  /**Delete**/
  IF @bitOperation  = 0     
  BEGIN   
 
	UPDATE rvlfVehicleTempUserAssignment SET isDelete = 1, DeletedBy = @bigOperationBy, DeletedDateTime = @dtOperationDateTime
	WHERE TAutoTokenID in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@UniTokenId,','))
  END   
    /**UnAssign**/ 
  ELSE IF @bitOperation  = 1       
  BEGIN     
   UPDATE rvlfVehicleTempUserAssignment SET isAssign = 1, UnAssignedBy = @bigOperationBy, UnAssignedDateTime = @dtOperationDateTime,UnAssignedRemarks=@vcOperationRemarks
	WHERE TAutoTokenID in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@UniTokenId,','))	
  END   
 COMMIT TRAN    
 END TRY    
 BEGIN CATCH    
  ROLLBACK TRAN     
  SET @ErrorMessage = 'An Error occured during unassigning vehicles to the fleet : ' + ERROR_MESSAGE()    
  RAISERROR( @ErrorMessage,16,1)    
 END CATCH    
SET NOCOUNT OFF    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UnAssignUserGroup]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UnAssignUserGroup]
	@UserGroupId int,
	@vcUserIDs varchar(250)
AS
/******************************************************************************/
--	Name		:	rvlf_sp_UnAssignUserGroup
--	Description	:	To unassign the User Group for the selected users
--	Author		:	Kumuthini.L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	27-Jul-2009		Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
	
	BEGIN TRAN MessageOutTransaction
	BEGIN TRY
		DELETE FROM rvlfUserGroupAssignment WHERE UserGroupId = @UserGroupId and UserId in 
			(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcUserIDs,','))
		IF(@UserGroupId=35)
			BEGIN
				DELETE FROM rvlfPartnerMaster WHERE PartnerId in 
					(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcUserIDs,','))
			END			
	COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during unassigning User Groups to the Users : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UnAssignVehicleMaintenancePlan]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UnAssignVehicleMaintenancePlan]
	@bigPlanId bigint,
	@vcVehicleIDs varchar(250) = null

AS
/******************************************************************************/
--	Name		:	rvlf_sp_UnAssignVehicleMaintenancePlan
--	Description	:	To unassign vehicles from the maintenance plan.
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	14-Jul-2010	Kumuthini. L	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
	
	BEGIN TRAN MessageOutTransaction
	BEGIN TRY
		
		DELETE FROM rvlfVehicleMaintenanceService
		WHERE Status = 0 AND VehiclePlanId IN (SELECT VehiclePlanId FROM rvlfVehiclePlanAssignment
		  WHERE PlanId = @bigPlanId AND VehicleId IN 
			(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcVehicleIDs,',')))
		
		DELETE FROM rvlfVehiclePlanAssignment
		WHERE PlanId = @bigPlanId AND VehicleId IN 
			(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcVehicleIDs,','))
		AND VehiclePlanId NOT IN (SELECT ms.VehiclePlanId FROM rvlfVehicleMaintenanceService ms 
		                          WHERE ms.VehiclePlanId = VehiclePlanId AND Status <> 0) 
		                          
		UPDATE rvlfVehiclePlanAssignment SET AssignedStatus = 0
		WHERE PlanId = @bigPlanId AND VehicleId IN 
			(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcVehicleIDs,','))
	
	COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during unassigning vehicles from the maintenance plan : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UnAssignVendorVehicle]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UnAssignVendorVehicle]      
 @bigVendorID bigint ,      
 @vcVehicleIDs varchar(250) = null,      
 @bitIsAll bit = null,      
 @bigOrganizationID bigint = null,      
 @siAssignedMakeID smallint = null,      
 @siAssignedModelID smallint = null,      
 @intAssignedVehicleTypeID int = null,      
 @vcAssignedVehicleDesc varchar = null,  
 @bigDeactivatedBy		bigint = null,
 @dtDeactivatedDateTime datetime = null      
AS      
/******************************************************************************/      
-- Name  : [rvlf_sp_UnAssignVendorVehicle]      
-- Description : To unassign vehicles to the Vendor.      
-- Author  : R.Gopal  
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--23-oct-2013  
/******************************************************************************/      
BEGIN      
SET NOCOUNT ON       
 -- Local variables to hold the intermediate results      
 DECLARE @ErrorMessage varchar(3000)      
       
 BEGIN TRAN MessageOutTransaction      
 BEGIN TRY      
  IF @bitIsAll IS NULL OR @bitIsAll = 0       
  --BEGIN      
  --print 1      
  -- DELETE FROM rvlfVendorVehicles WHERE VendorId = @bigVendorID and VehicleId in       
  --  (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcVehicleIDs,','))      
  --END      
  --ELSE      
  --BEGIN      
  --print 2       
  -- DELETE FROM rvlfVendorVehicles WHERE VendorId = @bigVendorID and VehicleId in       
  --  (SELECT v.VehicleId FROM rvlfVehicle v       
  --    INNER JOIN rvlfVendorVehicles fv ON v.VehicleId = fv.VehicleId       
  --    INNER JOIN rvlfFleet f ON fv.VendorId = f.FleetId      
  --    INNER JOIN rvlfModel m ON v.ModelId = m.ModelId      
  --    INNER JOIN rvlfMake k ON v.MakeId = k.MakeId      
  --    INNER JOIN rvlfVehicleType t ON v.VehicleTypeId = t.VehicleTypeId      
  --    WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)      
  --     AND ((@vcAssignedVehicleDesc is null or @vcAssignedVehicleDesc='' or v.VehicleDescription LIKE '%'+@vcAssignedVehicleDesc+'%')  
  --      OR v.VehicleTypeId = @intAssignedVehicleTypeID OR v.MakeId = @siAssignedMakeID OR v.ModelId = @siAssignedModelID)      
  --     AND v.VehicleId IN      
  --     ( SELECT rfv.VehicleId FROM rvlfVendorVehicles rfv WHERE FleetId = @bigVendorID))      
  --END  
  
  BEGIN    
  print 1    
	UPDATE rvlfVendorVehicles SET IsActive = 0, DeactivatedBy = @bigDeactivatedBy, DeactivatedDate = @dtDeactivatedDateTime
	WHERE VendorId = @bigVendorID and VehicleId in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcVehicleIDs,','))
  END    
  ELSE    
  BEGIN    
  print 2     
	UPDATE rvlfVendorVehicles SET IsActive = 0, DeactivatedBy = @bigDeactivatedBy, DeactivatedDate = @dtDeactivatedDateTime
	WHERE VendorId = @bigVendorID and VehicleId in
	(SELECT v.VehicleId FROM rvlfVehicle v     
	INNER JOIN rvlfVendorVehicles fv ON v.VehicleId = fv.VehicleId     
	INNER JOIN rvlfFleet f ON fv.VendorId = f.FleetId    
	INNER JOIN rvlfModel m ON v.ModelId = m.ModelId    
	INNER JOIN rvlfMake k ON v.MakeId = k.MakeId    
	INNER JOIN rvlfVehicleType t ON v.VehicleTypeId = t.VehicleTypeId    
	WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR v.OrganizationId = @bigOrganizationID)
	AND ((@vcAssignedVehicleDesc is null or @vcAssignedVehicleDesc='' or v.VehicleDescription LIKE '%'+@vcAssignedVehicleDesc+'%')
	OR v.VehicleTypeId = @intAssignedVehicleTypeID OR v.MakeId = @siAssignedMakeID OR v.ModelId = @siAssignedModelID)
	AND v.VehicleId IN (SELECT rfv.VehicleId FROM rvlfVendorVehicles rfv WHERE FleetId = @bigVendorID))
  END    
 COMMIT TRAN      
 END TRY      
 BEGIN CATCH      
  ROLLBACK TRAN       
  SET @ErrorMessage = 'An Error occured during unassigning vehicles to the fleet : ' +ERROR_MESSAGE()      
  RAISERROR( @ErrorMessage,16,1)      
 END CATCH      
SET NOCOUNT OFF      
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateAddress_BgProcess]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_UpdateAddress_BgProcess]                
(                
 @latitude decimal(14,6),                
 @longitude decimal(14,6),                
 @vcstreetaddress nvarchar(250),                
 @vcnearestlandmark nvarchar(300),                
 @vcmessageInID varchar(40)                
)                
AS                
/***********************************************************************************************/                
-- Name  : rvlf_sp_UpdateAddress_BgProcess                
-- Description : To get update the street address from the background process                
-- Author  : T. Sathish Kumar                
-- Company  : Angler Technologies                
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                
--    : 14-Nov-2009 MJJC Included the script for adding the information to the notification log.                
--    : 29-Jan-2010 MJJC Included the organization check for landmarks.                
--              :   09-Feb-2010 Kumu    Included the transaction                
--    : 12-Jul-2010 MJJC Included passing of Message Type for notifications                
--    : 05-Aug-2010 TSK  Included Org Code in Landmark assignment to solve History page issue                 
--    : 10-Aug-2010 TSK  Included Isolation level to avoid deadlock                
--    : 13-Aug-2010 TSK  Commented the TRANSACTION BLOCK to avoid deadlock                
--    : 25-Aug-2010 VN  Uncomment the notification isnotificationsent block.                
--    : 11-oct-2011 TSK  Optimized the query and removed unwanted temp. Tables.                
--    : 06-Dec-2011 Sakthi Decimal conversion to get the landmark id              
--    : 14-Feb-2013 Sakthi Restrict the multiple entries of notification log
/***********************************************************************************************/                
BEGIN                
                
-- SET TRANSACTION ISOLATION LEVEL READ COMMITTED;                
                
DECLARE @bigOrganizationID bigint,@tiBoxMsgInTypeId tinyint,@IntBoxid int=null,@landmarkID bigint                   
                
--    SELECT @tiBoxMsgInTypeId = BoxMsgInTypeId,@IntBoxid=BoxId FROM rvlfMsgInHst where MessageInID = @vcmessageInID                
SELECT @bigOrganizationID = B.OrganizationId,@tiBoxMsgInTypeId = H.BoxMsgInTypeId,@IntBoxid = H.BoxId FROM [DBO].[rvlfBoxId] B                 
  INNER JOIN [DBO].[rvlfMsgInHst] h On B.BoxId = h.BoxId WHERE h.MessageInID = @vcmessageInID                
                
DECLARE @ErrorMessage varchar(200)                
                
BEGIN TRY                
                
SET @landmarkID = null        
SELECT top 1 @landmarkID = A.LandmarkID FROM                 
(select distinct(G.OriginDateTime),L.LandMarkId,L.LandMarkName,G.Latitude as HLat,G.longitude as HLng,L.Latitude,L.Longitude,                
              ROUND((MIN(DEGREES(ACOS(                
                  --CAST(                
                  (                
      SIN(RADIANS(L.Latitude)) *                                            
      SIN(RADIANS(@latitude)) +                                            
      COS(RADIANS(L.Latitude)) *                                            
      COS(RADIANS(@latitude)) *                                            
      COS(RADIANS(L.Longitude - G.Longitude))                
                  ) 
                  --AS Decimal(14,10))                
              ))) * 69.09 * 1.609344),3) as Distance,CAST(CAST(L.Radius AS DECIMAL(8,4))/1000 as decimal(10,6)) as Radius                                              
From rvlfLandMarK L,rvlfMsgInHst G WHERE ValidGPS = 0 and G.Latitude = @latitude and G.Longitude = @longitude AND G.MessageInID = @vcmessageInID                
AND L.OrganizationId = @bigOrganizationID                 
group by G.OriginDateTime,L.LandMarkId,L.LandMarkName,G.Latitude,G.longitude,L.Latitude,L.Longitude,L.Radius                
) A WHERE A.Distance <= Radius                
order by Distance asc               
                
print 'update'                
--DECLARE @dtOriginDate AS DATETIME            
--DECLARE @intMapProvider AS INT          
--SELECT @dtOriginDate = OriginDateTime FROM rvlfMsgInHst WHERE MessageInID = @vcmessageInID            
--SELECT  FROM           
          
            
 UPDATE rvlfMsgInHst SET IsProcessed = 0, StreetAddress = @vcstreetaddress,NearestLandmark = @vcnearestlandmark,                
 LandMarkID = @landmarkID           
 --WHERE Latitude = @latitude AND Longitude = @longitude  AND IsProcessed=1         
 --AND BoxId IN (Select BoxId FROM rvlfBoxId WHERE OrganizationId <> 119)           
 Where MessageInID = @vcmessageInID                
                
print 'History update'                
                
  UPDATE [DBO].[rvlfBoxID] SET                 
  LastStreetAddress = isnull(@vcStreetAddress, LastStreetAddress),               
  NearestLandmark = @vcNearestLandmark                
 WHERE LastLatitude = @latitude AND LastLongitude = @longitude                
                 
 UPDATE [DBO].[rvlfAlarm] SET                
  StreetAddress = @vcStreetAddress                
 WHERE lat = @latitude AND Long = @longitude                
                   
  /*********************************************************************************************/                
   --DROP TABLE #tempDis                
   --DROP TABLE #LandMark                  
   --DECLARE @tiBoxMsgInTypeId tinyint,@IntBoxid int=null                  
   --SELECT @tiBoxMsgInTypeId = BoxMsgInTypeId,@IntBoxid=BoxId FROM rvlfMsgInHst where MessageInID = @vcmessageInID                
   --IF @tiBoxMsgInTypeId NOT IN (5,6)    
   --BEGIN                 
   IF NOT EXISTS(SELECT 1 FROM dbo.rvlfNotificationLog WHERE MessageInID=@vcMessageInID)
   BEGIN
	EXEC [DBO].[rvlf_sp_LogNotificaitons] @vcMessageInID, @tiBoxMsgInTypeId     
   END     
                 
END TRY                
BEGIN CATCH                
  -- ROLLBACK TRAN                
   SET @ErrorMessage = 'An Error occured during updating background process : ' + ERROR_MESSAGE()                
   RAISERROR( @ErrorMessage,16,1)                  
END CATCH                
                
  UPDATE rvlfMsgInHst SET IsProcessed = 0 WHERE MessageInID = @vcmessageInID                
                
END 
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateAddress_BgProcessTest]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_UpdateAddress_BgProcessTest]                          
(                                                
 @TableXML XML = NULL,  
 @TableName varchar(20)=  NULL  
)                  
AS                                                
/***********************************************************************************************/                                                
-- Name  : rvlf_sp_UpdateAddress_BgProcess                                                
-- Description : To get update the street address from the background process                                                
-- Author  : T. Sathish Kumar                                                
-- Company  : Angler Technologies                                                
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                                
--    : 14-Nov-2009 MJJC Included the script for adding the information to the notification log.                                                
--    : 29-Jan-2010 MJJC Included the organization check for landmarks.                                                
--              :   09-Feb-2010 Kumu    Included the transaction                                                
--    : 12-Jul-2010 MJJC Included passing of Message Type for notifications                                                
--    : 05-Aug-2010 TSK  Included Org Code in Landmark assignment to solve History page issue                                                 
--    : 10-Aug-2010 TSK  Included Isolation level to avoid deadlock                                                
--    : 13-Aug-2010 TSK  Commented the TRANSACTION BLOCK to avoid deadlock                                                
--    : 25-Aug-2010 VN  Uncomment the notification isnotificationsent block.                                                
--    : 11-oct-2011 TSK  Optimized the query and removed unwanted temp. Tables.                                                
--    : 06-Dec-2011 Sakthi Decimal conversion to get the landmark id                                       
--    : 3-Apr-2012 - Vijay XML parsing for updating the address in batch process.                              
--    : 7-Apr-2012 - Vijay - loop thru for setting notification and log exact number of address resolved   
--    : 14-Feb-2013 Sakthi Restrict the multiple entries of notification log      
--   : 22-Oct-2013 - Sakthi Include landmark address                                                                                      
/***********************************************************************************************/                                                
BEGIN                                                
                                                
-- SET TRANSACTION ISOLATION LEVEL READ COMMITTED;          
                                                       
--DECLARE @bigOrganizationID bigint,@Intboxid bigint=null,@landmarkID bigint          
          
DECLARE @tiBoxMsgInTypeId tinyint          
DECLARE @ErrorMessage varchar(200)          
                                               
BEGIN TRY  
          
/*****************************************************************************************************/                              
/**********************************Insert the Xml data to a TempTable ********************************/                  
/*****************************************************************************************************/                              
          
DECLARE @TemptblMaster TABLE              
(                          
 Latitude decimal(10,6),                          
 Longitude decimal(10,6),                 
 StreetAddress VARCHAR(MAX),  
 StreetAddress_AR NVARCHAR(MAX),                 
 StreetAddress_Hin NVARCHAR(MAX),   
 Boxid nvarchar(200),  
 district VARCHAR(300),              
 --MapProvider INT ,            
 --OrganizationId INT,  
 --LandMarkId BIGINT               
 SpeedLimit VARCHAR(100),                         RoadType INT     
)           
                
                                  
DECLARE @MapProvider AS INT                            
DECLARE @RowCount As BIGINT            
                  
DECLARE @tblName varchar(30) = '/NewDataSet/TableNew'                     
SET @tblName = '/NewDataSet/' + @TableName                     
          
                  
                                      
DECLARE @Index AS INT;                      
      SET @Index = 0;                                      
      EXEC Sp_xml_preparedocument  @Index OUTPUT,@TableXML                    
                  
         
                      
INSERT INTO @TemptblMaster(Latitude,Longitude,StreetAddress,StreetAddress_AR,StreetAddress_Hin,Boxid,SpeedLimit,RoadType,district)             
SELECT SA.latitude,                
       SA.longitude,                
       --ISNULL(SA.streetaddress,'Address could not be resolved!'),     
       ISNULL(SA.StreetAddress,'Address Could not be resolved!'),                   
       ISNULL(SA.StreetAddress_AR,N'لا يمكن أن تحل عنوان!'),    
       ISNULL(SA.StreetAddress_Hin,N'पता हल नहीं किया जा सकता है!'),           
       SA.boxid,                
       --SA.mapprovider ,            
       --B.OrganizationId,  
       SpeedLimit,  
    RoadType  ,DistrictAddr            
FROM   OPENXML (@Index, @tblName)                
          WITH (latitude      DECIMAL(10, 6) 'Latitude',                
                longitude     DECIMAL(10, 6) 'Longitude',                
                --streetaddress VARCHAR(250) 'StreetAddress',                
                streetaddress VARCHAR(250) 'StreetAddress',                   
                streetaddress_AR NVARCHAR(250) 'StreetAddress_AR',  
                streetaddress_Hin NVARCHAR(250) 'StreetAddress_Hin',  
                boxid         nvarchar(200) 'BoxId',                                
                --mapprovider   INT 'MapProvider'   
                SpeedLimit    DECIMAL  'SpeedLimit',                        
    RoadType      INT 'RoadType',
				DistrictAddr      VARCHAR(300) 'DistrictAddr') SA          
                INNER JOIN rvlfBoxId AS B ON SA.BoxId = B.BoxId  
  
/*****************************************************************************************************/           
            
--  DECLARE  @TemptblMsgInID TABLE               
--(                          
--msgid UNIQUEIDENTIFIER,                          
--boxtypeid TINYINT,                          
--[Rows] INT  IDENTITY PRIMARY KEY          
--)                          
        
        
--CREATE CLUSTERED INDEX IDX_TemptblMsgInID_Rows ON #TemptblMsgInID([Rows])                
                             
--INSERT INTO @TemptblMsgInID          
-- SELECT                            
-- msg.MessageInId,                          
-- msg.BoxMsgInTypeId                              
-- FROM rvlfMsgInHst_Techno AS Msg                          
--             INNER JOIN @TemptblMaster AS SA                                    
--               ON msg.Latitude = SA.Latitude AND msg.Longitude = SA.Longitude AND IsProcessed = 1     
--UNION ALL
--SELECT                            
-- msg.MessageInId,                          
-- msg.BoxMsgInTypeId                              
-- FROM rvlfMsgInHst_Techno_355 AS Msg                          
--             INNER JOIN @TemptblMaster AS SA                                    
--               ON msg.Latitude = SA.Latitude AND msg.Longitude = SA.Longitude AND IsProcessed = 1   
               --INNER JOIN rvlfOrganization org ON org.organizationId = SA.OrganizationId                         
               --WHERE SA.StreetAddress NOT LIKE 'Address could not be resolved!          
            
            
--SELECT * FROM @TemptblMsgInID        
/*****************************************************************************************************/                              
/******************************************Update rvlfmsginhst table*********************************************/                  
/*****************************************************************************************************/                              
  
UPDATE msg                
SET    msg.streetaddress = sa.streetaddress, isprocessed = 0
       --msg.NearestLandmark = sa.LandMarkId   
FROM   rvlfMsgInHst_Techno AS msg WITH (nolock)                
       INNER JOIN @TemptblMaster AS sa                
         ON msg.latitude = sa.Latitude                
            AND msg.longitude = sa.Longitude                
            AND isprocessed = 1          
            --INNER JOIN rvlfOrganization Org           
            --ON Org.OrganizationId = sa.OrganizationId          
UPDATE msg                
SET    msg.streetaddress = sa.streetaddress, isprocessed = 0
       --msg.NearestLandmark = sa.LandMarkId   
FROM   rvlfMsgInHst_Techno_355 AS msg WITH (nolock)                
       INNER JOIN @TemptblMaster AS sa                
         ON msg.latitude = sa.Latitude                
            AND msg.longitude = sa.Longitude                
            AND isprocessed = 1         
        
                                      
SELECT @RowCount = @@ROWCOUNT                            
SELECT @RowCount                         
                      
/*****************************************************************************************************/                  
/******************************************Update History*********************************************/                  
/*****************************************************************************************************/                              
  
UPDATE BX           
SET    BX.LastStreetAddress = SA.StreetAddress, BX.LastStreetAddress_AR = SA.StreetAddress_AR, BX.LastStreetAddress_Hin = SA.StreetAddress_Hin  
FROM   [DBO].[rvlfBoxID] AS BX WITH (nolock)                
     INNER JOIN @TemptblMaster AS SA                
    ON BX.LastLatitude = sa.Latitude                
            AND BX.LastLongitude = SA.Longitude          
         --AND BX.OrganizationId = SA.OrganizationId          
  
                                            
/*****************************************************************************************************/                              
/*******************************************Update Alarms in Alarms Table*********************************************/                  
/*****************************************************************************************************/                         
                  
UPDATE AL                
SET    AL.StreetAddress = SA.StreetAddress,AL.StreetAddress_AR = SA.StreetAddress_AR,AL.StreetAddress_Hin = SA.StreetAddress_Hin  
FROM   [DBO].[rvlfAlarm] AS AL WITH (nolock)                
       INNER JOIN @TemptblMaster AS SA                
         ON AL.Lat = sa.Latitude                
            AND AL.long = sa.Longitude AND AL.StreetAddress IS NULL        
/*****************************************************************************************************/                                          
/*******************************************Update Street Address in Landmark Table*********************************************/                              
/*****************************************************************************************************/                                     
                        
                        
UPDATE Msg SET Msg.StreetAddress = SA.StreetAddress FROM [DBO].[rvlfLandmark] AS Msg  
INNER JOIN @TemptblMaster AS SA ON Msg.Latitude = SA.Latitude AND Msg.Longitude = SA.Longitude  
WHERE Msg.StreetAddress IS NULL   
                                                     
/*****************************************************************************************************/                         
/************************Update resolved address count in respective table****************************/                    
/*****************************************************************************************************/                         
                            
--SELECT Top 1 @MapProvider = MapProvider from @TemptblMaster                 
                            
                                                                           
--IF( @RowCount <> 0 )                
--  BEGIN                
--      IF( @MapProvider = 0 )                
--        BEGIN                
--            IF EXISTS (SELECT RequestDate                
--                       FROM   rvlfGoogleRequest                
--                       WHERE  RequestDate = CONVERT(VARCHAR(10), Getutcdate(),                
--                                       110                
--                                            ))                
--              BEGIN                
--                  UPDATE rvlfGoogleRequest                
--     SET    RequestCount = RequestCount + @RowCount                
--                  WHERE  RequestDate = CONVERT(VARCHAR(10), Getutcdate(), 110)                
--              END                
--            ELSE                
--              BEGIN                
--           INSERT INTO rvlfGoogleRequest                
--                              (RequestDate,                
--                               RequestCount)                
--                  VALUES      (Getutcdate(),                
--                               @RowCount)                
--              END                
--        END                
--      ELSE                
--        IF( @MapProvider = 1 )                
--          BEGIN                
--              IF EXISTS (SELECT RequestDate                
--                         FROM   rvlfNavTeqRequest                
--                         WHERE  RequestDate = CONVERT(VARCHAR(10), Getutcdate(),                
--                                              110))                
--                BEGIN                
--                    UPDATE rvlfNavTeqRequest                
--                    SET    RequestCount = RequestCount + @RowCount                
--                    WHERE  RequestDate = CONVERT(VARCHAR(10), Getutcdate(), 110)                
--                END                
--              ELSE                
--                BEGIN                
--                    INSERT INTO rvlfNavTeqRequest                
--                                (RequestDate,                
--                                 RequestCount)                
--                    VALUES      (Getutcdate(),                
--                                 @RowCount)                
--                END                
--          END                
--  END                           
--IF EXISTS (SELECT RequestDate                
--                         FROM   rvlfNavTeqRequest                
--                         WHERE  RequestDate = CONVERT(VARCHAR(10), Getutcdate(),                
--                                              110))                
--                BEGIN                
--                    UPDATE rvlfNavTeqRequest                
--                    SET    RequestCount = RequestCount + @RowCount                
--                    WHERE  RequestDate = CONVERT(VARCHAR(10), Getutcdate(), 110)                
--                END                
--              ELSE                
--                BEGIN                
--                    INSERT INTO rvlfNavTeqRequest                
--                                (RequestDate,                
--                                 RequestCount)                
--                    VALUES      (Getutcdate(),                
--                                 @RowCount)                
--                END      
                                                   
/*********************************************************************************************/                                                
/*****************************Set Notofication for batch process*****************************/                          
/********************************************************************************************/                          
                             
--DECLARE @intFlag AS INT = 1                          
--DECLARE @vcMessageInID AS UNIQUEIDENTIFIER          
--DECLARE @landmarkID AS INT = NULL          
--DECLARE @latitude DECIMAL(10,6)          
--DECLARE @longitude DECIMAL(10,6)          
--DECLARE @bigOrganizationID INT          
                          
--WHILE (@intFlag <= @RowCount)                          
--BEGIN                          
          
--/*****************************************************************************************************/                              
--/********************Calculate Nearest Landmark and update tio the landmark table*********************/                  
--/*****************************************************************************************************/                                
--SET @landmarkID = NULL          
          
--SELECT @vcMessageInID = msgid, @tiBoxMsgInTypeId = boxtypeid FROM @TemptblMsgInID WHERE [Rows] = @intFlag                          
          
--SELECT @bigOrganizationID = B.OrganizationId,@latitude=h.Latitude,@longitude = h.Longitude FROM [DBO].[rvlfBoxId] B --@tiBoxMsgInTypeId = H.BoxMsgInTypeId           
--INNER JOIN [DBO].[rvlfMsgInHst] h On B.BoxId = h.BoxId WHERE h.MessageInID = @vcmessageInID               
          
--SELECT top 1 @landmarkID = A.LandmarkID FROM               
--(select distinct(G.OriginDateTime),L.LandMarkId,L.LandMarkName,G.Latitude as HLat,G.longitude as HLng,L.Latitude,L.Longitude,              
--              ROUND((MIN(DEGREES(ACOS(              
--                  --CAST(              
--                  (              
--      SIN(RADIANS(L.Latitude)) *                                          
--      SIN(RADIANS(@latitude)) +                                          
--      COS(RADIANS(L.Latitude)) *                                          
--      COS(RADIANS(@latitude)) *                                          
--      COS(RADIANS(L.Longitude - G.Longitude))              
--                  )     
--                  --AS Decimal(14,10))              
--              ))) * 69.09 * 1.609344),3) as Distance,cast(CAST(L.Radius AS decimal(8,4))/1000 as decimal(10,6)) as Radius                                            
--From rvlfLandMarK L,rvlfMsgInHst G WHERE ValidGPS = 0 and G.Latitude = @latitude and G.Longitude = @longitude AND G.MessageInID = @vcMessageInID              
--AND L.OrganizationId = @bigOrganizationID               
--group by G.OriginDateTime,L.LandMarkId,L.LandMarkName,G.Latitude,G.longitude,L.Latitude,L.Longitude,L.Radius              
--) A WHERE A.Distance <= Radius              
--order by Distance asc              
           
--PRINT @landmarkID        
--Print 'NUll'        
        
--UPDATE rvlfMsgInHst SET LandMarkID = @landmarkID,NearestLandmark = @landmarkID WHERE MessageInID = @vcMessageInID          
--UPDATE rvlfBoxId SET NearestLandmark = @landmarkID WHERE LastLatitude = @latitude AND LastLongitude = @longitude          
          
--/*****************************************************************************************************/                              
--/***********************************Update log Notification*******************************************/                  
--/*****************************************************************************************************/                                
--  IF NOT EXISTS(SELECT 1 FROM dbo.rvlfNotificationLog WHERE MessageInID=@vcMessageInID)  
--  BEGIN        
-- EXEC [DBO].[rvlf_sp_LogNotificaitons] @vcMessageInID, @tiBoxMsgInTypeId         
--  END  
      
-- SET @intFlag = @intFlag + 1                          
--END                                           
     
   --IF @TableName = 'TableGoogle'  
   --     BEGIN  
   --Select 'Google'  
   --     END  
                                                 
END TRY                                                
BEGIN CATCH                                                
  -- ROLLBACK TRAN                                                
   SET @ErrorMessage = 'An Error occured during updating background process : ' + ERROR_MESSAGE()                       
   RAISERROR( @ErrorMessage,16,1)                                             
END CATCH                    
                                                
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateBattaAmtIssued]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_UpdateBattaAmtIssued]
	@bigDriverId bigint=null,
	@bigVehicleId bigint=null,
	@dtTripStartDate datetime=null,
	@dtTripEndDate datetime=null,
	@bitIsPartialAmt bit=null,
	@nuPartialAmt numeric(6,2)=null,	
	@nuTotalAmt numeric(6,2)=null
AS
/******************************************************************************/
--	Name		:	rvlf_sp_UpdateBattaAmtIssued 45,23,'11/12/2010 7:32:14 AM','11/12/2010 2:01:08 PM',0,null,null
--	Description	:	To update the driver batta amount issued details.
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	03-Aug-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN
	DECLARE @BOXID BIGINT=NULL
	
	SELECT @BOXID=BoxId FROM rvlfVehicleAssignment WHERE VehicleId=@bigVehicleId 

	declare @tblTripStart table
(
	datein datetime,
	dateout datetime,
	boxid bigint,
	driver bigint,
	inc int
)
declare @tblTripEnd table
(	
	dateout datetime,
	driver bigint
)
insert into @tblTripStart (datein,boxid,driver)
select OriginDateTime,BoxId,CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))AS BIGINT) END  from rvlfmsginhst 
   where origindatetime between @dtTripStartDate and @dtTripEndDate 
          and BoxMsgInTypeId=76
          AND BoxId=@BOXID
          and (@bigDriverId IS NULL OR case when CustomProp like '%MAPID=%' then CAST(substring(CustomProp,CHARINDEX('MAPID=',customprop,1)+6,len(CustomProp)) AS bigint) end=@bigDriverId) 
          and CustomProp like '%Driver Status%'
          and CASE WHEN CustomProp LIKE '%Driver Status=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,CHARINDEX(';',CustomProp,
								CHARINDEX('Driver Status=',CustomProp,1)) - (CHARINDEX('Driver Status=',CustomProp,1)+14)) as VARCHAR) END='IN'
          order by OriginDateTime 
insert @tblTripEnd(dateout,driver)
select OriginDateTime,CASE WHEN CustomProp LIKE '%MAPID=%' THEN CAST(SUBSTRING(CustomProp,CHARINDEX('MAPID=',CustomProp,1)+6,LEN(CustomProp))AS BIGINT) END from rvlfmsginhst 
   where origindatetime between @dtTripStartDate and @dtTripEndDate 
          and BoxMsgInTypeId=76
          AND BoxId=@BOXID
          and (@bigDriverId IS NULL OR case when CustomProp like '%MAPID=%' then CAST(substring(CustomProp,CHARINDEX('MAPID=',customprop,1)+6,len(CustomProp)) AS bigint) end=@bigDriverId)
          and CustomProp like '%Driver Status%'
          and CASE WHEN CustomProp LIKE '%Driver Status=%' THEN CAST( SUBSTRING (CustomProp,CHARINDEX('Driver Status=',CustomProp,1)+14,CHARINDEX(';',CustomProp,
								CHARINDEX('Driver Status=',CustomProp,1)) - (CHARINDEX('Driver Status=',CustomProp,1)+14)) as VARCHAR) END='OUT'
          order by OriginDateTime  

UPDATE @tblTripStart SET inc=1 WHERE driver=0
     
while exists(select * from @tblTripStart where inc is null)
begin

	declare @dt datetime =null	
	SET @bigDriverId=NULL
	select top 1 @dt=datein,@bigDriverId=driver from @tblTripStart where dateout is null AND inc IS NULL
	update top(1) @tblTripStart set dateout=(select top 1 dateout  from @tblTripEnd where dateout>@dt and driver=@bigDriverId)where dateout is null and datein=@dt and inc is null 		  
	update @tblTripStart set inc=1 where inc is null and datein=@dt 		

end		
	UPDATE @tblTripStart SET inc=null WHERE driver!=0
	while exists(select * from @tblTripStart where inc is null)
		begin
			SET @dtTripStartDate=NULL
			SET @dtTripEndDate =NULL
			SELECT TOP 1 @dtTripStartDate=datein,@dtTripEndDate=dateout FROM @tblTripStart WHERE inc IS NULL 
			IF NOT EXISTS(SELECT DriverId FROM rvlfDriverIncentiveAmounts WHERE DriverId=@bigDriverId AND TripStart=@dtTripStartDate AND TripEnd=@dtTripEndDate)
				BEGIN
					INSERT INTO rvlfDriverIncentiveAmounts(DriverId,VehicleId,TripStart,TripEnd,IsPartialAmt,PartialAmt,TotalAmt)   
						VALUES(@bigDriverId,@bigVehicleId,@dtTripStartDate,@dtTripEndDate,@bitIsPartialAmt,@nuPartialAmt,@nuTotalAmt)     				 
				END	
				
			update @tblTripStart set inc=1 where inc is null and datein=@dtTripStartDate and dateout=@dtTripEndDate and driver=@bigDriverId   					
		end
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateBoxDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateBoxDetails]
(   
	@intBoxId int,
	@bigFwId bigint = null
)

AS

/********************************************************************************************/
--	Name		:	rvlf_sp_UpdateBoxDetails
--	Description	:	To Add and Edit the Box Details
--	Author		:	S. Jeyanthi
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	30-Oct-2010		Created Intial Version 
/********************************************************************************************/

BEGIN
SET NOCOUNT ON  
  BEGIN
  
	  UPDATE rvlfBoxSettings SET  FwID = @bigFwId WHERE BoxId = @intBoxId
  
  END

	
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateBoxIDDataForDemo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_UpdateBoxIDDataForDemo] 
	@bigOrganizationID bigInt=30 --Demo Organization ID For Dedicated Server
	--@intBoxId int=Null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_UpdateBoxIDDataForDemo] 29,42
--	Description	:	Update the Latest postition of the Device in rvlfBoxID
--	Author		:	S.Jeyanthi.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	20-Sep-2010	SJ	Created Intial Version 
/******************************************************************************/
BEGIN	

	--Update rvlfBoxId Set LastValidDateTime='2010-09-19 07:21:46.000', LastLatitude='11.673878', LastLongitude='77.129708',
	--LastSpeed=0, LastStreetAddress='NH 209, Tamil Nadu, India',
	--LastCommunicatedDateTime=DATEADD(MI,3,'2010-09-19 07:21:46.000'),LastSensorMask='00100010',
	--OrganizationId=29,LastStatusDateTime=DATEADD(MI,1,'2010-09-19 07:21:46.000'),
	--NearestLandmark='N/A',Heading=120, MessageInId='510B02FD-4EC2-DF11-B201-001A4DA9CFD4'

		DECLARE @tblBoxes TABLE (BoxID int)
		
		INSERT INTO @tblBoxes (BoxID) SELECT BoxID FROM rvlfBoxId 
			WHERE OrganizationId =@bigOrganizationID 
		
		Declare @IsArmed int
		Declare @OriginDateTime DateTime
		Declare @DateTimeReceived DateTime
		Declare @Latitude nvarchar(15)
		Declare @Longitude nvarchar(15)
		Declare @Speed bigint
		Declare @StreetAddress nvarchar(150)
		Declare @SensorMask nvarchar(10)
		Declare @NearestLandMark nvarchar(50)='N/A'
		Declare @Heading  bigint=0
		Declare @MsgInID nvarchar(50)
	
		--For using the BoxId in while Loop
		DECLARE @intBoxLooping int		
		SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes
		
		WHILE @intBoxLooping IS NOT NULL
			BEGIN
			
			Select top 1 @IsArmed= IsArmed,@OriginDateTime=OriginDateTime,@DateTimeReceived=DateTimeReceived,@Latitude=Latitude,@Longitude=Longitude,
			@Speed=Speed, @StreetAddress=StreetAddress,@SensorMask=SensorMask,@NearestLandMark=NearestLandmark,
			@Heading=Heading,@MsgInID=MessageInID 
			from rvlfMsgInHst where BoxId =@intBoxLooping order by OriginDateTime Desc 
		 
		 
			Update rvlfBoxId Set BoxArmed=ISNULL(@IsArmed,0), LastValidDateTime=@OriginDateTime, LastLatitude=@Latitude, 
			LastLongitude=@Longitude,LastSpeed=@Speed, LastStreetAddress=@StreetAddress,
			LastCommunicatedDateTime=@DateTimeReceived,LastSensorMask=@SensorMask,
			OrganizationId=@bigOrganizationID,LastStatusDateTime=@OriginDateTime,
			NearestLandmark=@NearestLandMark,Heading=@Heading, 
			MessageInId=@MsgInID where BoxId =@intBoxLooping
		
			SELECT @intBoxLooping = MAX(BoxID) from @tblBoxes WHERE BoxID < @intBoxLooping		
		END
 
 END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateBoxSettingsForAPN]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_UpdateBoxSettingsForAPN]
@BoxId varchar(15),
@CommModeId int
AS
/****************************************************************************************/    
-- Name    : [rvlf_sp_UpdateBoxSettingsForAPN]  
-- Description   : To update the service provider in Box Settings table for APN Change
-- Author    : Sakthi Gopinath S  
-- Created Date  : 17-Jun-2011  
-- Modified Date :    
/***************************************************************************************/    
BEGIN
SET NOCOUNT ON
	UPDATE rvlfBoxSettings SET CommModeId=@CommModeId WHERE BoxId=@BoxId
SET NOCOUNT OFF
END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateCommandSent]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_UpdateCommandSent]
	@intBoxID varchar(15),
	@dtSentDateTime datetime,
	@bigUserId bigint = 0,
 	@tiPriority tinyint = 0,	
	@tiBoxMsgOutCmdTypeId char(2),	
	@vcCommInfo1 varchar(15),
	@siCommInfo2 int ,
	@vcCustomProp varchar(max)= null,
	@bigSequenceNum bigint = null,
	@ScheduleID bigint= null,
	@bitScheduled bit= 0
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_UpdateCommandSent]
--	Description	:	To insert the messages that is sent to the device
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	26-May-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)	
	DECLARE @intBoxProtocolTypeId int
	DECLARE @tiServiceID tinyint
	DECLARE @tiCommModeId tinyint	
	Declare @tiBoxMsgOutCmdTypeId1 tinyint = (select BoxCmdOutTypeId from rvlfBoxCmdOutType where BoxCmdOutTypeCode=@tiBoxMsgOutCmdTypeId COLLATE SQL_Latin1_General_CP1_CS_AS )
	SELECT @intBoxProtocolTypeId = BoxProtocolTypeId, @tiCommModeId = CommModeId 
		FROM rvlfBoxSettings WHERE BoxId = @intBoxID
		
	SELECT @tiServiceID = ServiceID FROM rvlfServices 
		WHERE CommModeId = @tiCommModeId
		 
	--BEGIN TRAN MessageOutTransaction
	--BEGIN TRY
		-- To insert the information in the message in history table
		INSERT INTO rvlfMsgOutHst 
		(
			BoxId, SentDateTime, UserId, Priority, ServiceId,
			BoxCmdOutTypeId, BoxProtocolTypeId, CommInfo1, CommInfo2,
			CustomProp, SequenceNum, Scheduled,ScheduleId
		)
		VALUES
		(
			@intBoxID, @dtSentDateTime, @bigUserId, @tiPriority, @tiServiceID, 
			@tiBoxMsgOutCmdTypeId1, @intBoxProtocolTypeId, @vcCommInfo1, @siCommInfo2, 
			@vcCustomProp, @bigSequenceNum, @bitScheduled,@ScheduleID
		)
		--COMMIT TRAN
	--END TRY
	--BEGIN CATCH
	--	ROLLBACK TRAN 
	--	SET @ErrorMessage = 'An Error occured during insert of the message sent : ' +ERROR_MESSAGE()
	--	RAISERROR( @ErrorMessage,16,1)
	--END CATCH
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateCommandSent_old]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_UpdateCommandSent_old]
	@intBoxID int,
	@dtSentDateTime datetime,
	@bigUserId bigint = 0,
 	@tiPriority tinyint = 0,	
	@vcBoxCmdOutTypeName varchar(50),	
	@vcCommInfo1 varchar(15),
	@siCommInfo2 int ,
	@vcCustomProp varchar(350)= null,
	@bigSequenceNum bigint = null,
	@bitScheduled bit= 0
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_UpdateCommandSent]150,'2011-05-31 07:38:28.490',62,0,'GetBoxStatus','94.201.228.72',29225
--	Description	:	To insert the messages that is sent to the device
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	26-May-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
	DECLARE @tiBoxMsgOutCmdTypeId tinyint
	DECLARE @intBoxProtocolTypeId int
	DECLARE @tiServiceID tinyint
	DECLARE @tiCommModeId tinyint
	
	-- Gets the required IDS.
	SELECT @tiBoxMsgOutCmdTypeId = BoxCmdOutTypeId FROM rvlfBoxCmdOutType
		WHERE BoxCmdOutTypeName = @vcBoxCmdOutTypeName	
print 	@tiBoxMsgOutCmdTypeId	
	SELECT @intBoxProtocolTypeId = BoxProtocolTypeId, @tiCommModeId = CommModeId 
		FROM rvlfBoxSettings WHERE BoxId = @intBoxID
print 	@intBoxProtocolTypeId		
	SELECT @tiServiceID = ServiceID FROM rvlfServices 
		WHERE CommModeId = @tiCommModeId
print 	@tiServiceID		 
	BEGIN TRAN MessageOutTransaction
	BEGIN TRY
		-- To insert the information in the message in history table
		INSERT INTO rvlfMsgOutHst 
		(
			BoxId, SentDateTime, UserId, Priority, ServiceId,
			BoxCmdOutTypeId, BoxProtocolTypeId, CommInfo1, CommInfo2,
			CustomProp, SequenceNum, Scheduled
		)
		VALUES
		(
			@intBoxID, @dtSentDateTime, @bigUserId, @tiPriority, @tiServiceID, 
			@tiBoxMsgOutCmdTypeId, @intBoxProtocolTypeId, @vcCommInfo1, @siCommInfo2, 
			@vcCustomProp, @bigSequenceNum, @bitScheduled
		)
		COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during insert of the message sent : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


--select * from rvlfMsgOutHst

--select * from rvlfBoxCommInfo


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateDateForDemo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_UpdateDateForDemo] 
	@bigOrganizationID bigInt=Null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_UpdateDateForDemo] 30
--	Description	:	Modify the datepart in History for Demo
--	Author		:	S.Jeyanthi.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	16-Sep-2010	SJ	Created Intial Version 
--				:   02-Dec-2010 SJ  Included RouteMangement and Fleet Maintenenace Tables to update the Date 
/******************************************************************************/
BEGIN
	
	--UPDATE rvlfMsgInHst 
	--SET OriginDateTime= dateadd(dd,datediff(dd,OriginDateTime,GetDate()),OriginDateTime)
	--WHERE  BoxId=42

	----For getting ID with comma separation for the organization
	DECLARE @vcBoxID nvarchar(4000)
	SELECT @vcBoxID=Coalesce(@vcBoxID,'')+ CONVERT(varchar,BoxId)+',' from rvlfBoxId where OrganizationId=@bigOrganizationID 
		AND BOXID NOT IN(10001,10002,10003,10004,10005,10006,10007,10008,10009,10010,10011,10012,10013,10014,10015,10016,10017)
	----End	
	
	----Function used to convert varchar to int in where condition
	--UPDATE rvlfMsgInHst 	
	--SET OriginDateTime= dateadd(dd,datediff(dd,OriginDateTime,DateAdd(DAY,-1,GetUTCDate())),OriginDateTime)
	--WHERE  BoxId in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxID,','))
	----End
	
	--Modified for Updating the different date
	DECLARE @index as int;
	DECLARE @TotalCount as int;	
		
	DECLARE @DemoDate TABLE(OriginDate DATE, INC int IDENTITY)
	
	INSERT INTO @DemoDate 
	SELECT DISTINCT Convert(Date,OriginDateTime) from rvlfMsgInHst 
	WHERE BoxId in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxID,','))
	ORDER BY Convert(Date,OriginDateTime) desc
		
	SELECT @TotalCount = COUNT(*) from @DemoDate;
	SET @index = 1;
	
	WHILE(@index <= @TotalCount)	
		BEGIN 
				UPDATE rvlfMsgInHst 			
				SET OriginDateTime= dateadd(dd,datediff(dd,OriginDateTime,DateAdd(DAY,-@index,GetUTCDate())),OriginDateTime),
				DateTimeReceived = dateadd(dd,datediff(dd,DateTimeReceived,DateAdd(DAY,-@index,GetUTCDate())),DateTimeReceived)				
				WHERE  BoxId in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxID,','))	
				
				UPDATE rvlfBoxId			
				SET LastValidDateTime= dateadd(dd,datediff(dd,LastValidDateTime,DateAdd(DAY,-@index,GetUTCDate())),LastValidDateTime),
				LastCommunicatedDateTime= dateadd(dd,datediff(dd,LastCommunicatedDateTime,DateAdd(DAY,-@index,GetUTCDate())),LastCommunicatedDateTime),
				LastStatusDateTime = dateadd(dd,datediff(dd,LastStatusDateTime,DateAdd(DAY,-@index,GetUTCDate())),LastStatusDateTime)
				WHERE  BoxId in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxID,','))	
				
				UPDATE rvlfAlarm			
				SET DateTimeCreated = dateadd(dd,datediff(dd,DateTimeCreated,DateAdd(DAY,-@index,GetUTCDate())),DateTimeCreated),
				DateTimeAccepted= NULL,AcceptedBy=NULL,DateTimeClosed=NULL,ClosedBy=NULL,IsClosed=0				
				WHERE  BoxId in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxID,','))
								
				
			SET @index = @index + 1;
		END	
		--End Updating History and BoxID tables with current date

--Update Date for BoxMsgOutHst
	UPDATE rvlfMsgOutHst
		SET SentDateTime= dateadd(MM,datediff(MM,SentDateTime,DateAdd(MONTH,-1,GetUTCDate())),SentDateTime)
				WHERE  BoxId in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxID,','))	
				
	UPDATE rvlfMsgOutHst
		SET SentDateTime= dateadd(dd,datediff(dd,SentDateTime,DateAdd(DAY,-1,GetUTCDate())),SentDateTime)
				WHERE  BoxId in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcBoxID,','))	
--End


	--Update Date for Driver Management
	UPDATE rvlfDriverAssignment 			
				SET AssignmentDate = dateadd(dd,datediff(dd,AssignmentDate,DateAdd(DAY,-1,GetUTCDate())),AssignmentDate),
				FromTime=dateadd(dd,datediff(dd,FromTime,DateAdd(DAY,-2,GetUTCDate())),FromTime),
				ToTime=dateadd(dd,datediff(dd,ToTime,DateAdd(DAY,-1,GetUTCDate())),ToTime),
				AssignedDate =dateadd(dd,datediff(dd,AssignedDate,DateAdd(DAY,-1,GetUTCDate())),AssignedDate)
				WHERE  AssignmentId=204 and DriverId=49
	--End		
	
	--Update Month and Day for Route Management	
	Update rvlfEmployeeShifts set 
		ShiftDate = dateadd(MM,datediff(MM,ShiftDate,DateAdd(Month,-1,GetUTCDate())),ShiftDate)
		
	Update rvlfEmployeeShifts SET
		ShiftDate = dateadd(dd,datediff(dd,ShiftDate,DateAdd(Day,-1,GetUTCDate())),ShiftDate)
		
	Update rvlfEmployeeShifts SET 
		ShiftDay = datename(dw,ShiftDate)
				
	Update rvlfScheduledVehicleRequisition set 
	RequisitionDate = dateadd(MM,datediff(MM,RequisitionDate,DateAdd(MONTH,-1,GetUTCDate())),RequisitionDate),
	RequisitionFromDate=dateadd(MM,datediff(MM,RequisitionFromDate,DateAdd(MONTH,-1,GetUTCDate())),RequisitionFromDate),
	RequisitionToDate=dateadd(MM,datediff(MM,RequisitionToDate,DateAdd(MONTH,-1,GetUTCDate())),RequisitionToDate)
	
	
	Update rvlfScheduledVehicleRequisition set 	
	RequisitionDate = dateadd(dd,datediff(dd,RequisitionDate,DateAdd(Day,-1,GetUTCDate())),RequisitionDate),
	RequisitionFromDate=dateadd(dd,datediff(dd,RequisitionFromDate,DateAdd(Day,-1,GetUTCDate())),RequisitionFromDate),
	RequisitionToDate=dateadd(dd,datediff(dd,RequisitionToDate,DateAdd(Day,-1,GetUTCDate())),RequisitionToDate)		
	--End
	
	--Update Date for Fleet Maintenance
	Update rvlfVehicleMaintenanceService 
		SET StartDate=dateadd(MM,datediff(MM,StartDate,DateAdd(MONTH,-1,GetUTCDate())),StartDate),
		DueOnDate=dateadd(MM,datediff(MM,DueOnDate,DateAdd(MONTH,-1,GetUTCDate())),DueOnDate),
		ExecutedOn=dateadd(MM,datediff(MM,ExecutedOn,DateAdd(MONTH,-1,GetUTCDate())),ExecutedOn),
		ModifiedDateTime=dateadd(MM,datediff(MM,ModifiedDateTime,DateAdd(MONTH,-1,GetUTCDate())),ModifiedDateTime)	
	FROM rvlfVehicleMaintenanceService vms
		INNER JOIN rvlfVehiclePlanAssignment vpa ON vpa.VehiclePlanId =vms.VehiclePlanId 
		INNER JOIN rvlfVehicle v ON v.VehicleId = vpa.VehicleId  
		Where OrganizationId =@bigOrganizationID
	--END
	
	--Route Management	
	Update rvlfRouteDriverAssignment Set FromDateTime=dateadd(MM,datediff(MM,FromDateTime,DateAdd(MONTH,-1,GetUTCDate())),FromDateTime), 
		ToDateTime=dateadd(MM,datediff(MM,ToDateTime,DateAdd(MONTH,-1,GetUTCDate())),ToDateTime)
		
	Update rvlfRouteDriverAssignment Set FromDateTime=dateadd(dd,datediff(dd,FromDateTime,DateAdd(Day,-1,GetUTCDate())),FromDateTime), 
		ToDateTime=dateadd(dd,datediff(dd,ToDateTime,DateAdd(Day,-1,GetUTCDate())),ToDateTime)
	--End
	
END




GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateEmailNotification]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_UpdateEmailNotification]     
/******************************************************    
Stored Procedure Name : rvlf_sp_UpdateEmailNotification    
Purpose     : Update email notifications to a fleet    
Created by    : Uma    
Created date   : 14-Jul-09    
Updated by    :     
Updated date   :     
*******************************************************/    
    
@FleetId bigint   = Null,    
@Email  varchar(2010) = Null,  
@SMS  varchar(160) = Null,  
@Notify  bit    = Null,  
@Warning bit    = Null,  
@Critical bit    = Null    
    
AS    
    
BEGIN     
    
 IF (@FleetId > 0)    
 BEGIN    
    
  UPDATE rvlfFleet SET  
 Email=@Email,  
 SMS=@SMS,  
 Notify=@Notify,  
 Warning=@Warning,  
 Critical=@Critical  
 WHERE FleetId=@FleetId  
          
 END    
    
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateFareDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlf_sp_UpdateFareDetails]    
@TripId bigint,    
@PackageLocation varchar(25),    
@UsersDepartment varchar(25),    
@AddDistance decimal(8,2),    
@UwDistance decimal(8,2),    
@TollCharge decimal(8,2),    
@MaintFare decimal(8,2),    
@FuelRate decimal(8,2),    
@FuelHike decimal(6,2),    
@ModifiedBy int    
as    
-- =============================================                  
-- Name   : rvlf_sp_UpdateFareDetails    
-- Author  : Gopal.R                  
-- Create date : 25-Oct-2013                  
-- Description :  Update Fare Details                  
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
-- =============================================         
 begin   
   
 DECLARE @HoursToBeAdded INT = 0                            
DECLARE @MinsToBeAdded INT = 0                            
DECLARE @ConversionFactor decimal(18,2) = 1.0                            
DECLARE @ConversionFactorSpeed decimal(18,2) = 1.0                            
DECLARE @DefaultDateFormat INT = 0                            
                                        
SELECT @ConversionFactor = CASE WHEN up.Fuel = 0 THEN 3.79 ELSE 1.0 END,                    
@DefaultDateFormat=(case when  ISNULL(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end),                                      
@ConversionFactorSpeed = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                                   
@HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded                                         
FROM [DBO].[rvlfUserPreferences] up INNER JOIN [DBO].[rvlfTimeZones] tz                                          
ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @ModifiedBy    
  
update rvlfTripFareDetails set     
PackageLocation = @PackageLocation,    
UsersDepartment =@UsersDepartment,    
AddDistance =(@AddDistance /@ConversionFactorSpeed) ,  
UwDistance =(@UwDistance/@ConversionFactorSpeed) ,    
TollCharge=@TollCharge,    
MaintFare=@MaintFare,    
FuelRate=@FuelRate,    
FuelHike=@FuelHike,    
ModifiedBy=@ModifiedBy,    
ModifiedDate= getdate() where TripId=@TripId    
    
 end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateFleet]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateFleet]
	@bigFleetID bigint = null,
	@vcFleetName varchar(100),
	@bigOrganizationID bigint,
	@vcDescription varchar(250),
	@intTimeZone int,
	@bitDayLightSaving bit = null,
	@bitNotify bit,
	@bitWarning bit,
	@bitCritical bit,
	@bitAutoAdjustDayLightSaving bit = null,
	@bigProcessedBy bigint = null, -- Created / Modified UserID
	@dtProcessedDateTime datetime = null, -- Created / Modified date time
	--@tblNotificationsList as NotificaitonUserList READONLY
	@tblNotificationsList XML = null,
	@vcPowerplantRating varchar(50) = null, 
	@vcRatingOfHVREquip varchar(50) = null,
	@tintControllerType tinyint = null 
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_UpdateFleet]
--	Description	:	To insert / update the fleets.
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	17-Sep-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
/****************************Reading XML File and Store into Temp table**************/   
   DECLARE @docHandle int     
   DECLARE  @temptable TABLE (UserID Bigint,Email bit,SMS bit)        
    IF @tblNotificationsList IS NOT NULL   
  BEGIN                  
   EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblNotificationsList                           
  INSERT INTO @tempTable                                        
   SELECT * FROM OPENXML(@docHandle, '/DocumentElement/Notification') 
   WITH   
   (           
		UserID bigint 'UserID'            
		,Email  bit  'Email'                                      
		,SMS bit  'SMS'  
   )        
	END  
	declare @tblNotificationsListTmp As NotificaitonUserList 
	insert into  @tblNotificationsListTmp
	select * from @temptable   
 /**************************************************************************************/
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
		 
	BEGIN TRAN MessageOutTransaction
	BEGIN TRY
		-- Checks whether to update or insert the data with the help of fleet ID.
		IF @bigFleetID IS NULL
		BEGIN
			-- Inserts the data to the fleet table.
			INSERT INTO rvlfFleet 
				(FleetName,OrganizationId,[Description],TimeZone,DayLightSaving,Notify,
				Warning,Critical,AutoAdjustDayLightSaving,CreatedBy,CreatedDate,
				PowerPlantRating,RatingOfHVREquip,ControllerType)
			VALUES
				(@vcFleetName, @bigOrganizationID, @vcDescription, @intTimeZone,
				@bitDayLightSaving, @bitNotify, @bitWarning, @bitCritical, 
				@bitAutoAdjustDayLightSaving, @bigProcessedBy, @dtProcessedDateTime,
				@vcPowerplantRating, @vcRatingOfHVREquip, @tintControllerType)
				
			--SET @bigFleetID = @@IDENTITY
			select @bigFleetID = IDENT_CURRENT('rvlfFleet')
			
			exec rvlf_sp_Save_notificationsList @tblNotificationsListTmp, 3 , @bigFleetID
			
			IF EXISTS(SELECT UserId FROM rvlfuser WHERE OrganizationId = @bigOrganizationID AND UserId = @bigProcessedBy)
			   BEGIN
						INSERT INTO rvlfFleetUsers(FleetId, UserId, AssignedBy, AssignedDate) VALUES
							(@bigFleetId,@bigProcessedBy, @bigProcessedBy, @dtProcessedDateTime)
			   END
		END
		ELSE
		BEGIN
			-- Checks if the fleet exists
			IF EXISTS(SELECT * FROM rvlfFleet WHERE FleetId = @bigFleetID)
			BEGIN
				UPDATE rvlfFleet SET FleetName = @vcFleetName, OrganizationId=@bigOrganizationID, [Description] = @vcDescription,
									 TimeZone= @intTimeZone, DayLightSaving = @bitDayLightSaving, Notify = @bitNotify,
									 Warning = @bitWarning, Critical = @bitCritical, AutoAdjustDayLightSaving = @bitAutoAdjustDayLightSaving,
									 ModifiedBy = @bigProcessedBy, ModifiedDate = @dtProcessedDateTime, PowerPlantRating = @vcPowerplantRating,
									 RatingOfHVREquip = @vcRatingOfHVREquip, ControllerType = @tintControllerType
				WHERE FleetId = @bigFleetID
				
				DELETE FROM rvlfNotificationList WHERE NotificationType = 3  and TypeID = @bigFleetID
				exec rvlf_sp_Save_notificationsList @tblNotificationsListTmp, 3 , @bigFleetID
			END
			ELSE
			BEGIN
				raiserror('Invalid Fleet for update.',16,1);
			END
		END
		COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during insert of the message sent : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateIgnoredPackets]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateIgnoredPackets]
	@vcDataPacket varchar(150), 
	@dtRecDateTime datetime, 
	@vcReason varchar(50),
	@vcCommInfo1 varchar(15),
	@siCommInfo2 smallint,
	@vcCommMode varchar(100)
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_UpdateIgnoredPackets]
--	Description	:	To insert the invalid messages which has been reached the DCL
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	25-May-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN

	-- Declares the required variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
	DECLARE @tiServiceID tinyint
	
	-- Gets the required data.
	SELECT @tiServiceID = ServiceID FROM rvlfServices 
		WHERE CommModeId = (SELECT CommModeId FROM rvlfCommMode 
			WHERE CommModeName = @vcCommMode)

	BEGIN TRAN IgnoreMessageUpdate
	BEGIN TRY
		INSERT INTO rvlfMsgInHstIgnore 
		(
			DataPacket , RecDateTime , Reason , CommInfo1 , CommInfo2 , ServiceID
		)
		VALUES
		(
			@vcDataPacket , @dtRecDateTime , @vcReason , @vcCommInfo1, @siCommInfo2 , @tiServiceID 
		)
		COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during insert of the ignored message : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdatemailStatusDelayNotify]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author:  Vijay N  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
CREATE PROCEDURE [dbo].[rvlf_sp_UpdatemailStatusDelayNotify]  
 -- Add the parameters for the stored procedure here   
 @Boxid AS INT,  
 @GeozoneId AS INT,  
 @TripNo INT   
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
    -- Insert statements for procedure here  
    IF(@TripNo = 1)  
    BEGIN  
  UPDATE rvlfDelayNotify SET Trip1MailStatus = CAST(GETUTCDATE() AS DATE)   
  WHERE BoxId = @Boxid AND GeozoneId = @GeozoneId  
    END  
    ELSE IF(@TripNo = 2)  
    BEGIN  
  UPDATE rvlfDelayNotify SET Trip2MailStatus = CAST(GETUTCDATE() AS DATE)   
  WHERE BoxId = @Boxid AND GeozoneId = @GeozoneId  
    END  
    ELSE IF(@TripNo = 3)  
    BEGIN  
  UPDATE rvlfDelayNotify SET Trip3MailStatus = CAST(GETUTCDATE() AS DATE)   
  WHERE BoxId = @Boxid AND GeozoneId = @GeozoneId  
    END   
END  

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateMaintenanceServiceDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateMaintenanceServiceDetails]
	@bigServiceDetailsId bigint,
	@tiStatus tinyint,
	@bigCurrentReading bigint,
	@dtExecutionOnDate Datetime = null,
	@tblMaintenanceServiceDetails XML =NULL,
	@IsDueOn bit = 1,
	@dtScheduleOnDate Datetime = null,
	@vcComments varchar(250) = null,
	@ModifiedBy bigint,
	@ModifiedDateTime Datetime =null ,
	@bigQueryingUser Bigint =null
AS
/******************************************************************************/
-- Name : [rvlf_sp_UpdateMaintenanceServiceDetails]
-- Description : To update the service details on completion, skipping the
--@tblMaintenanceServiceDetails AS MaintenanceServiceDetails READONLY,
-- service or dismissing the service
-- Author : Kumuthini. L
-- Company : Angler Technologies
-- History : <<Date(dd-MON-yyyy)>> Initial Reason
-- : 21-Jun-2010 LK Created Intial Version
/******************************************************************************/
	BEGIN
		SET NOCOUNT ON
		-- Local variables to hold the intermediate results
		DECLARE @ErrorMessage varchar(3000)
		DECLARE @VehiclePlanId bigint = 0
		DECLARE @VehicleId bigint = 0
		DECLARE @docHandle int = 1
		DECLARE @tblMaintenanceServiceDetailsXML TABLE (--ServiceDetailsId Bigint,
		ServiceId bigint,ServicedOn Datetime,ServiceCost numeric (10,2)
		--,ServicedBy Bigint
		)
		--AS MaintenanceServiceDetails READONLY
		IF @tblMaintenanceServiceDetails IS NOT NULL
			BEGIN
				EXEC sp_xml_preparedocument @docHandle OUTPUT, @tblMaintenanceServiceDetails
				INSERT INTO @tblMaintenanceServiceDetailsXML
				SELECT * FROM OPENXML(@docHandle, '/DocumentElement/serviceDetails')
				WITH
				(
				--ServiceDetailsId Bigint 'serviceDetailsId'
					ServiceId bigint 'ServiceId'
					,ServicedOn Datetime 'ServicedOn'
					,ServiceCost Numeric(10,2) 'ServiceCost'
					--,ServicedBy Bigint 'ServicedBy'
				)
				--declare @tblMaintenanceServiceDetails1 As MaintenanceServiceDetails
				insert into @tblMaintenanceServiceDetailsXML
				select * from @tblMaintenanceServiceDetailsXML
			END
		-- Get the User Preferences whether miles or kilometer based on the user id

		DECLARE @ConversionFactor numeric (10,2) = 1.0
		SELECT @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END
		FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz
		ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @ModifiedBy
		SELECT @bigCurrentReading = (CASE WHEN ServiceType = 0 OR ServiceType = 3 THEN @bigCurrentReading
		WHEN ServiceType = 1 THEN ((CASE WHEN (@bigCurrentReading / @ConversionFactor) > 0 THEN ROUND((@bigCurrentReading / @ConversionFactor), 0) ELSE (@bigCurrentReading / @ConversionFactor) END))
		ELSE 0 END), @VehiclePlanId = vm.VehiclePlanId, @VehicleId = vp.VehicleId
		FROM rvlfVehicleMaintenanceService vm
		INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId
		WHERE ServiceDetailsId = @bigServiceDetailsId
		-- Get current readings for the vehicle using the vehicle plan id
		CREATE TABLE #temp(ServiceDetailsId bigint, ServiceType int, CurrentReading bigint)
		INSERT INTO #temp(ServiceDetailsId, ServiceType, CurrentReading)
		SELECT vm.ServiceDetailsId, vm.ServiceType, CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3THEN CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0)) as FLOAT)/ 3600 as DECIMAL(18,2))
		WHEN vm.ServiceType = 1 THEN cr.CurrentOdometerReading ELSE 0 END AS CurrentReading
		FROM rvlfVehicleMaintenanceService vm
		INNER JOIN rvlfVehiclePlanAssignment vp ON vm.VehiclePlanId = vp.VehiclePlanId
		INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId
		INNER JOIN rvlfVehicle v ON v.VehicleId = cr.VehicleId
		WHERE vm.VehiclePlanId = @VehiclePlanId AND vm.Status = 0
		BEGIN TRAN MessageOutTransaction
		BEGIN TRY
		DECLARE @bigCurrentEngineHrs AS BIGINT = NULL
		DECLARE @bigCurrentOdometerReading AS BIGINT = NULL
		IF (@tiStatus = 1 OR @tiStatus = 2)
			BEGIN
				SELECT @bigCurrentEngineHrs = CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0)) as FLOAT)/ 3600 as DECIMAL(18,2)),
				@bigCurrentOdometerReading = cr.CurrentOdometerReading
				FROM rvlfVehicleCurrentReadings cr
				INNER JOIN rvlfVehicle v ON v.VehicleId = cr.VehicleId
				WHERE cr.VehicleId = @VehicleId
			END
		IF(@tiStatus = 0 OR @tiStatus = 1)
			BEGIN
				INSERT INTO rvlfMaintenanceServiceDetails(ServiceDetailsId, ServiceId, ServicedOn, ServiceCost, ServicedBy)
				(SELECT distinct @bigServiceDetailsId AS ServiceDetailsId, ServiceId, ServicedOn, ServiceCost, @ModifiedBy
				FROM @tblMaintenanceServiceDetailsXML WHERE ServiceId NOT IN (SELECT sd.ServiceId FROM rvlfMaintenanceServiceDetails sd WHERE sd.ServiceDetailsId = @bigServiceDetailsId))
				UPDATE rvlfVehicleMaintenanceService SET ExecutedOn = @dtExecutionOnDate, ServiceCost = (SELECT SUM(ServiceCost) FROM rvlfMaintenanceServiceDetails WHERE ServiceDetailsId = @bigServiceDetailsId),
				Comments = @vcComments, StatusChangeOn = @bigCurrentReading, EngineHrsOnClose = (CASE WHEN @bigCurrentEngineHrs IS NULL THEN EngineHrsOnClose ELSE @bigCurrentEngineHrs END),
				OdometerReadingOnClose = (CASE WHEN @bigCurrentOdometerReading IS NULL THEN OdometerReadingOnClose ELSE @bigCurrentOdometerReading END),
				Status = @tiStatus, ModifiedBy = @ModifiedBy, ModifiedDateTime = @ModifiedDateTime
				WHERE ServiceDetailsId = @bigServiceDetailsId
			END
		ELSE
			BEGIN
				IF (@tiStatus = 4)
					BEGIN
						UPDATE rvlfVehicleMaintenanceService SET RescheduledOn = @dtScheduleOnDate WHERE ServiceDetailsId = @bigServiceDetailsId
					END
				ELSE
					BEGIN
						UPDATE rvlfVehicleMaintenanceService SET ExecutedOn = @dtExecutionOnDate, StatusChangeOn = @bigCurrentReading,
						EngineHrsOnClose = (CASE WHEN @bigCurrentEngineHrs IS NULL THEN EngineHrsOnClose ELSE @bigCurrentEngineHrs END),
						OdometerReadingOnClose = (CASE WHEN @bigCurrentOdometerReading IS NULL THEN OdometerReadingOnClose ELSE @bigCurrentOdometerReading END),
						Comments = @vcComments, Status = @tiStatus, ModifiedBy = @ModifiedBy, ModifiedDateTime = @ModifiedDateTime
						WHERE ServiceDetailsId = @bigServiceDetailsId
					END
			END
		IF(@tiStatus = 1 OR @tiStatus = 2)
			BEGIN
				-- Update the status with the details for the remaining service type within the same plan
				UPDATE vm SET vm.ExecutedOn = @dtExecutionOnDate, vm.Comments = @vcComments,
				vm.Status = @tiStatus, vm.StatusChangeOn = t.CurrentReading,
				vm.ModifiedBy = @ModifiedBy, vm.ModifiedDateTime = @ModifiedDateTime
				FROM rvlfVehicleMaintenanceService vm
				INNER JOIN #temp t ON t.ServiceDetailsId = vm.ServiceDetailsId
				WHERE vm.VehiclePlanId = @VehiclePlanId AND vm.Status = 0
				IF EXISTS(SELECT mp.RecurringService FROM rvlfVehiclePlanAssignment vp
				INNER JOIN rvlfVehicleMaintenanceService vm ON vm.VehiclePlanId = vp.VehiclePlanId
				INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId
				WHERE ServiceDetailsId = @bigServiceDetailsId AND mp.RecurringService = 1)
					BEGIN
						-- Calculate Due On, Nearing % and insert the details if the plan is recurring
						INSERT INTO rvlfVehicleMaintenanceService(VehiclePlanId, PlanDetailsId, ServiceType, Frequency, StartDate, DueOn, DueOnDate, NearingPercentage, IsNearing, Status, CreatedBy, CreatedDateTime, StatusChangeOn)
						(SELECT ms.VehiclePlanId, ms.PlanDetailsId, mp.ServiceType, mp.Frequency, (CASE WHEN @IsDueOn = 1 THEN ms.DueOnDate ELSE ms.ExecutedOn END) AS StartDate,
						CASE WHEN mp.ServiceType = 0 OR mp.ServiceType = 1 OR mp.ServiceType = 3 THEN ((CASE WHEN @IsDueOn = 1 THEN ms.DueOn ELSE t.CurrentReading END) + mp.ServiceInterval) ELSE 0 END AS DueOn,
						CASE WHEN mp.ServiceType = 2 THEN
						CASE WHEN mp.Frequency = 0 THEN DATEADD(D, mp.ServiceInterval, (CASE WHEN @IsDueOn = 1 THEN ms.DueOnDate ELSE ms.ExecutedOn END))
						WHEN mp.Frequency = 1 THEN DATEADD(M, mp.ServiceInterval, (CASE WHEN @IsDueOn = 1 THEN ms.DueOnDate ELSE ms.ExecutedOn END))
						WHEN mp.Frequency = 2 THEN DATEADD(YEAR, mp.ServiceInterval, (CASE WHEN @IsDueOn = 1 THEN ms.DueOnDate ELSE ms.ExecutedOn END)) ELSE NULL END
						ELSE NULL END AS DueOnDate,
						((CASE WHEN mp.ServiceType = 0 OR mp.ServiceType = 3 THEN (CASE WHEN ((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0)) - ms.StatusChangeOn) >= 0 THEN (((ISNULL(CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0)) as FLOAT)/ 3600 as DECIMAL(18,2)),0)) - ms.StatusChangeOn) * 100) ELSE 0 END)
						WHEN mp.ServiceType = 1 THEN (CASE WHEN (cr.CurrentOdometerReading - ms.StatusChangeOn) >= 0 THEN ((cr.CurrentOdometerReading - ms.StatusChangeOn) * 100) ELSE 0 END)
						WHEN mp.ServiceType = 2 THEN (CASE WHEN DATEDIFF(D, (CASE WHEN @IsDueOn = 1 THEN ms.DueOnDate ELSE ms.ExecutedOn END), GETUTCDATE()) > 0 THEN DATEDIFF(D, (CASE WHEN @IsDueOn = 1 THEN ms.DueOnDate ELSE ms.ExecutedOn END), GETUTCDATE()) ELSE 0 END)*
						100
						END) / (CASE WHEN mp.ServiceType = 0 OR mp.ServiceType = 1 OR mp.ServiceType = 3 THEN mp.ServiceInterval ELSE (
						CASE WHEN mp.Frequency = 0 THEN mp.ServiceInterval
						WHEN mp.Frequency = 1 THEN (mp.ServiceInterval * 30)
						WHEN mp.Frequency = 2 THEN (mp.ServiceInterval * 365) END
						)
						END)) AS NearingPercentage, 0 AS IsNearing, 0 AS Status, @ModifiedBy AS CreatedBy, @ModifiedDateTime AS CreatedDateTime, t.CurrentReading
						FROM rvlfMaintenancePlanDetails mp
						INNER JOIN rvlfVehiclePlanAssignment vp on vp.PlanId = mp.PlanId
						INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId
						INNER JOIN rvlfVehicle v ON v.VehicleId = cr.VehicleId
						INNER JOIN rvlfVehicleMaintenanceService ms on ms.VehiclePlanId = vp.VehiclePlanId AND ms.PlanDetailsId = mp.PlanDetailsId
						INNER JOIN #temp t ON t.ServiceDetailsId = ms.ServiceDetailsId)
						DROP TABLE #temp
						-- Update IsNearing field for the vehicle plan using the calculated nearing (%)
						CREATE TABLE #temp1(VehiclePlanId bigint, Nearing int)
						INSERT INTO #temp1(VehiclePlanId, Nearing)
						SELECT vm.VehiclePlanId, MAX(vm.NearingPercentage) AS Nearing FROM rvlfVehicleMaintenanceService vm
						INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId
						WHERE vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1 AND vm.VehiclePlanId = @VehiclePlanId
						GROUP BY vm.VehiclePlanId
						UPDATE vm SET vm.IsNearing = (CASE WHEN vm.NearingPercentage = t.Nearing THEN 1 ELSE 0 END),
						OverdueDate = (CASE WHEN vm.NearingPercentage >= 100 THEN GETUTCDATE() ELSE OverdueDate END),
						EngineHrsOnDue = (CASE WHEN vm.NearingPercentage >= 100 THEN CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0)) as Float) / 3600 as Decimal(18,2)) ELSE EngineHrsOnDue END),
						OdometerReadingOnDue = (CASE WHEN vm.NearingPercentage >= 100 THEN cr.CurrentOdometerReading ELSE OdometerReadingOnDue END)
						FROM rvlfVehicleMaintenanceService vm
						INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId
						INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId
						INNER JOIN rvlfVehicle v ON v.VehicleId = cr.VehicleId
						INNER JOIN #temp1 t ON t.VehiclePlanId = vm.VehiclePlanId
						WHERE vm.Status = 0
						DROP TABLE #temp1
						-- Update Last Execution On in Vehicle Assignment if the plan is completed
						IF @tiStatus = 1
							BEGIN
								DECLARE @IsEngineHrs AS BIT = 0
								DECLARE @EngineHrs AS BIGINT
								DECLARE @IsOdometerReading AS BIT = 0
								DECLARE @OdometerReading AS BIGINT
								DECLARE @IsTimeBased AS BIT = 0
								DECLARE @TimeBased AS DATETIME
								IF EXISTS (SELECT vp.VehiclePlanId FROM rvlfVehiclePlanAssignment vp
								INNER JOIN rvlfVehicleMaintenanceService vm ON vm.VehiclePlanId = vp.VehiclePlanId
								WHERE vm.VehiclePlanId = @VehiclePlanId AND vm.Status = 0 AND vm.ServiceType = 0 OR vm.ServiceType = 3)
									BEGIN
										SET @IsEngineHrs = 1
										SELECT @EngineHrs = vm.StatusChangeOn FROM rvlfVehiclePlanAssignment vp
										INNER JOIN rvlfVehicleMaintenanceService vm ON vm.VehiclePlanId = vp.VehiclePlanId
										WHERE vm.VehiclePlanId = @VehiclePlanId AND vm.Status = 0 AND vm.ServiceType = 0 OR vm.ServiceType = 3
									END
								IF EXISTS (SELECT vp.VehiclePlanId FROM rvlfVehiclePlanAssignment vp INNER JOIN rvlfVehicleMaintenanceService vm ON vm.VehiclePlanId = vp.VehiclePlanId
								WHERE vm.VehiclePlanId = @VehiclePlanId AND vm.Status = 0 AND vm.ServiceType = 1)
									BEGIN
										SET @IsOdometerReading = 1
										SELECT @OdometerReading = vm.StatusChangeOn FROM rvlfVehiclePlanAssignment vp
										INNER JOIN rvlfVehicleMaintenanceService vm ON vm.VehiclePlanId = vp.VehiclePlanId
										WHERE vm.VehiclePlanId = @VehiclePlanId AND vm.Status = 0 AND vm.ServiceType = 1
									END
								IF EXISTS (SELECT vp.VehiclePlanId FROM rvlfVehiclePlanAssignment vp
								INNER JOIN rvlfVehicleMaintenanceService vm ON vm.VehiclePlanId = vp.VehiclePlanId
								WHERE vm.VehiclePlanId = @VehiclePlanId AND vm.Status = 0 AND vm.ServiceType = 2)
									BEGIN
										SET @IsTimeBased = 1
									END
								UPDATE vp SET vp.EngineHrsStartValue = (CASE WHEN @IsEngineHrs = 1 THEN @EngineHrs ELSE vp.EngineHrsStartValue END),
								vp.OdometerReadingStartValue = (CASE WHEN @IsOdometerReading = 1 THEN @OdometerReading ELSE vp.OdometerReadingStartValue END),
								vp.TimeBasedStartValue = (CASE WHEN @IsTimeBased = 1 THEN @dtExecutionOnDate ELSE vp.TimeBasedStartValue END)
								FROM rvlfVehiclePlanAssignment vp
								WHERE vp.VehiclePlanId = @VehiclePlanId
							END
					END
				ELSE
				BEGIN
				-- Mark as not assigned in Vehicle Plan Assignment when the plan is not recurring
				UPDATE rvlfVehiclePlanAssignment SET AssignedStatus = 0 WHERE VehiclePlanId = @VehiclePlanId
				END
				--Serive close commant sent msg out insert here added by karthikeyan.R on 2020-Mar-11
				IF(@tiStatus=1)
					BEGIN
						declare @PlanName varchar(500),@BoxID varchar(100),@Command varchar(MAX),@sequenceNo bigint,@seralNo varchar(100)
						SELECT @BoxID=va.BoxId,@PlanName=mp.PlanName,@seralNo=RIGHT('0000'+cast(isnull(RunningSerial,0) as varchar),4) FROM rvlfVehiclePlanAssignment vp
						INNER JOIN rvlfVehicleMaintenanceService vm ON vm.VehiclePlanId = vp.VehiclePlanId
						INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId
						inner join rvlfVehicleAssignment VA on vp.VehicleId=VA.VehicleId
						WHERE ServiceDetailsId = @bigServiceDetailsId
						select @sequenceNo=max(SequenceNum) from rvlfMsgOutHst
						set @sequenceNo=isnull(@sequenceNo,0)
						set @seralNo=isnull(@seralNo,RIGHT('0000'+cast(0 as varchar),4))
						Select @Command=('#' + cast(FORMAT(getUTCdate(), 'yy') as varchar) + cast(FORMAT(getUTCdate(), 'MM') as varchar) + cast(FORMAT(getUTCdate(), 'dd') as varchar) + cast(FORMAT(getUTCdate(), 'HH') as varchar) + cast(FORMAT(getUTCdate(), 'mm') as varchar) + cast(FORMAT(getUTCdate(), 'ss') as varchar) + '|' + @BoxID + '|'+ @seralNo +'|0|' + @PlanName + '|**|END|')
						insert into rvlfMsgOutHst(BoxId,SentDateTime,UserId,Priority,ServiceId,BoxCmdOutTypeId,BoxProtocolTypeId,CommInfo1,CommInfo2,CustomProp,SequenceNum,Acknowledged,MessageInID,Scheduled,ScheduleId,isCommentSentStatus,isCommentSentUpdateDate,TriggerCount) values 
													(@BoxID,getUTCdate(),@bigQueryingUser,0,1,43,1,0,0,@Command,@sequenceNo + 1,NULL,NULL,0,NULL,1,GETDATE(),null)
					END
			END
		COMMIT TRAN
		END TRY
		BEGIN CATCH
		ROLLBACK TRAN
		SET @ErrorMessage = 'An Error occured during updation of maintenance service details : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
		END CATCH
		SET NOCOUNT OFF
	END
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateMapping]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
              
CREATE PROCEDURE [dbo].[rvlf_sp_UpdateMapping]              

AS              
-- =============================================              
-- Name   : rvlf_sp_UpdateMapping              
-- Author  : Kapil              
-- Create date : 25-Mar-2014              
-- Description : CheckDuplicate Tyre Mapping Details              
-- Company  : TRINETRA
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
-- =============================================              
BEGIN              
 -- SET NOCOUNT ON added to prevent extra result sets from              
 -- interfering with SELECT statements.              
 SET NOCOUNT ON;      
 
 /****************************Reading XML File and Store into Temp table**************/   

INSERT INTO rvlfTyreHistory(IsRetread,TyreID,TyreMappingID,VehicleID,CreatedDate,Category,AxleID,LocationID,Odometer,Distance) 
--values (@TyreID,@TyreMapId,@VehicleID,GETUTCDATE(),null,@AxleID,@TyreLocationID,0,0)

select IsRethread,TyreID,TyreMappingID,VehicleID,CreatedDateTime,Category,AxleID,TyreLocationID,Odometer,Distance from rvlfTyreVehicleMapping where IsActive = 0 and IsDelete =0
      
         
update rvlfTyreVehicleMapping set IsActive = 1 where IsActive = 0
update rvlfTyreVehicleMapping set isRemap = 0 where isRemap = 1
                  
         
                 
                   
END 





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateMappingAfterRetread]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
              
create PROCEDURE [dbo].[rvlf_sp_UpdateMappingAfterRetread]              

AS              
-- =============================================              
-- Name   : rvlf_sp_UpdateMappingAfterRetread            
-- Author  : Kapil              
-- Create date : 25-Mar-2014              
-- Description : Tyre Mapping Details              
-- Company  : TRINETRA
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
-- =============================================              
BEGIN              
 -- SET NOCOUNT ON added to prevent extra result sets from              
 -- interfering with SELECT statements.              
 SET NOCOUNT ON;      
 
 /****************************Reading XML File and Store into Temp table**************/   

  
--INSERT INTO rvlfTyreHistory(IsRetread,TyreID,TyreMappingID,VehicleID,CreatedDate,Category,AxleID,LocationID,Odometer,Distance) 
----values (@TyreID,@TyreMapId,@VehicleID,GETUTCDATE(),null,@AxleID,@TyreLocationID,0,0)

--select IsRethread,TyreID,TyreMappingID,VehicleID,CreatedDateTime,Category,AxleID,TyreLocationID,Odometer,Distance from rvlfTyreVehicleMapping where IsActive = 0 and IsDelete =0
      
         
update rvlfTyreVehicleMapping set isRemap = 0 where isRemap = 1
update rvlfTyreHistory set isRemap = 0 where isRemap = 1

         
                 
                   
END 





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateMessageReceived]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateMessageReceived]      
@intboxid bigint=null,      
@dtOriginDateTime datetime,      
@dtDateTimeReceived datetime,      
@vcCommMode varchar(100),      
@tiBoxMsgInTypeId TINYINT = null,      
@vcBoxProtocolTypeName varchar(50) = null,      
@vcCommInfo1 varchar(15),      
@siCommInfo2 int ,      
@tiValidGps smallint = 2,      
@dLatitude decimal(10,6) = 0,      
@dLongitude decimal(10,6) = 0,      
@tiSpeed smallint = 0,      
@siHeading smallint = 0,      
@vcSensorMask varchar(8) = null,      
@vcCustomProp varchar(max)= null,      
@bigSequenceNum bigint = null,      
@bitIsArmed bit = null,      
@tiPriority tinyint = null,      
@bitIsAlarm bit =0,      
@dtSentDateTime datetime = null,      
@bitIgnitionStatus bit = null,      
@bigOdoMeterReading bigint = null,      
@bitIsTrinetraApp bit = 0,      
@ModelNo VARCHAR(256) = null,      
@odoValue_app varchar(6) = null,      
@AlarmDesc_app varchar(256) = null,      
@IsPrefAck bit = 0,
@dtSeconday XML = NULL,
@dtPrimary XML = NULL,
@dtFiberCompactors XML = NULL     
AS      
/*********************************************************************************************************************************/      
-- Name : [rvlf_sp_UpdateMessageReceived]      
-- Description : To insert the messages that is sent to the device      
-- Author : V.Narayanasamy      
-- Company : Angler Technologies      
-- History : <<Date(dd-MON-yyyy)>> Initial Reason      
-- : 11-Oct-2011 VN Created Intial Version      
-- : 22-Nov-2011 Ranjith Add Geozone issue (Geozone id assigned instead of Geozone no for VehicleGeozone table)      
-- : 27-Jan-2012 Sakthi Casting for add geozone and Geozone id instead of Geozone no for deleting geozone      
-- : 11-May-2012 Sakthi Update the odometer and duration column with values      
-- : 11-Oct-2012 Sakthi Update reporting interval and speed threshold to master vehicle table      
-- : 17-Oct-2012 Set speed is 0 by default for extreme and harsh braking / acceleration      
-- : 23-Oct-2013 Sakthi Log the geozone based Trip details      
-- : 16-Nov-2013 Sakthi Track the trip details by vehicle wise to other clients      
-- : 29-Oct-2018 Asanraj Incluede OrganizationId for 412      
/*********************************************************************************************************************************/      
 BEGIN      
  SET NOCOUNT ON    
  DECLARE @startdate datetime,@enddate datetime,@Msgin varchar(50)  
  SET @startdate=getdate()  
  --For input Parameters verification from SLS service.      
  --if(@tiBoxMsgInTypeId in (20,22,114) and @dtSentDateTime IS not null)      
  --begin      
  --insert into SLSParam values(getdate(),isnull(cast(@intBoxID as varchar),',zz') + ' $ ' + isnull(cast(@dtOriginDateTime as varchar),',ZZ') + ' $ ' +      
  --isnull(cast(@dtDateTimeReceived as varchar),',zz') + ' $ ' + isnull( @vcCommMode,',zz') + ' $ ' + isnull( cast(@tiBoxMsgInTypeId as varchar),',zz') + ' $ ' +      
  --isnull(@vcBoxProtocolTypeName,',zz') + ' $ ' + isnull(@vcCommInfo1,',zz') + ' $ ' + isnull(cast(@siCommInfo2 as varchar),',zz') + ' $ ' +      
  --isnull(cast(@tiValidGps as varchar),',zz') + ' $ ' + isnull(cast(@dLatitude as varchar),',zz') + '$' + isnull(cast(@dLongitude as varchar),',zz') + ' $ ' +      
  --isnull(cast(@tiSpeed as varchar),',zz') + ' $ ' + isnull(cast(@siHeading as varchar),',zz') + ' $ ' + isnull(@vcSensorMask,',zz') + ' $ ' +      
  --isnull(@vcCustomProp,',zz') + ' $ ' + isnull( cast(@bigSequenceNum as varchar),',zz') + ' $ ' + isnull( cast(@bitIsArmed as varchar),',zz') + ' $ ' +      
  --isnull(cast(@tiPriority as varchar),',zz') + ' $ ' + isnull( cast(@bitIsAlarm as varchar),',zz') + ' $ ' + isnull(cast(@dtSentDateTime as varchar),',zz') + ' $ ' +      
  --isnull(cast(@bitIgnitionStatus as varchar),',zz') + ' $ ' + isnull(cast(@bigOdoMeterReading as varchar),',zz'))      
  --end      
  if(@intboxid = 0 and @tiBoxMsgInTypeId = 20)  
  Begin  
 Set @intboxid = (select Top 1 BoxId from rvlfMsgOutHst where CommInfo1 = @vcCommInfo1 and CommInfo2 = @siCommInfo2 and SUBSTRING(CustomProp, 10, 7) =  SUBSTRING(@vcCustomProp, 11, 7) order by SentDateTime desc )   
 Set @dtSentDateTime = (select Top 1 SentDateTime from rvlfMsgOutHst where CommInfo1 = @vcCommInfo1 and CommInfo2 = @siCommInfo2 and SUBSTRING(CustomProp, 10, 7) =  SUBSTRING(@vcCustomProp, 11, 7) order by SentDateTime desc)   
  End  
  
  DECLARE @bigOrganizationID bigint=(SELECT OrganizationID FROM rvlfBoxId with(nolock) WHERE BoxId = @intBoxID)      
  declare @OrganizationPackage table (packageid bigint,Moduleid bigint,operationid bigint,OperationTypeName varchar(500),operationdesc varchar(500))      
 
 if(@tiBoxMsgInTypeId in (121,158,188,113,96)) --22-07-2020 to avoid unwanted msg in msginhst table and track any repeated msg due to device issue 
 begin
 INSERT INTO rvlfmsginhst_resetmsg      
          (      
          BoxID , OriginDateTime , DateTimeReceived , ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,      
          CommInfo2 , ValidGps , Latitude ,Longitude , Speed , Heading , SensorMask , CustomProp , SequenceNum ,      
          IsArmed , Priority , StreetAddress, NearestLandmark , IsNotificationSent,odometer,IsProcessed,IsArchived      
          )               
          VALUES      
          (      
          @intBoxID , @dtOriginDateTime , @dtDateTimeReceived , 4 ,@tiBoxMsgInTypeId, 1 , @vcCommInfo1 ,      
          @siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed ,-1 , @vcSensorMask , @vcCustomProp , @bigSequenceNum ,      
          @bitIsArmed , @tiPriority ,CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,NULL,0,CAST(@odoValue_app as bigint),      
          CASE WHEN @tiValidGps = 0 THEN 1 ELSE NULL END,0      
          ) 
 end 
  --IF @intBoxID NOT IN (481,482,6846,358480082009731, 358480082009657, 358480082009491) and @tiBoxMsgInTypeId not in(188,113,121,158) --  
  else --IF @intBoxID NOT IN (8717,8768) and @tiBoxMsgInTypeId not in(96,188,113,158) -- ,121 commented 22-07-2020
   BEGIN      
    Declare @SMSbasedQueryError int = 0      
    IF @tiBoxMsgInTypeId = 114 and (@vcCustomProp like '%SendSMSQuery:1%')      
     Begin      
      select @intBoxID = va.BoxId from rvlfVehicleAssignment va with(nolock) inner join rvlfVehicle v on v.VehicleId =va.VehicleId      
      where v.VehicleDescription =      
      SUBSTRING(@vcCustomProp, CHARINDEX('VehicleName:',@vcCustomProp,0)+12,(CHARINDEX(';',@vcCustomProp,CHARINDEX('VehicleName:',@vcCustomProp,1))) -(CHARINDEX('VehicleName:',@vcCustomProp,1)+12))      
      DECLARE @CommandId Bigint      
      DECLARE @MobileNo varchar(20),@VCSmsMsg varchar(max),@VCSmsMsgUserRights varchar(max)      
      Declare @SMSAlertMsgs varchar(max)      
      Declare @Userid varchar(50),      
      @OrganizationID varchar(50),      
      @UserName varchar(50),      
      @Email varchar(50),      
      @FleetId varchar(50),      
      @FleetName varchar(500)      
      Declare @VehicleID varchar(50),@VehicleDescription varchar(50),@VehicleName varchar(50),@LicensePlate varchar(50)      
      SELECT @MobileNo = CAST(REPLACE(SUBSTRING(@vcCustomProp, CHARINDEX('MobileNo:',@vcCustomProp,0)+9,(CHARINDEX(';',@vcCustomProp,CHARINDEX('MobileNo:',@vcCustomProp,1))) -(CHARINDEX('MobileNo:',@vcCustomProp,1)+9)),'+','') AS bigint),      
      @CommandId = SUBSTRING(@vcCustomProp, CHARINDEX('Command:',@vcCustomProp,0)+8,LEN(@vcCustomProp))      
      Select @OrganizationID=OrganizationId,@UserName=UserName,@Email=Email,@Userid=UserId from rvlfuser where MobileNo = @MobileNo --set @MobileNo = 9585846164      
      set @VCSmsMsgUserRights = dbo.rvlf_fn_GetSMSCommandUserRights(@MobileNo,@intBoxID)      
      if @VCSmsMsgUserRights <> '' and @VCSmsMsgUserRights is not null --and @intBoxID <> ''      
       Begin      
        Set @VCSmsMsg = @VCSmsMsgUserRights      
       end      
      Else    
       Begin      
        Set @VCSmsMsg = dbo.rvlf_fn_GetSMSCommand(@CommandId,@vcCustomProp)      
       End      
      if @intBoxID = '' or @VCSmsMsgUserRights <> ''      
       Begin      
        If @VCSmsMsgUserRights <> '' and @VCSmsMsgUserRights is not null --and @intBoxID <> ''      
        Set @SMSAlertMsgs = @VCSmsMsg      
        Else IF @CommandId = 255 --and @VCSmsMsgUserRights ='' and @VCSmsMsgUserRights is null      
        Set @SMSAlertMsgs = 'Invalid command. Send Tri HELP to know the available commands and inputs.'      
        Else IF @CommandId = 254 --and @VCSmsMsgUserRights ='' and @VCSmsMsgUserRights is null      
        Set @SMSAlertMsgs = @VCSmsMsg      
        Else --if @VCSmsMsgUserRights ='' and @VCSmsMsgUserRights is null      
        Set @SMSAlertMsgs = 'Please check the vehicle name and resend the command.'      
        --_SendSMSTest      
        insert into rvlfNotificationLog(MessageInID,OriginDateTime,DateTimeReceived,CanSendSMS,IsSMSSent,Userid,OrganizationID,      
        UserName,Email,MobileNo,StreetAddress,Speed,Boxid,BoxMsgInTypeName,VehicleID,VehicleDescription,      
        VehicleName,Fleetid,Fleetname,LicensePlate,Subjectsufix,MessageDetails,CanSendEmail,SMSScheduleID)      
        values      
        (null,@dtOriginDateTime,@dtOriginDateTime,1,0,@Userid,@OrganizationID,@UserName,@Email,@MobileNo,      
        'N/A',0,000,@tiBoxMsgInTypeId,null,null,null,null,null,null,'Notify',@SMSAlertMsgs,0,0)      
        set @SMSbasedQueryError = 1      
       End      
     End      
    if @intBoxID <> 000 -- Validating Boxid for SMS based Query      
     Begin      
      IF @bitIsTrinetraApp = 1 AND @ModelNo IS NOT NULL      
       BEGIN      
        --For mobile application      
        DECLARE @MsgInID_App TABLE (uiMsgInID uniqueidentifier)      
        DECLARE @uiMsgInID_App uniqueidentifier      
        DECLARE @orgId int      
        DECLARE @dtLastValidGPSTime_app datetime      
        SELECT @intBoxID = mb.BoxID,@orgId=b.OrganizationId FROM rvlfModelBoxSettings_App mb      
        INNER JOIN rvlfModel_App ap ON ap.ModelId=mb.ModelId      
        INNER JOIN rvlfBoxId b ON b.BoxId=mb.BoxId WHERE ap.ModelCode=@ModelNo      
        IF @intBoxID IS NULL      
         BEGIN      
          RAISERROR('Given asset details not mapped in the software side', 16,1)      
         END      
        ELSE      
         BEGIN      
          --Last valid location update      
          IF @tiValidGps =3 BEGIN SELECT @tiValidGps =0,@tiBoxMsgInTypeId=8 END      
          --Preference settings ack received      
          IF @IsPrefAck = 1 BEGIN UPDATE dbo.rvlfModel_App SET IsChanged= 0 WHERE ModelCode=@ModelNo END      
          --If message is alarm, set type      
          IF @bitIsAlarm =1 AND @vcCustomProp NOT LIKE '%Param=Preference Changed%' AND @tiValidGps <> 3 BEGIN SET @tiBoxMsgInTypeId = 4 END      
          --If datetime received is lesser than origin datetime      
          IF @dtDateTimeReceived < @dtOriginDateTime BEGIN SET @dtDateTimeReceived = DATEADD(SECOND,3,@dtOriginDateTime) END      
          -- Log mobile messages into server      
          INSERT INTO rvlfMsgInHSt      
          (      
          BoxID , OriginDateTime , DateTimeReceived , ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,      
          CommInfo2 , ValidGps , Latitude ,Longitude , Speed , Heading , SensorMask , CustomProp , SequenceNum ,      
          IsArmed , Priority , StreetAddress, NearestLandmark , IsNotificationSent,odometer,IsProcessed,IsArchived      
          )      
          OUTPUT INSERTED.MessageInID into @MsgInID_App      
          VALUES      
          (      
          @intBoxID , @dtOriginDateTime , @dtDateTimeReceived , 4 ,@tiBoxMsgInTypeId, 1 , @vcCommInfo1 ,      
          @siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed ,-1 , @vcSensorMask , @vcCustomProp , @bigSequenceNum ,      
          @bitIsArmed , @tiPriority ,CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,NULL,0,CAST(@odoValue_app as bigint),      
          CASE WHEN @tiValidGps = 0 THEN 1 ELSE NULL END,0      
          )      
          SELECT @uiMsgInID_App = uiMsgInID FROM @MsgInID_App      
          --For display the current location of mobile devices      
          IF @tiValidGps <> 0      
           BEGIN      
            SELECT @dtLastValidGPSTime_app = ISNULL(max(OriginDateTime), @dtOriginDateTime) FROM rvlfMsgInHst WHERE BoxId = @intBoxID and ValidGps = 0 --and SensorMask IS NOT NULL      
           END      
          DECLARE @dtLastValidDateTime_app DateTime=(SELECT LastValidDateTime FROM rvlfBoxId WHERE BoxId = @intBoxID)      
          -- Checks if the last information exists for the box, if so updates else inserts      
          IF @dtOriginDateTime >= @dtLastValidDateTime_app AND @tiBoxMsgInTypeId NOT IN (121,188)      
           BEGIN      
            UPDATE rvlfBoxId SET BoxArmed = 1,LastValidDateTime = CASE WHEN @tiValidGps = 0 THEN @dtOriginDateTime ELSE LastValidDateTime END,      
            LastLatitude = @dLatitude,LastLongitude = @dLongitude,LastSpeed = @tiSpeed,      
            LastCommunicatedDateTime = @dtDateTimeReceived,LastSensorMask = @vcSensorMask,OrganizationId = @orgId,      
            LastStatusDateTime = @dtOriginDateTime,LastStreetAddress = CASE WHEN @tiValidGps = 0 THEN NULL ELSE LastStreetAddress END,      
            NearestLandmark = CASE WHEN @tiValidGps = 0 THEN NULL ELSE NearestLandmark END,Heading = @siHeading,MessageInId = @uiMsgInID_App      
            WHERE BoxId = @intBoxID      
           END      
          --If message is alarm      
          IF @bitIsAlarm =1      
           BEGIN      
            INSERT INTO rvlfAlarm(AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,DriverId)      
             VALUES(3,@dtOriginDateTime,@intBoxID,91,@dLatitude,@dLongitude,@AlarmDesc_app,(CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END), NULL)       
           END      
          --Get the preference settings      
          SELECT a.ModelId,a.ModelCode,CASE WHEN ISNULL(a.IsChanged,0)=0 THEN '0' ELSE '1' END AS IsChanged FROM dbo.rvlfModel_App a      
          INNER JOIN rvlfModelBoxSettings_App bx ON bx.ModelId=a.ModelId WHERE ModelCode=@ModelNo      
          --SELECT ModelId,ModelCode,ISNULL(IsChanged,0) AS IsChanged FROM dbo.rvlfModel_App WHERE ModelCode=@ModelNo      
         END      
       END      
      ELSE      
       BEGIN      
        IF (@tiBoxMsgInTypeId <> 52)      
         BEGIN--CONDITION 01 START      
          DECLARE @tintSensor tinyint=CASE WHEN @vcCustomProp LIKE '%SENSOR_NUM=%' THEN      
          CAST(dbo.rvlf_fn_getparamvaluewithindex(@vccustomprop,'SENSOR_NUM=',';')AS TINYINT) ELSE 0 END      
          --SUBSTRING(@vcCustomProp,CHARINDEX('%SENSOR_NUM=%',@vcCustomProp,0)+12,(CHARINDEX(';',@vcCustomProp,(CHARINDEX('%SENSOR_NUM=%',@vcCustomProp,0)))-(CHARINDEX('%SENSOR_NUM=%',@vcCustomProp,0)+12)))      
          DECLARE @tintBoxgnore tinyint=(SELECT COUNT(igid) FROM rvlfboxignoremsgs WHERE BOXID =@intBoxID AND      
          BOXMSGINTYPEID=@tiBoxMsgInTypeId AND SENSORNO=@tintSensor)      
          IF(@tintBoxgnore=0)      
          DECLARE @tintOrgIgnore tinyint=(SELECT count(igid) FROM rvlforgignoremsgs WHERE ORGID =@bigOrganizationID      
          AND BOXMSGINTYPEID=@tiBoxMsgInTypeId AND SENSORNO=@tintSensor)      
          --CHECK THE IGNORE MESSAGES BASED ON THE RVLFBOXIGNOREMSGS TABLE      
          IF(@tintBoxgnore=0)      
          IF(@tintOrgIgnore=0)      
           BEGIN      
            IF Exists (SELECT MessageInID FROM rvlfMsgInHst with(nolock) WHERE BoxId = @intBoxID AND BoxMsgInTypeId = @tiBoxMsgInTypeId      
            AND OriginDateTime = @dtOriginDateTime and CustomProp=@vcCustomProp)      
             BEGIN      
              RAISERROR('Data Integrity Violation1', 16,1)      
             END      
            ELSE      
             BEGIN--CONDITION 02 START      
              -- Local variables to hold the intermediate results      
              IF @intBoxID = 999986      
               BEGIN      
                SET @dLatitude = '12.920182'      
                SET @dLongitude = '77.679921'      
                SET @tiValidGps = 0      
               END      
              DECLARE @ErrorMessage varchar(3000)      
              DECLARE @intBoxProtocolTypeId int      
              DECLARE @tiServiceID tinyint      
              DECLARE @tiCommModeId tinyint      
              DECLARE @MsgInID TABLE ( uiMsgInID uniqueidentifier)      
              DECLARE @uiMsgInID1 uniqueidentifier      
              DECLARE @uiMsgInID uniqueidentifier      
              DECLARE @vcNewIP varchar(25)      
              SET @vcNewIP = @vcCommInfo1 + ':'+ CAST(@siCommInfo2 AS varchar(5))      
              DECLARE @dtLastValidGPSTime datetime      
              DECLARE @bitCreateAlarm bit      
              DECLARE @tiAlarmLevelID tinyint      
              DECLARE @bigGeoZoneID bigint      
              DECLARE @vcAlarmLevelName varchar(30)      
              /********** demo*************/      
              DECLARE @DemoMsgInID TABLE ( uiDemoMsgInID uniqueidentifier)      
              DECLARE @uiDemoMsgInID uniqueidentifier      
              DECLARE @vcOldIP varchar(25)      
              SET @vcNewIP = @vcCommInfo1 + ':'+ CAST(@siCommInfo2 AS varchar(5))      
              --DECLARE @bitCanNotify bit      
              SET @dtLastValidGPSTime = @dtOriginDateTime      
              DECLARE @IsAddressAlreadyAvailable bit = 0      
              DECLARE @vcStreetAddress varchar(250)      
   DECLARE @vcNearestLandmark varchar(300)      
              /*********end *****************/      
              SET @dtLastValidGPSTime = @dtOriginDateTime      
              --update the origindatetime if origindatetime is greater then current date time      
              IF(@dtOriginDateTime>CONVERT(datetime,CONVERT(varchar(19),SYSUTCDATETIME())))      
               BEGIN      
                SET @dtOriginDateTime=CONVERT(datetime,CONVERT(varchar(19),SYSUTCDATETIME()))      
               END      
              --update the datetimerecived if datetimerecived is greater then origindatetime      
              IF(@dtOriginDateTime>=@dtDateTimeReceived)      
               BEGIN      
                SET @dtDateTimeReceived=DATEADD(S,2,@dtOriginDateTime)      
               END      
              IF(@tiBoxMsgInTypeId=100 AND CHARINDEX('RF_ID=',@vcCustomProp,0) > 1)      
               BEGIN --RFID Automate Schedule START      
                SET @vcSensorMask='00000000'      
                DECLARE @rfDRIVERID BIGINT=NULL      
          SELECT @rfDRIVERID=DriverId FROM rvlfIButtonMapping      
                WHERE IButtonKey=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RF_ID=',';') AND OrganizationId=@bigOrganizationID      
                -- updated BoxID aganist Driver based on Ibutton punch      
                DECLARE @rfResult varchar(5)      
                DECLARE @dtRFPunchIn DATETIME=NULL,@AssignmentId INT = NULL      
                SET @rfResult = dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'Punch:',';')      
                IF @rfDRIVERID IS NOT NULL      
                 BEGIN      
                  IF(@rfResult='OUT')      
                   BEGIN      
                    SELECT TOP 1 @AssignmentId=AssignmentId,@dtRFPunchIn=PunchIn FROM rvlfDriverAssignment      
                    WHERE BoxID=@intBoxID AND DriverId=@rfDRIVERID AND PunchOut IS NULL ORDER BY PunchIn DESC      
                    IF(@dtRFPunchIn IS NOT NULL)      
                     BEGIN      
                      UPDATE rvlfDriverAssignment SET PunchIn =@dtRFPunchIn,PunchOut=@dtOriginDateTime WHERE BOXID=@intBoxID AND DriverId=@rfDRIVERID AND AssignmentId=@AssignmentId AND PunchIn=@dtRFPunchIn      
                     END      
                   END      
                  ELSE      
                   BEGIN      
                    IF EXISTS (SELECT 1 FROM rvlfDriverAssignment WHERE BoxId=@intBoxID AND PunchIn IS NOT NULL AND PunchOut IS NULL AND DriverId=@rfDRIVERID)      
                     BEGIN      
                     UPDATE rvlfDriverAssignment SET PunchOut=DATEADD(SECOND,-30,@dtOriginDateTime) WHERE BoxId=@intBoxID AND PunchIn IS NOT NULL AND PunchOut IS NULL AND DriverId=@rfDRIVERID      
                     END      
                    INSERT INTO rvlfDriverAssignment(DriverId,PunchIn,PunchOut,BOXID,AssignmentDate,IsAmtIssued,AssignedDate)      
                    VALUES(@rfDRIVERID,@dtOriginDateTime,NULL,@intBoxID,CONVERT(DATE,GETDATE()),0,GETDATE())      
                   END      
                 END      
               END--RFID Automate Schedules END      
              --update driver key messages      
              IF(@tiBoxMsgInTypeId=76)      
               BEGIN --CONDITION 03 START      
                SET @vcCustomProp=@vcCustomProp+'ignition='+CAST(@bitIgnitionStatus as varchar)+';'      
                SET @vcSensorMask='00000000'      
                DECLARE @DRIVERID BIGINT=NULL      
                SELECT @DRIVERID=DriverId FROM rvlfIButtonMapping      
                WHERE IButtonKey=CASE WHEN @vcCustomProp LIKE '%Driver ID=%'      
                THEN CAST(SUBSTRING (@vcCustomProp,CHARINDEX('Driver ID=',@vcCustomProp,1)+10,      
                CHARINDEX(';',@vcCustomProp,CHARINDEX('Driver ID=',@vcCustomProp,1)) -      
                (CHARINDEX('Driver ID=',@vcCustomProp,1)+10)) as varchar) ELSE '0' END AND OrganizationId=@bigOrganizationID      
                -- updated BoxID aganist Driver based on Ibutton punch      
                DECLARE @result varchar(5)      
                SET @result = CASE WHEN @vcCustomProp LIKE '%Driver Status=%'      
                THEN CAST(SUBSTRING (@vcCustomProp,CHARINDEX('Driver Status=',@vcCustomProp,1)+14,      
                CHARINDEX(';',@vcCustomProp,CHARINDEX('Driver Status=',@vcCustomProp,1)) - (CHARINDEX('Driver Status=',@vcCustomProp,1)+14)) as varchar) ELSE 'OUT' END      
                IF(@result='OUT')      
                 BEGIN      
                  DECLARE @dtPunchin DATETIME=NULL      
                  SELECT @dtPunchin=PUNCHINTIME FROM rvlfIButtonMapping WHERE BoxID=@intBoxID AND DriverId=@DRIVERID      
                  IF(@dtPunchin IS NOT NULL)      
                   BEGIN      
                    IF EXISTS(SELECT AssignmentId FROM rvlfDriverAssignment WHERE BOXID=@intBoxID AND DriverId=@DRIVERID AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime)     
     AND CONVERT(DATE,ToTime)) AND (@dtPunchin <=ToTime) AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime) AND PunchIn IS NULL AND PunchOut IS NULL)      
             BEGIN      
                      UPDATE rvlfDriverAssignment SET PunchIn =@dtPunchin,PunchOut=@dtOriginDateTime      
                      WHERE BOXID=@intBoxID AND DriverId=@DRIVERID      
                      AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime)      
                      AND CONVERT(DATE,ToTime)) AND (@dtPunchin <=ToTime)      
                      AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime)      
                      AND PunchIn IS NULL AND PunchOut IS NULL      
                     END      
                    ELSE IF EXISTS(SELECT AssignmentId FROM rvlfDriverAssignment WHERE BOXID=@intBoxID AND DriverId=@DRIVERID AND (CONVERT(DATE,@dtOriginDateTime)     
     BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime)) AND (@dtPunchin <=ToTime) AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime) AND     
     PunchIn IS NOT NULL AND PunchOut IS NOT NULL)      
                     BEGIN      
                      INSERT INTO rvlfDriverAssignment(DriverId,FromTime,ToTime,PunchIn,PunchOut,BOXID,AssignmentDate,IsAmtIssued,AssignedDate)      
                      SELECT TOP 1 @DRIVERID,FromTime,ToTime,@dtPunchin,@dtOriginDateTime,@intBoxID,CONVERT(DATE,GETDATE()),0,GETDATE()      
                      FROM rvlfDriverAssignment      
                      WHERE BOXID=@intBoxID AND DriverId=@DRIVERID      
                      AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime))      
                      AND (@dtPunchin <=ToTime)      
                      AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime)      
                      AND PunchIn IS NOT NULL AND PunchOut IS NOT NULL      
                     END      
                    ELSE      
                     BEGIN      
                      INSERT INTO rvlfDriverAssignment(DriverId,PunchIn,PunchOut,BOXID,AssignmentDate,IsAmtIssued,AssignedDate)      
                      VALUES(@DRIVERID,@dtPunchin,@dtOriginDateTime,@intBoxID,CONVERT(DATE,GETDATE()),0,GETDATE())      
                     END      
                   END      
                 END      
                UPDATE RVLFIButtonMapping SET Boxid = CASE WHEN @result = 'IN' THEN @intBoxID ELSE 0 END,      
                PunchInTime=CASE WHEN @result = 'IN' THEN @dtOriginDateTime ELSE NULL END WHERE DriverId = @DRIVERID      
                IF(@DRIVERID IS NOT NULL)      
                 BEGIN      
                  SET @vcCustomProp=@vcCustomProp+'MAPID='+CAST(@DRIVERID as varchar)      
                 END      
                ELSE      
                 BEGIN      
                  SET @vcCustomProp=@vcCustomProp+'MAPID=0'      
                 END      
               END--CONDITION 03 END    
              --GET THE PROTOCOLID BASED ON THE PROTOCOL NAME      
              SELECT @intBoxProtocolTypeId = BoxProtocolTypeId FROM rvlfBoxProtocolType WHERE BoxProtocolTypeName = @vcBoxProtocolTypeName      
              --GET THE COMMAND MODE ID BASED ON THE COMMANDMODE NAME      
              SELECT @tiCommModeId = CommModeId FROM rvlfCommMode WHERE CommModeName = @vcCommMode      
              --GET THE PROTOCOLID BASED ON THE PROTOCOL NAME      
              SELECT @tiServiceID = ServiceID FROM rvlfServices WHERE CommModeId = @tiCommModeId      
              /***************************Severity Settings**********************************/      
              -- Checks if the message has the severity settings such that an alarm has to be created.      
              IF EXISTS (SELECT BoxId FROM rvlfBoxMsgSeverity WHERE BoxId=@intBoxID AND BoxMsgInTypeId = @tiBoxMsgInTypeID)      
               BEGIN      
                DECLARE @intDuration int = 1      
                IF @tiBoxMsgInTypeId = 9      
                 BEGIN      
                  SET @intDuration = CAST (SUBSTRING (@vcCustomProp, CHARINDEX(':',@vcCustomProp,1)+1, CHARINDEX(';',@vcCustomProp)-1 -CHARINDEX(':',@vcCustomProp,1)) as Int)      
 END      
                IF @intDuration > 0      
                 BEGIN      
                  SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.AlarmLevelID, @vcAlarmLevelName = s.AlarmLevelName FROM rvlfBoxMsgSeverity bs INNER JOIN rvlfSeverity s On bs.AlarmLevelID = s.AlarmLevelId WHERE bs.BoxId = @intBoxID   
      AND bs.BoxMsgInTypeId = @tiBoxMsgInTypeID      
                 END      
               END      
              ELSE      
               BEGIN      
                SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.DefaultAlarmLevel,@vcAlarmLevelName = s.AlarmLevelName FROM rvlfBoxProtocolMsgInType bs INNER JOIN rvlfSeverity s On bs.DefaultAlarmLevel = s.AlarmLevelId WHERE bs.BoxMsgInTypeId



   
    
= @tiBoxMsgInTypeID      
               END      
              IF @tiBoxMsgInTypeId =5 OR @tiBoxMsgInTypeId =6      
               BEGIN
				set @bigGeoZoneID=cast(dbo.rvlf_fn_getparamvaluewithindex(@vccustomprop,'GeozoneID=',';') as bigint)
                --SET @bigGeoZoneID =CAST(SUBSTRING(@vcCustomProp,CHARINDEX('=',@vcCustomProp,1)+1, (CHARINDEX(';',@vcCustomProp,1)- CHARINDEX('=',@vcCustomProp,1))-1) as bigint)      
                SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = s.AlarmLevelId, @vcAlarmLevelName = s.AlarmLevelName FROM rvlfOrganizationGeozone g INNER JOIN rvlfSeverity s ON g.SeverityId = s.AlarmLevelId   
    WHERE g.OrganizationId = @bigOrganizationID AND g.GeozoneId = @bigGeoZoneID
				
				--Update rvlfBoxId set LastGeoZoneStatus= case when @tiBoxMsgInTypeId=5 then 1 else case when @tiBoxMsgInTypeId=6 then 0 end end,LastGeozoneID=@bigGeoZoneID,LastGeozoneINOUTdt=@dtOriginDateTime where BoxId=@intboxid
               END      
              IF @tiBoxMsgInTypeId = 11      
               BEGIN      
                DECLARE @tiSensorID tinyint,@intSensorStateStart int,@intSensorStateEnd int, @vcSensorStatus varchar(10),@bitIsOn bit      
                SET @tiSensorID = CAST(SUBSTRING(@vcCustomProp,CHARINDEX('=',@vcCustomProp)+1,1) As tinyint)      
                SET @intSensorStateStart = CHARINDEX('=',@vcCustomProp,LEN('SENSOR_NUM=')+1)      
                SET @intSensorStateEnd = CHARINDEX(';',@vcCustomProp,15)      
                SET @vcSensorStatus =      
                CASE WHEN @vcCustomProp LIKE '%SENSOR_STATUS=%' THEN dbo.rvlf_fn_getparamvaluewithindex(@vccustomprop,'SENSOR_STATUS=',';')      
                -- SUBSTRING(@vcCustomProp,CHARINDEX('SENSOR_STATUS=',@vcCustomProp,0)+14,      
                -- (CHARINDEX(';',@vcCustomProp,(CHARINDEX('SENSOR_STATUS=',@vcCustomProp,0)))-(CHARINDEX('SENSOR_STATUS=',@vcCustomProp,0)+14)))      
                ELSE SUBSTRING(@vcCustomProp,@intSensorStateStart+1, @intSensorStateEnd - @intSensorStateStart-1)END      
                SET @bitIsOn = CASE WHEN @vcSensorStatus = 'OPEN' OR @vcSensorStatus = 'ON'      
                OR @vcSensorStatus = 'NORMAL' OR @vcSensorStatus = 'OK' THEN 1      
                WHEN @vcSensorStatus = 'CLOSE' OR @vcSensorStatus = 'OFF' OR @vcSensorStatus = 'LOW' THEN 0      
                END      
             IF EXISTS (SELECT BoxId FROM rvlfBoxSensorsCfg WHERE BoxId = @intBoxID AND SensorId = @tiSensorID)      
                 BEGIN      
                  SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = s.AlarmLevelId, @vcAlarmLevelName = s.AlarmLevelName FROM rvlfBoxSensorsCfg bs INNER JOIN rvlfSeverity s ON s.AlarmLevelId = (CASE WHEN @bitIsOn=1 THEN bs.AlarmLevelOn   
      ELSE AlarmLevelOff END) WHERE bs.BoxId = @intBoxID AND bs.SensorId = @tiSensorID      
                 END      
                ELSE      
                 BEGIN      
                  SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.DefaultAlarmLevel, @vcAlarmLevelName = s.AlarmLevelName FROM rvlfBoxProtocolMsgInType bs INNER JOIN rvlfSeverity s On bs.DefaultAlarmLevel = s.AlarmLevelId   
      WHERE bs.BoxMsgInTypeId = @tiBoxMsgInTypeID      
                 END      
               END      
              IF @tiBoxMsgInTypeId = 27      
               BEGIN      
                SET @bitCreateAlarm = 1      
               END      
              IF @tiBoxMsgInTypeId IN (14,15,16,17)      
               BEGIN      
                SET @tiSpeed = 0      
               END      
              DECLARE @trancount int;      
              SET @trancount = @@trancount;      
              --PRINT CAST(@trancount as varchar)      
               BEGIN TRY      
                IF @trancount = 0      
                BEGIN TRANSACTION;      
            ELSE      
                SAVE TRANSACTION MessageTransaction;      
                /***********************Message In History*************************************/      
                --BEGIN TRAN MessageTransaction      
                --BEGIN TRY      
                --PRINT 'Welcome 1'      
				
				 IF EXISTS(select * from rvlfRouteVehicleAssignment rva inner join rvlfRouteVehicleAssignmentDetails RVAD on RVA.AssignmentId=RVAD.AssignmentId inner join rvlfVehicleAssignment va on rva.VehicleId = va.VehicleId where BoxId =@intboxid and rva.TripStatus=2 and CONVERT(date,RVAD.AssignmentDate) = CONVERT(Date,GETDATE()))
					BEGIN
						--Karthick
						
						declare @landmarkID bigint=0
						declare @NearLandmarkList table(ID int identity(1,1),LandmarkID Bigint)

						SET @landmarkID = null        

						declare @tblRouteLandmark table(id int identity(1,1),AssignmentID bigint,RouteID bigint,TripStatus int,LandmarkID bigint)
						insert into @tblRouteLandmark(AssignmentID,RouteID,TripStatus,LandmarkID)
						select RVA.AssignmentId,RVA.RouteId,RVAD.TripStatus,RD.LndID from rvlfRouteVehicleAssignment RVA 
								inner join rvlfRouteVehicleAssignmentDetails RVAD on RVA.AssignmentId=RVAD.AssignmentId
								inner join rvlfRouteMaster RM on RVA.RouteId=RM.RouteID 
								inner join rvlfRouteDetails RD on RD.RouteID=RM.RouteID 
								inner join rvlfVehicleAssignment VA on RVA.VehicleId=VA.VehicleId
								where isnull(RVA.Isdelete,0)=0 and va.BoxId=@intboxid and RVAD.TripStatus=2 and CONVERT(date,RVAD.AssignmentDate) = CONVERT(Date,GETDATE())

						SELECT top 1 @landmarkID = A.LandmarkID FROM                 
						(select distinct L.LandMarkId,
									  ROUND((MIN(DEGREES(ACOS(
									  (                
							  SIN(RADIANS(L.Latitude)) *                                            
							  SIN(RADIANS(@dLatitude)) +                                            
							  COS(RADIANS(L.Latitude)) *                                            
							  COS(RADIANS(@dlatitude)) *                                            
							  COS(RADIANS(L.Longitude - @dLongitude))                
										  ) 
									  ))) * 69.09 * 1.609344),3) as Distance,CAST(CAST(L.Radius AS DECIMAL(8,4))/1000 as decimal(10,6)) as Radius                                              
						From rvlfLandMarK L WHERE --L.Latitude = @dlatitude and L.Longitude = @dlongitude AND 
						L.OrganizationId = @bigOrganizationID and L.LandmarkID in (Select RL.LandmarkID from @tblRouteLandmark RL)                
						group by L.LandMarkId,L.LandMarkName,L.Latitude,L.Longitude,L.Radius                
						) A WHERE A.Distance <= Radius                
						order by Distance asc   
						
						if(@landmarkID is not null)
							begin
								declare @ReturnCustomProp nvarchar(MAX)=null
								declare @routeID bigint=0
								select top 1 @routeID=RD.RouteId from @tblRouteLandmark RD where RD.LandmarkID=@landmarkID
								
								Exec rvlf_sp_GetNextStopID @intBoxID,@vcCustomProp,@landmarkID,@dtOriginDateTime,@routeID,@ReturnCustomProp output
								if(@ReturnCustomProp is not null)
									begin
										set @vcCustomProp=@ReturnCustomProp
									end
							end

						
					end

					


                IF @vcCustomProp not like '%ImgData:1%' -- CHARINDEX('ImgData:', @vcCustomProp) = 0      
                 begin      
                  PRINT 'Message Table'      
                  -- To insert the information in the message in history table      
                  INSERT INTO rvlfMsgInHSt      
                  (      
                  BoxID , OriginDateTime , DateTimeReceived ,      
                  ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,      
                  CommInfo2 , ValidGps , Latitude ,Longitude , Speed ,      
                  Heading , SensorMask , CustomProp , SequenceNum ,      
                  IsArmed , Priority , StreetAddress,IsNotificationSent,IsProcessed,IsArchived      
                  )      
                  OUTPUT INSERTED.MessageInID into @MsgInID      
                  VALUES      
                  (      
                  @intBoxID , @dtOriginDateTime , @dtDateTimeReceived ,      
                  @tiServiceID ,@tiBoxMsgInTypeId, @intBoxProtocolTypeId , @vcCommInfo1 ,      
                  @siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed ,      
                  @siHeading , @vcSensorMask , @vcCustomProp , @bigSequenceNum ,      
                  @bitIsArmed , @tiPriority ,      
                  CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,0,CASE WHEN @tiValidGps = 0 THEN 1 ELSE NULL END,0      
                  )      
                 End      
                IF @tiBoxMsgInTypeId = 114 and @vcCustomProp like '%ImgData:1%'      
                 BEGIN      
                  DECLARE @ImageID int      
                  DECLARE @CurrentPacket tinyint      
                  SELECT @ImageID = SUBSTRING(@vcCustomProp, CHARINDEX('Image ID:',@vcCustomProp,0)+9,      
                  (CHARINDEX(';',@vcCustomProp,CHARINDEX('Image ID:',@vcCustomProp,1))) -(CHARINDEX('Image ID:',@vcCustomProp,1)+9)),      
                  @CurrentPacket=SUBSTRING(@vcCustomProp, CHARINDEX('Current Packet:',@vcCustomProp,0)+15,      
                  (CHARINDEX(';',@vcCustomProp,CHARINDEX('Current Packet:',@vcCustomProp,1))) -(CHARINDEX('Current Packet:',@vcCustomProp,1)+15))      
                  IF NOT EXISTS (SELECT 1 FROM rvlfCameraImages WHERE BoxId=@intBoxID AND ImageID=@ImageID AND CurrentPacket=@CurrentPacket and CONVERT(date,ReceivedDate) = CONVERT(date,GETUTCDATE()))      
                   BEGIN      
                    INSERT INTO rvlfCameraImages      
                    (ReceivedDate,ImageID,BoxID,ImageData,ImageLength,CurrentPacket,TotalPackets)      
                    VALUES      
                    ( @dtOriginDateTime, @ImageID,@intBoxID,      
                    --SUBSTRING(@vcCustomProp, CHARINDEX('Image ID:', @vcCustomProp)+9,1),      
                    SUBSTRING(@vcCustomProp, CHARINDEX('Image Data:', @vcCustomProp)+11,LEN(@vcCustomProp)),      
                    SUBSTRING(@vcCustomProp, CHARINDEX('Image Length:',@vcCustomProp,0)+13,      
                    (CHARINDEX(';',@vcCustomProp,CHARINDEX('Image Length:',@vcCustomProp,1))) -(CHARINDEX('Image Length:',@vcCustomProp,1)+13)),      
                    @CurrentPacket,SUBSTRING(@vcCustomProp, CHARINDEX('Total Packets:',@vcCustomProp,0)+14,      
                    (CHARINDEX(';',@vcCustomProp,CHARINDEX('Total Packets:',@vcCustomProp,1))) -(CHARINDEX('Total Packets:',@vcCustomProp,1)+14))      
                    --SUBSTRING(@vcCustomProp, CHARINDEX('Current Packet:', @vcCustomProp)+15,1),      
                    --SUBSTRING(@vcCustomProp, CHARINDEX('Total Packets:', @vcCustomProp)+14,1)      
                    )      
                   END      
                 END      
                IF @tiBoxMsgInTypeId = 114 and (@vcCustomProp like '%SendSMSQuery:1%') and @SMSbasedQueryError = 0      
                 Begin      
                  Declare @VCCusProp varchar(max),@intBoxmsgintypeid int,@unMsginID varchar(max),@dtOrgDatetime datetime,@intSpeed bigint,      
                  @varStreetAddress varchar(max),@varBoxmsginTypeName varchar(max),      
                  @VarSensorStatus varchar(10), @VCCommandParam varchar(max), @VCCommand varchar(max),@intScheduleid int,      
                  @dtCmdCreateddate datetime,@dtcmdEnddate datetime      
                  set @VCSmsMsgUserRights = dbo.rvlf_fn_GetSMSCommandUserRights(@MobileNo,@intBoxID)      
                  select @intScheduleid = IDENT_CURRENT('rvlfScheduleOfCommandsMaster') + 1      
                  if @VCSmsMsgUserRights <> '' and @VCSmsMsgUserRights is not null      
                   Begin      
                    Set @VCSmsMsg = @VCSmsMsgUserRights      
                    set @intScheduleid = null      
                   end      
                  if @CommandId not in (254,255)      
                   Begin      
                    select @VehicleID =v.VehicleId,@VehicleDescription=v.VehicleDescription,@VehicleName=v.VehicleDescription,@LicensePlate=v.LicensePlate, @OrganizationID=v.OrganizationId,@FleetId=fv.FleetId,@FleetName=f.fleetname from rvlfVehicle v     

 
                    inner join rvlfvehicleassignment va with(nolock) on va.VehicleId=v.VehicleId      
                    inner join rvlfFleetVehicles fv on fv.VehicleId = v.VehicleId      
                    inner join rvlffleet f on f.fleetid = fv.fleetid      
                    where va.boxid = @intBoxID      
                   End      
                  SELECT @uiMsgInID1 = uiMsgInID FROM @MsgInID      
                  Set @dtCmdCreateddate =getutcdate()      
                  Set @dtcmdEnddate = dateadd(dd,1,getutcdate())      
                  Set @VCCommandParam = dbo.rvlf_fn_GetSMSCommandFrame(@intBoxID,@vcCustomProp)      
                  if @CommandId = 1      
                   Begin Set @VCCommand = '?' End      
                  else if @CommandId =2      
                   Begin Set @VCCommand = 'R' End      
                  else if @CommandId =3      
                   Begin Set @VCCommand = 'S' End      
                  --insert into rvlfSMSInHst(BoxId,Customprop,MessageInId,MobileNo,OriginDateTime,s) values(@intBoxID,@vcCustomProp,@unMsginID,@MobileNo,@dtOriginDateTime)      
                  if @CommandId not in (254,255) and @SMSbasedQueryError = 0      
                   Begin      
                    Exec [rvlf_sp_SaveAndUpdateAndDeleteSchedulingOfCommands] 0,0,@VCCommand,@VCCommandParam,@dtCmdCreateddate,@dtcmdEnddate,0,3,@Userid,@OrganizationID,@VehicleID,'any message in',@FleetId,@intBoxID      
                   end      
                  else if @VCSmsMsg like '%Invalid%' and @SMSbasedQueryError = 0      
                   Begin      
                    set @intScheduleid = null      
                   End      
                  --_SendSMSTest      
                  insert into rvlfNotificationLog(MessageInID,OriginDateTime,DateTimeReceived,CanSendSMS,IsSMSSent,Userid,OrganizationID,      
                  UserName,Email,MobileNo,StreetAddress,Speed,Boxid,BoxMsgInTypeName,VehicleID,VehicleDescription,      
                  VehicleName,Fleetid,Fleetname,LicensePlate,Subjectsufix,MessageDetails,CanSendEmail,SMSScheduleID)      
                  values      
                  (@uiMsgInID1,@dtOriginDateTime,@dtOriginDateTime,1,0,@Userid,@bigOrganizationID,@UserName,@Email,@MobileNo,      
                  null,0,@intBoxID,@tiBoxMsgInTypeId,@VehicleID,@VehicleDescription,@VehicleName,@FleetId,@FleetName,@LicensePlate,'Notify',      
                  @VCSmsMsg,0,@intScheduleid)      
                 End      
                SELECT @uiMsgInID = uiMsgInID,@Msgin=uiMsgInID FROM @MsgInID    
				 Declare @RouteAlertMsg varchar(3)=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'AlertMsg=',';'))      
							--Route ETA
					Declare @Route varchar(3)=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RouteID=',';'))                        

					if(@RouteAlertMsg='001')                          
						Begin                           
							--declare @msgid uniqueidentifier = (select MessageInID from rvlfMsgInHst where BoxId=@intBoxID and BoxMsgInTypeId=@tiBoxMsgInTypeId and MessageInID=@uiMsgInID order by OriginDateTime desc)
							update rvlfRouteETA set RouteStatus=2 where BoxID=@intBoxID and RouteStatus=0--2 incomplete route
							insert into rvlfRouteETA (BoxID,StartLocationDateTime,CustomProp,MessageInId,RouteStatus,StopStatus) values (@intBoxID,@dtOriginDateTime,@vcCustomProp,@uiMsgInID,0,@RouteAlertMsg)
						end
					if(@RouteAlertMsg='010' or @RouteAlertMsg='011')
						begin
							update rvlfRouteETA set CustomProp=@vcCustomProp,MessageInId=@uiMsgInID,StopStatus=@RouteAlertMsg where AutoNoETA in 
							(select top 1 AutoNoETA from rvlfRouteETA where BoxID=@intBoxID  and RouteStatus=0 and RouteID=@Route order by AutoNoETA desc)
						end
					if(@RouteAlertMsg='100')
						begin
							update rvlfRouteETA set CustomProp=@vcCustomProp,MessageInId=@uiMsgInID,RouteStatus=1,StopStatus=@RouteAlertMsg where AutoNoETA in 
							(select top 1 AutoNoETA from rvlfRouteETA where BoxID=@intBoxID  and RouteStatus=0 and RouteID=@Route order by AutoNoETA desc)
						end
                ----Data Movement for Global Scan Technologies---      
                --IF EXISTS(SELECT TOP 1 BoxId FROM rvlfBoxID WHERE BoxId=@intBoxID AND OrganizationId=242) AND      
                --@tiBoxMsgInTypeId IN (1,2,3,4,9,24,41,12,14,15,16,17)      
                --BEGIN TRY      
                -- INSERT INTO dbo.GlobalScan1(Unit_Id,Latitude,Latitude_Dir,Longitude,Longitude_Dir,UTC_Time,Speed,COG,Vt_date,      
                -- Vech_dist,Panic_Info,DubaiDateTime,currentdatetime,MessageId,IsProcessed)      
                -- VALUES(@intBoxID,CAST(@dLatitude AS FLOAT),(CASE WHEN SUBSTRING(CAST(@dLatitude AS VARCHAR),1,1)='-'THEN 'SOUTH' ELSE 'NORTH' END),      
                -- CAST(@dLongitude AS FLOAT),(CASE WHEN SUBSTRING(CAST(@dLongitude AS VARCHAR),1,1)='-'THEN 'WEST' ELSE 'EAST' END),GETUTCDATE(),@tiSpeed,      
                -- @siHeading,@dtOriginDateTime,      
                -- (CASE WHEN @vcCustomProp LIKE '%Odometer=%' THEN      
                -- CAST(SUBSTRING (@vcCustomProp,CHARINDEX('Odometer=',@vcCustomProp,1)+9,      
                -- CHARINDEX(';',@vcCustomProp,CHARINDEX('Odometer=',@vcCustomProp,1)) -      
                -- (CHARINDEX('Odometer=',@vcCustomProp,1)+9)) as bigint) ELSE 0 END),      
                -- dbo.[rvlf_fn_GetAlarmDetails_New](@vcCustomProp,@tiBoxMsgInTypeId,@intBoxID,NULL,NULL,NULL),DATEADD(HOUR,4,@dtOriginDateTime),      
                -- @dtDateTimeReceived,@uiMsgInID,1)      
                --END TRY      
                --BEGIN CATCH      
                -- PRINT 'END Global Scan'      
                --END CATCH      
                -----End--------------------------------------      
                ---------To update the duration from the custome prop to the Duration column------      
                UPDATE rvlfMsgInHst SET duration = (      
                CASE WHEN BoxMsgInTypeId = 3 AND customprop LIKE'%SENSOR_STATUS=OFF%' THEN SUBSTRING(SUBSTRING(customprop,CHARINDEX('SENSOR_DURATION=',customprop)+16,5),0,CHARINDEX(';',SUBSTRING(customprop,CHARINDEX('SENSOR_DURATION=',customprop)+16,5))) 

  
    
     
                WHEN BoxMsgInTypeId = 9 THEN SUBSTRING(customprop,8,CHARINDEX(';',customprop)-8)      
                ELSE NULL END), odometer = 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      
                WHERE MessageInID = @uiMsgInID      
                --PRINT 'Welcome 2'      
                --------------------------------------------------------------------------------------      
                /****************demo *****************/      
                -- Demo Entry Insertion      
                /*IF(@intDemoBoxID IS NOT NULL)      
                BEGIN      
                INSERT INTO rvlfMsgInHSt      
                (      
                BoxID , OriginDateTime , DateTimeReceived ,      
                ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,      
                CommInfo2 , ValidGps , Latitude ,Longitude , Speed ,      
                Heading , SensorMask , CustomProp , SequenceNum ,      
                IsArmed , Priority , StreetAddress, NearestLandmark , IsNotificationSent      
                )      
                OUTPUT INSERTED.MessageInID into @demoMsgInID      
                VALUES      
                (      
                @intDemoBoxID , @dtOriginDateTime , @dtDateTimeReceived ,      
                @tiServiceID ,@tiBoxMsgInTypeId, @intBoxProtocolTypeId , @vcCommInfo1 ,      
                @siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed ,      
                @siHeading , @vcSensorMask , @vcCustomProp , @bigSequenceNum ,      
                @bitIsArmed , @tiPriority ,      
                CASE WHEN @tiValidGps = 0 THEN      
                CASE WHEN @IsAddressAlreadyAvailable = 1 AND @vcStreetAddress!='N/A' THEN @vcStreetAddress ELSE NULL END      
                ELSE 'N/A' END,      
                CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,0      
                --CASE WHEN @tiValidGps > 0 THEN 0 ELSE 0 END      
                )      
                SELECT @uiDemoMsgInID = uidemoMsgInID FROM @demoMsgInID      
                END*/      
                /*************end ***************************/      
                PRINT 'BoxId Table'      
                /******************************************************************************/      
                /****************************Box ID Table**************************************/      
                -- Inserts into the rvlfBoxID if sensor mask is available in the information.      
                IF @vcSensorMask IS NOT NULL AND LEN(@vcSensorMask) = 8 AND @tiBoxMsgInTypeId NOT IN (51,121,188) AND @tiValidGps <>2      
                 BEGIN      
                  IF @tiValidGps <> 0      
                   BEGIN      
                    SELECT @dtLastValidGPSTime = ISNULL(max(OriginDateTime), @dtOriginDateTime)      
                    FROM rvlfMsgInHst WHERE BoxId = @intBoxID and ValidGps = 0 --and SensorMask IS NOT NULL      
                   END      
                  DECLARE @dtLastValidDateTime DateTime=(SELECT LastValidDateTime FROM rvlfBoxId with(nolock) WHERE BoxId = @intBoxID)      
                  -- Checks if the last information exists for the box, if so updates else inserts      
                  IF @dtOriginDateTime >= @dtLastValidDateTime      
                   BEGIN      
                    UPDATE rvlfBoxId SET BoxArmed = @bitIsArmed,LastValidDateTime = CASE WHEN @tiValidGps = 0 THEN @dtOriginDateTime ELSE LastValidDateTime END,      
                    LastLatitude = CASE WHEN @tiValidGps = 0 THEN @dLatitude ELSE LastLatitude END,      
                    LastLongitude = CASE WHEN @tiValidGps = 0 THEN @dLongitude ELSE LastLongitude END,LastSpeed = @tiSpeed,      
                    LastCommunicatedDateTime = @dtDateTimeReceived,LastSensorMask = @vcSensorMask,OrganizationId = @bigOrganizationID,      
                    LastStatusDateTime = @dtOriginDateTime,LastStreetAddress = CASE WHEN @tiValidGps = 0 THEN NULL ELSE LastStreetAddress END,      
                    NearestLandmark = CASE WHEN @tiValidGps = 0 THEN NULL ELSE NearestLandmark END,Heading = @siHeading,MessageInId = @uiMsgInID      
                    WHERE BoxId = @intBoxID      
                   END      
                  ELSE IF(@dtLastValidDateTime IS NULL OR @dtLastValidDateTime='')      
                   BEGIN      
                 DELETE FROM rvlfBoxId WHERE BoxId=@intBoxID      
                    INSERT INTO rvlfBoxId      
                    (      
                    BoxId, BoxArmed, LastValidDateTime, LastLatitude, LastLongitude,      
                    LastSpeed, LastCommunicatedDateTime, LastSensorMask,      
                    OrganizationId, LastStatusDateTime, Heading , LastStreetAddress ,      
                    NearestLandmark, MessageInId      
                    )      
                    VALUES      
                    (      
                    @intBoxID, @bitIsArmed, @dtLastValidGPSTime, @dLatitude, @dLongitude,      
                    @tiSpeed, @dtDateTimeReceived, @vcSensorMask,      
                    @bigOrganizationID, @dtOriginDateTime, @siHeading,      
                    CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,      
                    CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,      
                    @uiMsgInID      
                    )      
                    /*********** demo **************/      
                    --Demo Acoount Mapping      
                    /*IF(@intDemoBoxID IS NOT NULL)      
                    BEGIN      
                    INSERT INTO rvlfBoxId      
                    (      
                    BoxId, BoxArmed, LastValidDateTime, LastLatitude, LastLongitude,      
                    LastSpeed, LastCommunicatedDateTime, LastSensorMask,      
                    OrganizationId, LastStatusDateTime, Heading , LastStreetAddress ,      
                    NearestLandmark, MessageInId      
                    )      
                    VALUES      
                    (      
                    @intDemoBoxID, @bitIsArmed, @dtLastValidGPSTime, @dLatitude, @dLongitude,      
                    @tiSpeed, @dtDateTimeReceived, @vcSensorMask,      
                    55, @dtOriginDateTime, @siHeading,      
                    CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,      
                    CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,      
                    @uiDemoMsgInID )      
                    END */      
                    /*********end ************/      
                   END      
                 END      
                PRINT 'Alarm Table'      
                if (@tiBoxMsgInTypeId =187) --demo changes for accenture tilt sensor      
                 begin      
                  if(dbo.rvlf_fn_getparamvaluewithindex(@vcCustomProp,'Alertid=',';') in (1,2,3,5))      
                  set @bitIsAlarm = 1      
                  set @tiAlarmLevelID = 3      
                 end      
                /******************************************************************************/      
                /*************************Alarm Processing*************************************/      
                -- Inserts to Alarm table, if it is an alarm.      
                IF @bitIsAlarm = 1 Or @bitCreateAlarm = 1      
                 BEGIN      
                  DECLARE @siAlarmLevelID smallint,@bigDriverID bigint = NULL      
                  DECLARE @bigAlarmID bigint      
                  SELECT @bigDriverID = DriverId FROM RVLFIButtonMapping WHERE BoxID = @intBoxID      
                  IF(@bigDriverID IS NULL OR @bigDriverID='')      
                   BEGIN      
                    SELECT @bigDriverID = DriverId FROM rvlfDriverAssignment WHERE BoxID = @intBoxID      
                    AND @dtOriginDateTime BETWEEN FromTime AND ToTime      
                    AND CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime)      
                    if(@bigDriverID IS NULL OR @bigDriverID='') --Included for rfid based driver 21-apr-2016 gopal for cotton blossom      
                     begin      
                      select top 1 @bigDriverID=DriverId FROM rvlfDriverAssignment WHERE BoxID = @intBoxID order by assignmentid desc      
                     end      
                   END      
                  --PRINT 'Welcome 3'      
                  IF(@tiAlarmLevelID is null OR @tiAlarmLevelID='')      
                   BEGIN      
                    SET @tiAlarmLevelID = 4 -- hardcoded to avoid AlarmLeveleID issue      
                   END      
                  PRINT 'Alarm 1 Table'      
                  INSERT INTO rvlfAlarm(AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,DriverId,CustomProp)      
                  VALUES(@tiAlarmLevelID,@dtOriginDateTime,@intBoxID,@tiBoxMsgInTypeId,@dLatitude,@dLongitude,      
                  CASE WHEN @tiBoxMsgInTypeId IN (5 , 6) THEN CAST(@bigGeoZoneID AS varchar(600))      
                  WHEN @tiBoxMsgInTypeId = 4 THEN CAST (@tiSpeed As Varchar(600))      
                  ELSE dbo.rvlf_fn_GetAlarmDetails_Optimzd(@vcCustomProp , @tiBoxMsgInTypeId, @intBoxID,@uiMsgInID, @dtOriginDateTime,'LanguageEn') END,      
                  CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END, @bigDriverID,@vcCustomProp)      
                  PRINT 'Alarm 1 END'      
                  --Student sms Trigger for alarm for unassigned geozone/vehicle 12-feb-2015 commented for LKD org temporarily      
                  IF(@tiBoxMsgInTypeId=100 and charindex('Punch:101',@vcCustomProp,1)>0 or charindex('Punch:110',@vcCustomProp,1)>0)      
                   Begin      
                    print 'Student alarm'      
                    Declare @punch varchar(30)= dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'Punch:',';')      
                    Insert into rvlfRFIDSchoolSMSNotification(StudentID,VehicleID,BoxID,GeozoneID,OrganizationId ,EntryExitTime ,RFID ,StudentName,ContactNo , MessageTemplate,MsgType, IsSMSSent)      
                    select S.StudentMasterID,va.VehicleID,@intBoxID,S.GeozoneId,S.OrganizationID,@dtOriginDateTime,S.RFID,S.StudentFirstName + +      
                    S.StudentLastName,S.ContactNo ,      
          CASE WHEN @punch ='101' THEN ('Name : '+ S.StudentFirstName + + S.StudentLastName + '\n Info: Boarded / Get down incorrect Location at : '+ CAST((dbo.rvlf_fn_DayLightSavings_Date(@dtOriginDateTime,O.OrganizationID,TZ.HoursToBeAdded, TZ    
.MinToBeAdded,@dtOriginDateTime)) as varchar(20))) +'-Trinetra'      
                    WHEN @punch ='110' THEN ('Name : '+ S.StudentFirstName + + S.StudentLastName + '\n Info: Boarded / Get down from incorrect vehicle at : '+      
                    CAST((dbo.rvlf_fn_DayLightSavings_Date(@dtOriginDateTime,O.OrganizationID,TZ.HoursToBeAdded,TZ.MinToBeAdded,@dtOriginDateTime))      
                    as varchar(20)))+'-Trinetra' end as MessageType,4,0      
                    from rvlfStudentMaster S  with(nolock)    
                    inner join rvlfVehicle v on s.OrganizationId=v.OrganizationId      
                    inner join rvlfVehicleAssignment va with(nolock) on v.VehicleId=va.VehicleId      
                    inner join rvlfOrganization O on O.OrganizationId = S.OrganizationID      
                    inner join rvlfTimeZones TZ on TZ.TimeZoneID = O.CountryId      
                    where s.RFID= dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RF_ID=',';') and va.BoxId=@intBoxID      
                   End      
                  ---------------- ---------------- ----------------      
                  /*********** demo ********************/      
                  -- Demo Account Mapping      
                  /*IF(@intDemoBoxID IS NOT NULL)      
                  BEGIN      
                  SELECT @bigAlarmID = ISNULL(Max(AlarmID),0)+1 FROM rvlfAlarm      
                  INSERT INTO rvlfAlarm      
                  ( AlarmId,AlarmLevelId, DateTimeCreated , BoxId , AlarmType ,Lat , Long , [Description],StreetAddress )      
                  VALUES ( @bigAlarmID , @tiAlarmLevelID, @dtOriginDateTime , @intDemoBoxID , @tiBoxMsgInTypeId, @dLatitude , @dLongitude ,      
                  CASE WHEN @tiBoxMsgInTypeId IN (5 , 6) THEN CAST(@bigGeoZoneID AS varchar(600))      
                  WHEN @tiBoxMsgInTypeId = 4 THEN CAST (@tiSpeed As Varchar(600))      
                  ELSE dbo.rvlf_fn_GetAlarmDetails(@vcCustomProp , @tiBoxMsgInTypeId, @intDemoBoxID,@uiDemoMsgInID, @dtOriginDateTime) END,      
                  CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END      
)      
                  END */      
                  /*************end **********************/      
                 END      
                /******************************************************************************/      
                /***************************Communication Processing***************************/      
                -- Inserts the communication information based on the communication information.      
                IF NOT EXISTS(SELECT commAddressValue FROM rvlfBoxCommInfo WHERE BoxId = @intBoxID AND CommAddressValue =@vcNewIP)      
                 BEGIN      
                  DELETE FROM rvlfBoxCommInfo WHERE BoxId = @intBoxID      
                  INSERT INTO rvlfBoxCommInfo(BoxID,CommAddressTypeId,CommAddressValue)      
                  SELECT @intBoxID,CommAddressTypeID,@vcNewIP FROM rvlfCommModeAddressType      
                  WHERE CommModeId = @tiCommModeId      
                 END      
                /******************************************************************************/      
                PRINT 'Trip Table'      
                /**************************Trip Processing*************************************/      
                DECLARE @tripTobeProcessed bigint      
                DECLARE @bigTripID bigint      
                DECLARE @bigPreviousTripID bigint      
                -- Checks the Geozone status and update starts or ends the trip against boxid.      
                IF EXISTS (SELECT 1 FROM dbo.rvlfBoxId WHERE BoxID=@intBoxID AND OrganizationID=201) --Afcons Clients      
                 BEGIN      
                  select '201'      
                  -- SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetails_AFC WHERE BoxID = @intBoxID AND IsTripClosed = 0      
                  -- IF(@bigOdoMeterReading IS NULL AND @tiBoxMsgInTypeId=114 AND CHARINDEX(';Odometer:',@vcCustomProp,0) <> 0)      
                  -- BEGIN      
                  --SELECT @bigOdoMeterReading=SUBSTRING(@vcCustomProp,CHARINDEX(';Odometer:',@vcCustomProp,0)+10,      
                  --(LEN(@vcCustomProp)-(CHARINDEX(';Odometer:',@vcCustomProp,0)+9)))      
                  -- END      
                  -- ELSE IF (@bigOdoMeterReading IS NULL AND @tiBoxMsgInTypeId=6)      
                  -- BEGIN      
                  -- SELECT @bigOdoMeterReading=SUBSTRING(@vcCustomProp,CHARINDEX(';Odometer=',@vcCustomProp,0)+10,      
                  --((CHARINDEX(';Battery',@vcCustomProp,0))-(CHARINDEX(';Odometer=',@vcCustomProp,0)+10)))      
                  -- END      
                  -- UPDATE dbo.rvlfTripDetails_AFC SET EndDate=@dtOriginDateTime , OdometerEnd = CASE WHEN @bigOdoMeterReading IS NULL      
                  -- THEN OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID ,      
                  -- IsTripClosed = CASE WHEN @tiBoxMsgInTypeId = 5 THEN 1 ELSE 0 END,      
                  --IdlingDuration = IdlingDuration + (CASE WHEN @tiBoxMsgInTypeId <> 9 THEN 0 ELSE      
                  -- CAST(dbo.rvlf_fn_GetDuration(@vcCustomProp, @tiBoxMsgInTypeID, @intBoxID,0) as int) END)      
                  -- WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID AND IsTripClosed = 0      
                  -- IF @tiBoxMsgInTypeId IN (5,6,114)      
                  -- BEGIN      
                  -- IF (@tiBoxMsgInTypeId = 6 OR (@tiBoxMsgInTypeId = 114 AND CHARINDEX('GeozoneInOutWithDuration:',@vcCustomProp,0) <> 0))      
                  -- AND @tripTobeProcessed = 0      
                  -- BEGIN      
                  -- SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM dbo.rvlfTripDetails_AFC WHERE BoxId = @intBoxID      
 -- SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM dbo.rvlfTripDetails_AFC      
                  -- INSERT INTO dbo.rvlfTripDetails_AFC(TripId, BoxId, StartDate, EndDate, OdometerStart, OdometerEnd,      
        -- StartMessageInID , EndMessageInID, IsTripClosed) VALUES      
                  -- (@bigTripID,@intBoxID, @dtOriginDateTime, @dtOriginDateTime, @bigOdoMeterReading ,      
                  -- @bigOdoMeterReading , @uiMsgInID , @uiMsgInID, 0)      
                  -- INSERT INTO dbo.rvlfTripFareDetails(TripId) VALUES(@bigTripID) --Trip Fare Details      
                  -- UPDATE dbo.rvlfTripDetails_AFC SET StopTime = DATEDIFF(ss, EndDate, @dtOriginDateTime)      
                  -- WHERE BoxId = @intBoxID AND TripID = @bigPreviousTripID      
                  -- END      
                  -- ELSE IF @tiBoxMsgInTypeId = 5 AND @tripTobeProcessed = 0      
                  -- BEGIN      
                  -- SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetails_AFC WHERE BoxID = @intBoxID AND IsTripClosed = 1      
                  -- UPDATE dbo.rvlfTripDetails_AFC SET EndDate=@dtOriginDateTime , OdometerEnd = CASE WHEN @bigOdoMeterReading IS NULL      
                  -- THEN OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID ,IsTripClosed = 1      
                  -- WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID      
                  -- END      
                  --END      
                 END      
                ELSE      
                 BEGIN --Other Clients      
                  -- Checks the ignition status and starts or ends the trip.      
                  SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetails WHERE BoxID = @intBoxID      
                  AND IsTripClosed = 0      
                  UPDATE dbo.rvlfTripDetails SET EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL THEN OdometerEnd ELSE @bigOdoMeterReading END,EndMessageInID = @uiMsgInID , IsTripClosed = CASE WHEN @bitIgnitionStatus = 0 THEN 1 ELSE      
      0 END,      
                  IdlingDuration = IdlingDuration + (CASE WHEN @tiBoxMsgInTypeId <> 9 THEN 0 ELSE      
                  CAST(dbo.rvlf_fn_GetDuration(@vcCustomProp, @tiBoxMsgInTypeID, @intBoxID,0) as int) END)      
                  WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID AND IsTripClosed = 0      
                  IF @tiBoxMsgInTypeId <> 13      
                   BEGIN      
                    IF @bitIgnitionStatus = 1 AND @tripTobeProcessed = 0 and (@tiBoxMsgInTypeId = 2 AND CHARINDEX('SENSOR_NUM=3;',@vcCustomProp,0) <> 0)      
                     BEGIN      
                      SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM dbo.rvlfTripDetails WHERE BoxId = @intBoxID      
                      SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM dbo.rvlfTripDetails  with(nolock)     
                      INSERT INTO dbo.rvlfTripDetails      
                      (TripId, BoxId, StartDate, EndDate, OdometerStart, OdometerEnd,StartMessageInID , EndMessageInID, IsTripClosed)      
                      VALUES (@bigTripID, @intBoxID, @dtOriginDateTime, @dtOriginDateTime, @bigOdoMeterReading ,      
                      @bigOdoMeterReading , @uiMsgInID , @uiMsgInID, 0)      
                      UPDATE dbo.rvlfTripDetails SET StopTime = DATEDIFF(ss, EndDate, @dtOriginDateTime)      
                      WHERE BoxId = @intBoxID AND TripID = @bigPreviousTripID      
                     END      
                    ELSE IF @bitIgnitionStatus = 0 AND @tripTobeProcessed = 0 AND (@tiBoxMsgInTypeId = 3 AND      
                    CHARINDEX('SENSOR_NUM=3;',@vcCustomProp,0) <> 0)      
                     BEGIN      
                      SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetails  with(nolock)    
                      WHERE BoxID = @intBoxID AND IsTripClosed = 1      
                      UPDATE dbo.rvlfTripDetails SET EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL THEN OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID , IsTripClosed = 1      
                      WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID      
                     END      
                   END --      
                  Declare @Sensor int --Get sensor      
                  -- if CHARINDEX('SENSOR_NUM=',@vcCustomProp,0) <> 0      
                  --begin      
                  -- set @sensor=dbo.rvlf_fn_getparamvaluewithindex(@vcCustomProp,'SENSOR_NUM=',';')      
                  --end      
                  -- -- Checks the ignition status and starts or ends the trip.      
                  -- SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetailssensorbsd WHERE BoxID = @intBoxID      
                  --AND IsTripClosed = 0      
                  --AND (CHARINDEX('SENSOR_NUM=',@vcCustomProp,0) = 0 or SensorNo=@Sensor) --#      
                  -- UPDATE dbo.rvlfTripDetailssensorbsd SET EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL THEN OdometerEnd ELSE      
                  -- @bigOdoMeterReading END,EndMessageInID = @uiMsgInID , --IsTripClosed = CASE WHEN @bitIgnitionStatus = 0 THEN 1 ELSE 0 END, #      
                  -- IdlingDuration = IdlingDuration + (CASE WHEN @tiBoxMsgInTypeId <> 9 THEN 0 ELSE      
                  -- CAST(dbo.rvlf_fn_GetDuration(@vcCustomProp, @tiBoxMsgInTypeID, @intBoxID,0) as int) END)      
                  -- WHERE BoxId = @intBoxID AND IsTripClosed = 0 -- AND TripID = @tripTobeProcessed #      
                  -- IF @tiBoxMsgInTypeId <> 13      
                  -- BEGIN --@bitIgnitionStatus = 1 AND      
                  -- IF @tripTobeProcessed = 0 and (@tiBoxMsgInTypeId = 2 AND CHARINDEX('SENSOR_NUM=',@vcCustomProp,0) <> 0)      
                  -- BEGIN      
                  -- SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM dbo.rvlfTripDetailssensorbsd WHERE BoxId = @intBoxID and SensorNo=@sensor --#      
                  -- SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM dbo.rvlfTripDetailssensorbsd      
               --INSERT INTO dbo.rvlfTripDetailssensorbsd      
                  -- (TripId, BoxId, StartDate, EndDate, OdometerStart, OdometerEnd,StartMessageInID , EndMessageInID, IsTripClosed,SensorNo) --#      
                  -- VALUES (@bigTripID, @intBoxID, @dtOriginDateTime, @dtOriginDateTime, @bigOdoMeterReading , @bigOdoMeterReading , @uiMsgInID , @uiMsgInID, 0,@Sensor)      
                  -- UPDATE dbo.rvlfTripDetailssensorbsd SET StopTime = DATEDIFF(ss, EndDate, @dtOriginDateTime)      
                  --WHERE BoxId = @intBoxID AND TripID = @bigPreviousTripID      
                  -- END      
                  -- ELSE IF (@tiBoxMsgInTypeId = 3 AND CHARINDEX('SENSOR_NUM=',@vcCustomProp,0) <> 0) -- #@bitIgnitionStatus = 0 AND AND @tripTobeProcessed = 0      
                  -- BEGIN      
                  -- SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetailssensorbsd      
                  -- WHERE BoxID = @intBoxID and SensorNo=@sensor--AND IsTripClosed = 1 #      
                  -- UPDATE dbo.rvlfTripDetailssensorbsd SET EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL      
                  -- THEN OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID , IsTripClosed = 1      
                  -- WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID and SensorNo=@sensor --#      
                  -- END      
                  -- END      
                 END      
                /******************************************************************************/      
                PRINT 'Schedule Table'      
                /*************************Message out Processing (ACK / Response)**************/      
                IF @dtSentDateTime IS NOT NULL      
                 BEGIN      
    UPDATE rvlfMsgOutHst SET Acknowledged = 1, MessageInID= @uiMsgInID      
                  WHERE BoxId = @intBoxID AND SentDateTime = @dtSentDateTime      
                  --Update reporting interval and speed threshold to master table      
                  --UPDATE v SET v.RptInterval=--(CASE WHEN H.BoxCmdOutTypeId=1 THEN dbo.rvlf_fn_GetTimeFromSeconds(H.CustomProp) ELSE v.RptInterval END),      
                  --(CASE WHEN H.BoxCmdOutTypeId=1 and CHARINDEX(',1',H.CustomProp,1)=0 THEN dbo.rvlf_fn_GetTimeFromSeconds(H.CustomProp)      
                  --WHEN H.BoxCmdOutTypeId=1 and CHARINDEX(',1',H.CustomProp,1)>0 THEN REPLACE(H.CustomProp,',1','') ELSE v.RptInterval END),      
                  --v.SpdThreshold = (CASE WHEN H.BoxCmdOutTypeId=2 THEN CAST(H.CustomProp AS TINYINT) ELSE v.SpdThreshold END) FROM rvlfVehicle v      
                  --INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId      
                  --INNER JOIN rvlfMsgOutHst H ON H.BoxId=va.BoxId      
                  --WHERE H.BoxId = @intBoxID AND H.SentDateTime = CAST(@dtSentDateTime AS DATETIME) AND H.BoxCmdOutTypeId IN (1,2)    
       if LEN(@intBoxID) > 10   
      Begin  

	 -- declare @tmpcusprop varchar(max) = @vcCustomProp
	 -- if SUBSTRING(@tmpcusprop, len(@tmpcusprop) , 1) <> ';'
	 -- Begin
		--set @tmpcusprop = @tmpcusprop + ';'
	 -- End
	  --select SUBSTRING(@tmpcusprop, CHARINDEX(':', @tmpcusprop) + 1, (CHARINDEX(';', @tmpcusprop)) - (CHARINDEX(':', @tmpcusprop) + 1)) 
	  
     UPDATE v SET v.RptInterval=  
     SUBSTRING(H.CustomProp, CHARINDEX(':', H.CustomProp) + 1, len(H.CustomProp) - CHARINDEX(':', H.CustomProp) + 1)   
     FROM rvlfVehicle v      
     INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId      
     INNER JOIN rvlfMsgOutHst H ON H.BoxId=va.BoxId      
     WHERE H.BoxId = @intBoxID AND H.SentDateTime = CAST(@dtSentDateTime AS DATETIME) AND H.BoxCmdOutTypeId IN (1,2)     
	 --UPDATE v SET v.RptInterval=  
  --   SUBSTRING(@tmpcusprop, CHARINDEX(':', @tmpcusprop) + 1, (CHARINDEX(';', @tmpcusprop)) - (CHARINDEX(':', @tmpcusprop) + 1)) 
  --   FROM rvlfVehicle v      
  --   INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId      
  --   INNER JOIN rvlfMsgOutHst H ON H.BoxId=va.BoxId      
  --   WHERE H.BoxId = @intBoxID AND H.SentDateTime = CAST(@dtSentDateTime AS DATETIME) AND H.BoxCmdOutTypeId IN (1,2)         
      End  
      Else  
      Begin  
     UPDATE v SET v.RptInterval=--(CASE WHEN H.BoxCmdOutTypeId=1 THEN dbo.rvlf_fn_GetTimeFromSeconds(H.CustomProp) ELSE v.RptInterval END),      
     (CASE WHEN H.BoxCmdOutTypeId=1 and CHARINDEX(',1',H.CustomProp,1)=0 THEN dbo.rvlf_fn_GetTimeFromSeconds(H.CustomProp)      
     WHEN H.BoxCmdOutTypeId=1 and CHARINDEX(',1',H.CustomProp,1)>0 THEN REPLACE(H.CustomProp,',1','') ELSE v.RptInterval END),      
     v.SpdThreshold = (CASE WHEN H.BoxCmdOutTypeId=2 THEN CAST(H.CustomProp AS TINYINT) ELSE v.SpdThreshold END) FROM rvlfVehicle v      
     INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId      
     INNER JOIN rvlfMsgOutHst H ON H.BoxId=va.BoxId      
     WHERE H.BoxId = @intBoxID AND H.SentDateTime = CAST(@dtSentDateTime AS DATETIME) AND H.BoxCmdOutTypeId IN (1,2)            
      End  
          
                  /*********** demo *****************/      
                  -- Demo Account Mapping      
                  /*IF(@intDemoBoxID IS NOT NULL)      
                  BEGIN      
                  UPDATE rvlfMsgOutHst SET Acknowledged = 1, MessageInID= @uiDemoMsgInID WHERE      
                  BoxId = @intDemoBoxID AND SentDateTime = @dtSentDateTime      
                  END */      
                  /*********end **************/      
                  DECLARE @tiCmdTypeID tinyint=(SELECT BoxCmdOutTypeId FROM rvlfMsgOutHst WHERE BoxId = @intBoxID AND SentDateTime = @dtSentDateTime)      
                  IF(@tiCmdTypeID IN(11,12))      
                  BEGIN      
     DECLARE @bigUserID bigint,@bigVehicleID bigint,@bigGeozoneNo bigint,@bigPassOrganizationID bigint      
                  SELECT @bigVehicleID = VehicleId FROM rvlfVehicleAssignment      
                  WHERE BoxId=@intBoxID AND IsDeleted <> 1      
                  DECLARE @tiSeverity bigint      
                  IF @tiCmdTypeID = 11      
                   BEGIN      
                    --SELECT @bigUserID= MO.UserId, @bigGeozoneNo=CAST(MO.CustomProp AS bigint),@bigPassOrganizationID=OG.OrganizationId      
                    --FROM rvlfMsgOutHst MO INNER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId=CAST(MO.CustomProp AS bigint)      
                    --WHERE MO.BoxId = @intBoxID AND MO.SentDateTime = @dtSentDateTime AND OG.OrganizationId=@bigOrganizationID    
     if LEN(@intBoxID) > 10   
       Begin        
      declare @tmpsetparam varchar(max), @tmpsel varchar(10), @tmptelgeo int    
      set @tmpsetparam = (select Top 1 CustomProp from rvlfMsgOutHst WHERE BoxId = @intBoxID AND SentDateTime = CAST(@dtSentDateTime AS DATETIME) order by SentDateTime desc)        
      set @tmpsel = SUBSTRING(@tmpsetparam, 10, 5)  

        set @tmptelgeo = ISNULL((select GeozoneNo from rvlftkGeozoneParamID where ParamID = @tmpsel), 0)

 --     set @tmptelgeo = (select case @tmpsel   
 --     when 20100 then 1 when 20120 then 2 when 20140 then 3 when 20160 then 4 when 20180 then 5 when 20200 then 6 when 20220 then 7 when 20240 then 8 when 20260 then 9 when 20280 then 10 when 20300 then 11 when 20320 then 12 when 20340 then 13 when 20360
 --then 14 when 20380 then 15 when 20400 then 16 when 20420 then 17 when 20440 then 18 when 20460 then 19 when 20480 then 20 when 20500 then 21 when 20520 then 22 when 20540 then 23 when 20560 then 24 when 20580 then 25 when 20600 then 26 when 20620 then 27
 --when 20640 then 28 when 20660 then 29 when 20680 then 30 when 20700 then 31 when 20720 then 32 when 20740 then 33 when 20760 then 34 when 20780 then 35 when 20800 then 36 when 20820 then 37 when 20840 then 38 when 20860 then 39 when 20880 then 40 when 20900 then 41 when 20920 then 42 when 20940 then 43 when 20960 then 44 when 20980 then 45 when 21000 then 46 when 21020 then 47 when 21040 then 48 when 21060 then 49 when 21080 then 50 else 0 end )  
        
      SELECT @bigUserID= MO.UserId   
      FROM rvlfMsgOutHst MO WHERE MO.BoxId = @intBoxID AND MO.SentDateTime = @dtSentDateTime   
      SELECT  @bigGeozoneNo= b.GeozoneID, @bigPassOrganizationID= a.OrganizationId FROM rvlfOrganizationGeozone a inner join rvlfOrganizationGeozonetkRel b on a.GeozoneNo = b.GeozoneNo and a.OrganizationId = b.OrganizationID where b.BoxID = @intboxid and 

b.TKGeozoneID = @tmptelgeo         
       End  
       else  
       Begin  
     SELECT @bigUserID= MO.UserId, @bigGeozoneNo=CAST(MO.CustomProp AS bigint),@bigPassOrganizationID=OG.OrganizationId      
                    FROM rvlfMsgOutHst MO INNER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId=CAST(MO.CustomProp AS bigint)      
                    WHERE MO.BoxId = @intBoxID AND MO.SentDateTime = @dtSentDateTime AND OG.OrganizationId=@bigOrganizationID      
       End    
                    SELECT @tiSeverity = SeverityId FROM rvlfOrganizationGeozone WHERE GeozoneId = @bigGeozoneNo and OrganizationId = @bigPassOrganizationID      
                    IF(@tiSeverity IS NOT NULL)      
                     BEGIN IF NOT EXISTS(SELECT GeozoneNo FROM rvlfVehicleGeozone WHERE VehicleId = @bigVehicleID AND GeozoneNo = @bigGeozoneNo)      
                     BEGIN      
                      DECLARE @IsUnAuthorizedGeo AS BIT = 0      
                      SELECT @IsUnAuthorizedGeo = DN.IsUnAuthorisedGeoZone      
                      FROM rvlfdelaynotify DN      
                      INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId = DN.BoxId      
                      INNER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId = DN.GeozoneId      
                  WHERE VA.VehicleId = @bigVehicleID AND OG.GeozoneId = @bigGeozoneNo      
                      INSERT INTO rvlfVehicleGeozone(VehicleId,SeverityId,GeozoneNo,AssingedBy,AssingedDate,IsUnAuthorizedGeozone)      
                      VALUES(@bigVehicleID, @tiSeverity, @bigGeozoneNo, @bigUserID, @dtSentDateTime,@IsUnAuthorizedGeo)      
                     END      
                    END      
                   END      
                  IF @tiCmdTypeID = 12      
                   BEGIN      
                    DECLARE @vcGeozoneIDs varchar(150)=(SELECT CustomProp FROM rvlfMsgOutHst WHERE BoxId = @intBoxID AND SentDateTime = @dtSentDateTime)      
                    IF @vcGeozoneIDs ='65535'      
                     BEGIN      
                      DELETE FROM rvlfVehicleGeozone WHERE VehicleId= @bigVehicleID      
                     END      
                    ELSE      
                     BEGIN      
                      DELETE rvlfVehicleGeozone WHERE VehicleId= @bigVehicleID      
                      AND GeozoneNo IN (SELECT GeozoneId FROM rvlfOrganizationGeozone      
                      WHERE OrganizationId = @bigOrganizationID AND GeozoneId IN      
                      (SELECT * from dbo.rvlf_fn_ConvertArrayToTable(@vcGeozoneIDs,',')))      
                     END      
                   END      
                  END      
                 END      
                IF (@intBoxID = 2)      
                 BEGIN      
                  exec rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId       
                 END      
                -- Disable SMS for Dhana college when Fuel Drain with Ignition ON      
                IF (@bigOrganizationID = 47 and @tiBoxMsgInTypeId = 90 and @bitIgnitionStatus = 1)      
                 BEGIN      
                  UPDATE rvlfMsgInHst set IsNotificationSent = 1 where MessageInID = @uiMsgInID      
                 END      
                --Log notifications for geozone messages.      
                --IF(@tiBoxMsgInTypeId IN(5,6))      
                --BEGIN      
                --EXEC rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId      
                --END      
                PRINT 'Log Notification Table'      
                --UPDATE THE LOG NOTIFICATION FOR INVALID GPS      
                -- ELSE IF @tiValidGps >= 0 AND @tiBoxMsgInTypeId=100      
                -- BEGIN      
                --EXEC rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId      
                -- END      
                IF @tiValidGps > 0 AND @tiBoxMsgInTypeId NOT IN (100,21) and @vcCustomProp not like '%IButtonCommand:1%' and @vcCustomProp not like '%CameraSettings:1%' and @vcCustomProp not like '%Img%' and @vcCustomProp not like '%SendSMSQuery:1%'
  
    
      
                 BEGIN      
                  EXEC rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId      
                 END      
                --PRINT 'Welcome 4'      
                IF @trancount = 0      
        COMMIT;      
                -- COMMIT TRAN      
               END TRY      
              BEGIN CATCH      
              DECLARE @error int, @message varchar(4000), @xstate int;      
              SELECT @error = ERROR_NUMBER(),      
              @message = ERROR_MESSAGE(),      
              @xstate = XACT_STATE();      
              if @xstate = -1      
              ROLLBACK TRAN;      
              if @xstate = 1 and @trancount = 0      
              ROLLBACK TRAN;      
              if @xstate = 1 and @trancount > 0      
              ROLLBACK TRANSACTION MessageTransaction;      
              --ROLLBACK TRAN      
              SET @ErrorMessage = 'An Error occured during insert of the packet message : ' + @message      
              RAISERROR( @ErrorMessage,16,1)      
              END CATCH      
             END--CONDITION 02 END      
           END      
         END --CONDITION 01 END      
        /******************************************************************************/      
        --SELECT @bigOrganizationID = OrganizationID FROM rvlfBoxId WHERE BoxId = @intBoxID      
        if(@tiBoxMsgInTypeId in (2,3,5,6,114,100))      
         begin      
          insert into @OrganizationPackage      
          select op.packageid ,po.Moduleid ,po.operationid ,operationtypename ,operationdesc from rvlfOrganizationPackage op      
          INNER JOIN rvlfPackageOperations po on op.PackageId=po.PackageId      
          INNER JOIN rvlfOperationType ot on po.OperationID=ot.OperationTypeId      
          inner join rvlforganization o on op.organizationid=o.organizationid      
          WHERE op.OrganizationID=@bigOrganizationID and op.IsActive=1 and o.ExpiresOn>=getdate()      
         end      
        --Student Punch Geozone In/Out      
        IF(@tiBoxMsgInTypeId IN(5,6,114) and CHARINDEX('GeozoneID=',@vcCustomProp,0)>0)      
         BEGIN      
          --School Geozone Entry/Exit      
          If exists (select * from rvlfSchoolMaster A inner join rvlfBoxId B on a.OrganizationID=B.OrganizationId      
          where B.BoxId=@intBoxID and GeozoneId=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'GeozoneID=',';')      
          and A.OrganizationId not in (select OrgId from rvlfGitscoSchoolMgmt)) --Disabled for GITSCO on 30-Oct-2017 --A.OrganizationId not in (6,352,412))      
           begin      
             Begin try      
              Exec rvlf_sp_GetandUpdateRFIDStudentSMSTrigger @intBoxID      
              print 'Student log RFID Updated'      
             end try      
            BEGIN CATCH      
            --ROLLBACK TRAN      
            SET @ErrorMessage = 'An Error occured during insert of RFID Student entry to school : ' + ERROR_MESSAGE()      
            RAISERROR( @ErrorMessage,16,1)      
            END CATCH      
           end      
  -- As per the client request, We have command the school Entry / Exit notification by karthikeyan.R on 2019-Nov-01.  
          --If exists (select * from rvlfSchoolMaster A inner join rvlfBoxId B on a.OrganizationID = B.OrganizationId      
          --where B.BoxId = @intBoxID and GeozoneId = dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'GeozoneID=',';')      
          --and A.OrganizationId in (select OrgId from rvlfGitscoSchoolMgmt)) --Disabled for GITSCO on 30-Oct-2017      
          -- begin      
          --   Begin try      
          --    Exec rvlf_sp_GetandUpdateRFIDStudentSMSTrigger_TripWise @intBoxID,@dtOriginDateTime,@vcCustomProp,@uiMsgInID,@tiBoxMsgInTypeId      
          --    print 'School geozone reached/started based on trips has been Updated'      
          --   end try      
          --  BEGIN CATCH      
          --  --ROLLBACK TRAN      
          --  SET @ErrorMessage = 'An Error occured during insert of School geozone reached/started based on trips : ' + ERROR_MESSAGE()      
          --  RAISERROR( @ErrorMessage,16,1)      
          --  END CATCH      
          -- end      
          --Student Pickup/Drop Geozone Entry      
          --If exists(select * from rvlfBoxId b      
          --inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId      
          --inner join rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1      
          --inner join rvlfPackageOperations po on op.PackageId=po.PackageId      
          --inner join rvlfOperationType ot on po.OperationID=ot.OperationTypeId      
          --Where b.BoxId=@intBoxID and @tiBoxMsgInTypeId = 5 and b.OrganizationId in (6)      
          --and charindex('Notification for Student Pickup point Entry',ot.OperationTypeName,1)>0)      
          If exists(select * from @OrganizationPackage b Where @tiBoxMsgInTypeId = 5 -- and @bigOrganizationID in (6)      
          and charindex('Notification for Student Pickup point Entry',b.OperationTypeName,1)>0)      
           BEGIN      
             BEGIN TRY      
              Exec rvlf_sp_TriggerSMSforStudentGeozoneEntry @intBoxID,@dtOriginDateTime,@vcCustomProp,@uiMsgInID      
              print 'Student Pickup point Entry Notification log Updated'      
             END TRY      
            BEGIN CATCH      
            --ROLLBACK TRAN      
            SET @ErrorMessage = 'An Error occured during insert of Student Pickup point Entry Notification : ' + ERROR_MESSAGE()      
            RAISERROR( @ErrorMessage,16,1)      
            END CATCH      
           END      
         END      
        --Student RFID Swipes Notifications by Anbarasu.E on 12-Aug-2015      
        IF(@tiBoxMsgInTypeId IN(100) and CHARINDEX('RF_ID=',@vcCustomProp,0)>0)      
         BEGIN      
          If exists (select * from rvlfStudentMaster where OrganizationID=@bigOrganizationID and RFID=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RF_ID=',';'))      
           begin      
             Begin try      
              -- if exists(select * from rvlfBoxId b inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId      
              --inner join rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1      
              --inner join rvlfPackageOperations po on op.PackageId=po.PackageId      
              --inner join rvlfOperationType ot on po.OperationID=ot.OperationTypeId      
              --where b.BoxId=@intBoxID and charindex('Notification for Each',ot.OperationTypeName,1)>0)      
              if exists(select * from @OrganizationPackage b where charindex('Notification for Each',b.OperationTypeName,1)>0)      
               Begin      
                Exec rvlf_sp_TriggerSMSforStudentRFIDSwipes @intBoxID,@dtOriginDateTime,@vcCustomProp,@uiMsgInID      
                print 'Student RFID swipes log Updated'      
               End      
             end try      
            BEGIN CATCH      
            --ROLLBACK TRAN      
            SET @ErrorMessage = 'An Error occured during insert of RFID Student swipe : ' + ERROR_MESSAGE()      
            RAISERROR( @ErrorMessage,16,1)      
            END CATCH      
           end      
         END      
        --Student SMS before stops reached      
        IF(@tiBoxMsgInTypeId=114 and charindex('34;Routeid',@vcCustomProp,1)>0)      
         BEGIN      
          Declare @AlertMsg varchar(3)=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'AlertMsg=',';'))      
          if(@AlertMsg='011' or @AlertMsg='001')      
           Begin      
            --if exists(select b.boxid from rvlfBoxId b inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId      
            --inner join rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1      
            --inner join rvlfPackageOperations po on op.PackageId=po.PackageId      
            --inner join rvlfOperationType ot on po.OperationID=ot.OperationTypeId      
            --where b.BoxId=@intBoxID and charindex('Notification before',ot.OperationTypeName,1)>0)      
            if exists(select * from @OrganizationPackage b where charindex('Notification before',b.OperationTypeName,1)>0)      
             begiN      
              exec rvlf_sp_TriggerSMSBfrStops @intBoxID,@dtOriginDateTime,@vcCustomProp      
             enD      
           End      
         END      
        IF(dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'SENSOR_NUM=',';') = '1' or dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'SENSOR_NUM=',';') = '2')      
         BEGIN      
          --IF EXISTS(select * from rvlfBoxId b inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId      
          --INNER JOIN rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1      
          --INNER JOIN rvlfPackageOperations po on op.PackageId=po.PackageId      
          --INNER JOIN rvlfOperationType ot on po.OperationID=ot.OperationTypeId      
          --WHERE b.BoxId=@intBoxID and charindex('Trip switch Notifications to Reporting Person',ot.OperationTypeName,1)>0)      
          if exists(select * from @OrganizationPackage b where charindex('Trip switch Notifications to Reporting Person',b.OperationTypeName,1)>0) and @tiBoxMsgInTypeId = 2      
           BEGIN      
            EXEC rvlf_sp_TriggerTripStartNotification @dtOriginDateTime,@vcCustomProp,@tiBoxMsgInTypeId,@intBoxID      
            EXEC rvlf_sp_TripDetails_GIT @intBoxID,@dtOriginDateTime,@uiMsgInID,1      
            print 'Trip switch ON Notifications log Updated'      
           END      
          --IF EXISTS(select b.boxid from rvlfBoxId b inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId      
          --INNER JOIN rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1      
          --INNER JOIN rvlfPackageOperations po on op.PackageId=po.PackageId      
          --INNER JOIN rvlfOperationType ot on po.OperationID=ot.OperationTypeId      
          --WHERE b.BoxId=@intBoxID and charindex('Trip switch based Headcount Notification to Reporting Person',ot.OperationTypeName,1)>0) and @tiBoxMsgInTypeId = 3      
          if exists(select * from @OrganizationPackage b where charindex('Trip switch based Headcount Notification to Reporting Person',b.OperationTypeName,1)>0) and @tiBoxMsgInTypeId = 3      
           BEGIN      
             BEGIN TRY      
              exec rvlf_sp_TriggerTripEndNotification @dtOriginDateTime,@vcCustomProp,2,@intBoxID,@uiMsgInID,@tiValidGps,@dLatitude,@dLongitude      
              EXEC rvlf_sp_TripDetails_GIT @intBoxID,@dtOriginDateTime,@uiMsgInID,0      
              print 'Trip switch OFF with Student Headcount Notifications log Updated'      
             END TRY      
            BEGIN CATCH      
            --ROLLBACK TRAN      
            SET @ErrorMessage = 'An Error occured during Gitsco Head count Notification : ' + ERROR_MESSAGE()      
            RAISERROR( @ErrorMessage,16,1)      
            END CATCH      
           END      
         END      
        --CHECK THE SCHEDULED OTA COMMAND RETRY**************************************************************      
        DECLARE @bigRetryScheduleId bigint=null,@tintAck tinyint=null,@dtOtaTime datetime=null      
        SELECT TOP 1 @tintAck=Acknowledged,@dtOtaTime=H.SentDateTime FROM rvlfMsgOutHst H      
        WHERE H.BoxCmdOutTypeId =22 AND H.BoxId =@intBoxID AND H.Acknowledged BETWEEN 0 AND 10 ORDER BY H.SentDateTime DESC      
        IF (@tintAck NOT IN(2,6) AND @tintAck IS NOT NULL)      
         BEGIN      
          IF EXISTS(SELECT ScheduleId FROM rvlfScheduleOfCommandsMaster WHERE Boxid=@intBoxID AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND BoxCmdOutTypeId =22)      
           BEGIN      
            SELECT @bigRetryScheduleId =a.ScheduleId FROM rvlfScheduleOfCommandsMaster a inner join rvlfSchedulingOfCommandsLog b      
            on a.ScheduleId=b.ScheduleId      
            WHERE Boxid=@intBoxID and ResponseMsg != 'Success' AND BoxCmdOutTypeId =22 AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND GETUTCDATE() BETWEEN EffectiveFrom AND EffectiveTo      
            IF @bigRetryScheduleId IS NOT NULL      
             BEGIN      
              UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=NULL WHERE ScheduleId =@bigRetryScheduleId AND BoxCmdOutTypeId=22      
              IF EXISTS(SELECT ScheduleLogId FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId)      
               BEGIN      
                UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=NULL,ActualExecutionDate=CASE WHEN @dtOtaTime>CreatedDate AND @dtOtaTime <=EffectiveTo THEN @dtOtaTime ELSE NULL END WHERE ScheduleId =@bigRetryScheduleId AND BoxCmdOutTypeId =22    



  
                DELETE rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId AND ResponseId IN (1,2,3,4,6,7,8,9,10) --RESPONSEMSG!='Aborted'      
               END      
             END      
           END      
         END      
        ELSE IF(@tintAck IS NULL)      
         BEGIN      
          SELECT @bigRetryScheduleId =ScheduleId FROM rvlfScheduleOfCommandsMaster      
          WHERE Boxid=@intBoxID AND BoxCmdOutTypeId =22 AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND GETUTCDATE() BETWEEN EffectiveFrom AND EffectiveTo      
          IF(@bigRetryScheduleId IS NOT NULL OR @bigRetryScheduleId!='')      
           BEGIN      
            IF NOT EXISTS(SELECT ScheduleLogId FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId)      
             BEGIN      
              INSERT INTO rvlfSchedulingOfCommandsLog (ScheduleId,ExecutionOn,IsCommandSend,[No.ofTries],ResponseMsg,ResponseId)      
              SELECT @bigRetryScheduleId,@dtOtaTime,1,1,'Command sent successfully.',3      
             END      
           END      
         END      
        --------------Get next route to assign ---------------------------------------      
        IF(@tiBoxMsgInTypeId=114 and charindex('AlertMsg=001',@vcCustomProp,1)>0)      
         Begin      
          DECLARE @vcType1 varchar(50)=null,@bigScheduleId1 bigint=null      
          SELECT top 1 @vcType1=ExecutionOn,@bigScheduleId1= ScheduleId FROM rvlfScheduleOfCommandsMaster SM      
          WHERE ScheduleId NOT IN(SELECT ScheduleId FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE())) AND SM.BoxId =@intBoxID and SM.Isdelete is null      
          AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))      
          AND (GETUTCDATE()<= EffectiveFrom      
          AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END))      
          AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE()))      
          order by EffectiveFrom asc      
          --UPDATE THE LATEST IP AND PORT      
          UPDATE rvlfScheduleOfCommandsMaster      
          SET PacketInfo = REPLACE(PacketInfo,SUBSTRING(PacketInfo,CHARINDEX('IP=',PacketInfo,1)+3,(CHARINDEX(';',PacketInfo,CHARINDEX('Port=',PacketInfo,1))-4)),@vcCommInfo1+';Port='+CAST(@siCommInfo2 AS VARCHAR))      
          WHERE ScheduleId=@bigScheduleId1      
          --IF THE COMMANDS EXECUTION TYPE IS Ignition On      
          IF (@vcType1 ='Ignition On' AND @tiBoxMsgInTypeId=2)      
           BEGIN      
            --INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn)      
            -- VALUES(@bigScheduleId1,GETUTCDATE())      
            INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)      
            VALUES(@bigScheduleId1,GETUTCDATE(),0)      
           END      
          ELSE IF(@vcType1 ='Any message in' AND @tiBoxMsgInTypeId =114)      
           BEGIN      
            INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId) VALUES(@bigScheduleId1,GETUTCDATE(),0)      
           END      
         End      
        ----------------------------------      
        /**************************************************************************************************/      
        --SCHEDULE THE COMMANDS****************************************************************************/      
        IF (((SELECT TOP 1 BoxId FROM rvlfBoxId WHERE BoxId=@intBoxID AND CONVERT(DATE,LastCommunicatedDateTime)=CONVERT(DATE,GETUTCDATE()))=@intBoxID) OR (@tiBoxMsgInTypeId=52))      
         BEGIN      
          --PRINT 'Welcome 5'      
          --CHECK IF THE BOXID HAVE ANY SCHEDULES FOR GIVE COMMANDS      
          IF EXISTS(SELECT ScheduleId FROM rvlfScheduleOfCommandsMaster SM      
     WHERE ScheduleId NOT IN(SELECT ScheduleId FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE()))      
          AND SM.BoxId =@intBoxID and SM.Isdelete is null      
          AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))      
          --AND (GETUTCDATE()>= EffectiveFrom      
          --AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END)) and BoxCmdOutTypeId<>94      
          AND (GETUTCDATE()>= (case when BoxCmdOutTypeId=94 then DATEADD(MINUTE,-30,EffectiveFrom) else EffectiveFrom end)      
          AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END))      
          AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE())))      
           BEGIN      
            --PRINT 'Welcome 6'      
            DECLARE @TBLSCHEDULES TABLE(ScheduleId bigint,inc bit)      
            INSERT INTO @TBLSCHEDULES(ScheduleId,inc)      
            SELECT DISTINCT SM.ScheduleId,0 FROM rvlfScheduleOfCommandsMaster SM      
            WHERE ScheduleId NOT IN(SELECT ScheduleId FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE()))      
            AND SM.BoxId =@intBoxID and SM.Isdelete is null      
            AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))      
            -- AND (GETUTCDATE()>= EffectiveFrom      
            --AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END)) and BoxCmdOutTypeId<>94      
            AND (GETUTCDATE()>= (case when BoxCmdOutTypeId=94 then DATEADD(MINUTE,-30,EffectiveFrom) else EffectiveFrom end)      
            AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END))      
            AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE()))      
            WHILE EXISTS(SELECT ScheduleId FROM @TBLSCHEDULES WHERE inc =0)      
             BEGIN      
              --PRINT 'Welcome 7'      
              DECLARE @vcType varchar(50)=null,@bigScheduleId bigint=null      
              SELECT @bigScheduleId=ScheduleId FROM @TBLSCHEDULES WHERE inc=0      
              --UPDATE THE LATEST IP AND PORT      
              UPDATE rvlfScheduleOfCommandsMaster      
              SET PacketInfo = REPLACE(PacketInfo,SUBSTRING(PacketInfo,CHARINDEX('IP=',PacketInfo,1)+3,(CHARINDEX(';',PacketInfo,CHARINDEX('Port=',PacketInfo,1))-4)),@vcCommInfo1+';Port='+CAST(@siCommInfo2 AS VARCHAR))      
              WHERE ScheduleId=@bigScheduleId      
              SELECT TOP 1 @vcType=ExecutionOn,@bigScheduleId=ScheduleId FROM rvlfScheduleOfCommandsMaster      
              WHERE ScheduleId=@bigScheduleId      
              --IF THE COMMANDS EXECUTION TYPE IS Ignition On      
              IF (@vcType ='Ignition On' AND @tiBoxMsgInTypeId=2)      
               BEGIN      
                INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)      
                VALUES(@bigScheduleId,GETUTCDATE(),0)      
               END      
              ELSE IF(@vcType ='Any message in' AND @tiBoxMsgInTypeId NOT IN(12))      
               BEGIN      
                INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)      
                VALUES(@bigScheduleId,GETUTCDATE(),0)      
               END      
              UPDATE TOP(1) @TBLSCHEDULES SET inc=1 WHERE ScheduleId=@bigScheduleId      
             END      
           END      
         END 
--		 IF EXISTS(select * from rvlfRouteVehicleAssignment rva inner join rvlfVehicleAssignment va on rva.VehicleId = va.VehicleId
--where BoxId =@intboxid and rva.TripStatus=2 and CONVERT(date,FromDateTime) = CONVERT(Date,GETDATE()))
--		 BEGIN		  
--		  	exec rvlf_sp_Getinoutlandmark_Route @uiMsgInid,@bigOrganizationID,@dlatitude, @dlongitude,@intboxid,@vcStreetAddress, @vcNearestLandmark;						
--		 END     
       END      
     END      
   END     
    
  SET NOCOUNT OFF      
 end
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateMessageReceived_old]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateMessageReceived_old]
	@intBoxID int,
	@dtOriginDateTime datetime,
	@dtDateTimeReceived datetime, 
	@vcCommMode varchar(100),
	@vcBoxMsgInTypeName varchar(50) = null,
	@vcBoxProtocolTypeName varchar(50) = null,
	@vcCommInfo1 varchar(15),
	@siCommInfo2 int ,
	@tiValidGps tinyint = 2,
 	@dLatitude decimal(10,6) = 0,
 	@dLongitude decimal(10,6) = 0,
 	@tiSpeed tinyint = 0,
 	@siHeading  smallint = 0,
 	@vcSensorMask varchar(8) = null,
 	@vcCustomProp varchar(600)= null,
 	@bigSequenceNum bigint = null,
 	@bitIsArmed bit = null,
 	@tiPriority tinyint = null,
	@bitIsAlarm bit =0,
	@dtSentDateTime datetime = null,
	@bitIgnitionStatus bit = null,
	@bigOdoMeterReading bigint = null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_UpdateMessageReceived]
--	Description	:	To insert the messages that is orginated from the device 
--					also in relevant tables.
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	25-May-2009	MJJC	Created Intial Version 
--				:	08-Jan-2010 MJJC	Included the messaginId update for rvlfboxid table
--				:	01-Feb-2010 MJJC	Changed the parameters to the alarm details function.
--				:	13-Apr-2010	MJJC	Updated the streetaddress if lat & lng exists.
--				:	26-Apr-2010 MJJC	Checked the Message type for rvlfBoxID Processing
--				:	18-May-2010	MJJC	Checked the data integrity / duplication
--				:	19-Jun-2010	MJJC	Checked the idling start for ignoring the alarm
--				:	28-AUG-2010 VN		To update the datetimereceived value if the value greater then origindatetime.
--				:	30-Aug-2010 VN      update the origindatetime if origindatetime is greater then current date time	
--				:	02-sEP-2010 VN		Log the notifications if the messages based on the geozone.
--				:	17-Sep-2010 TSK		Fine tuned the Query for optimization and commented the Bg_Process to avoid Deadlock.
--              :   06-Dec-2010 LK      Removed the Keep Alive Packet from inserting
--			    :   30-Mar-2011 LK      Included the insertion of Driver Id into Alarms Table
--				:	17-Apr-2011 VN		Included the scheduling of commands for the keepalive packets(boxmsgid-52) and
--				:						Restricted the scheduling of commands for sleep mode packets(boxmgsid-12)
--				:	06-Jun-2011 TSK		Enabled the Geozone Msg in Monitor screen
--				:	06-Jul-2011 TSK		Included Validation to insert CommAddressType to 1, SET DEFAULT VALUE TO 1
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
	DECLARE @tiBoxMsgInTypeId tinyint
	DECLARE @intBoxProtocolTypeId int
	DECLARE @tiServiceID tinyint
	DECLARE @tiCommModeId tinyint
	DECLARE @MsgInID TABLE ( uiMsgInID uniqueidentifier)
	DECLARE @uiMsgInID uniqueidentifier
	DECLARE @DemoMsgInID TABLE ( uiDemoMsgInID uniqueidentifier)
	DECLARE @uiDemoMsgInID uniqueidentifier
	DECLARE @vcOldIP varchar(25) 
	DECLARE @vcNewIP varchar(25) 
	SET @vcNewIP = @vcCommInfo1 + ':'+ CAST(@siCommInfo2 AS varchar(5))
	DECLARE @bigOrganizationID bigint
	DECLARE @dtLastValidGPSTime datetime 
	DECLARE @bitCreateAlarm bit
	DECLARE @tiAlarmLevelID tinyint
	--DECLARE @bitCanNotify bit
	DECLARE @bigGeoZoneID bigint
	DECLARE @vcAlarmLevelName varchar(30)
	SET @dtLastValidGPSTime = @dtOriginDateTime 
	DECLARE @IsAddressAlreadyAvailable bit = 0
	DECLARE @vcStreetAddress varchar(250)
	DECLARE @vcNearestLandmark varchar(300)
	

		
	--update the origindatetime if origindatetime is greater then current date time	
	IF(@dtOriginDateTime>CONVERT(datetime,CONVERT(varchar(19),SYSUTCDATETIME())))
		BEGIN
			SET @dtOriginDateTime=CONVERT(datetime,CONVERT(varchar(19),SYSUTCDATETIME()))
		END
		
	--update the datetimerecived if datetimerecived is greater then origindatetime	
	IF(@dtOriginDateTime>=@dtDateTimeReceived)
		BEGIN
			SET @dtDateTimeReceived=DATEADD(S,2,@dtOriginDateTime)
		END
	
	-- Gets the required IDS.
	SELECT @tiBoxMsgInTypeId = BoxMsgInTypeId FROM rvlfBoxMsgInType 
				WHERE BoxMsgInTypeName = @vcBoxMsgInTypeName
	
	--Restricted the tamper msgs for girish and mastermarine organization
	IF(@intBoxID NOT IN(SELECT BOXID FROM rvlfBoxId WHERE OrganizationId=78) OR @tiBoxMsgInTypeId!=41)
	IF(@intBoxID NOT IN(SELECT BOXID FROM rvlfBoxId WHERE OrganizationId=101) OR @tiBoxMsgInTypeId!=41)
	IF(@intBoxID NOT IN(SELECT BOXID FROM rvlfBoxId WHERE OrganizationId=40) OR @tiBoxMsgInTypeId!=87)
		BEGIN				
				
	--CHECK THE ALARM PAKET WITH DRIVER PANIC MSG FOR SANKARA
	IF @tiBoxMsgInTypeId =11 AND @vcCustomProp  LIKE '%SENSOR_NUM=6;%' AND @intBoxID IN(SELECT BOXID FROM rvlfBoxId WHERE OrganizationId=22)		
		BEGIN	
			PRINT 'DRIVER PANIC BUTTON ALARM FOR SANKARA'
		END
	ELSE
		BEGIN	
		 --For Defense Demo BoxID mapping
	DECLARE @intDemoBoxID int=NULL	
	IF(@tiBoxMsgInTypeId NOT IN (SELECT BoxMsgInTypeId FROM rvlfBoxMsgInType where BoxMsgInTypeName like '%fuel%'))
	BEGIN
	--SET @intDemoBoxID =  CASE WHEN @intBoxID = 189 THEN 10001   
	--							 WHEN @intBoxID = 190 THEN 10002
	--							 WHEN @intBoxID = 45 THEN 10003
	--							 WHEN @intBoxID = 37 THEN 10004
	--							 WHEN @intBoxID = 38 THEN 10005
	--							 WHEN @intBoxID = 3 THEN 10006
	--							 WHEN @intBoxID = 192 THEN 10007
	--							 WHEN @intBoxID = 188 THEN 10008
	--							 WHEN @intBoxID = 43 THEN 10009
	--							 WHEN @intBoxID = 169 THEN 10010
	--							 WHEN @intBoxID = 27 THEN 10011
	--							 WHEN @intBoxID = 171 THEN 10012
	--							 WHEN @intBoxID = 172 THEN 10013
	--							 WHEN @intBoxID = 32 THEN 10014
	--							 WHEN @intBoxID = 193 THEN 10015
	--							 WHEN @intBoxID = 194 THEN 10016
	--							 WHEN @intBoxID = 191 THEN 10017 
	--							 ELSE NULL END
	SET @intDemoBoxID =  CASE WHEN @intBoxID = 101 THEN 10001   
								 WHEN @intBoxID = 104 THEN 10002
								 WHEN @intBoxID = 112 THEN 10003
								 WHEN @intBoxID = 114 THEN 10004
								 WHEN @intBoxID = 115 THEN 10005
								 WHEN @intBoxID = 117 THEN 10006
								 WHEN @intBoxID = 118 THEN 10007
								 WHEN @intBoxID = 119 THEN 10008
								 WHEN @intBoxID = 121 THEN 10009
								 WHEN @intBoxID = 206 THEN 10010
								 WHEN @intBoxID = 237 THEN 10011
								 WHEN @intBoxID = 242 THEN 10012
								 WHEN @intBoxID = 247 THEN 10013
								 WHEN @intBoxID = 248 THEN 10014
								 WHEN @intBoxID = 288 THEN 10015
								 WHEN @intBoxID = 323 THEN 10016
								 WHEN @intBoxID = 249 THEN 10017 
								 ELSE NULL END
	END		
 
  	
  	--Update Username
	--IF(@tiBoxMsgInTypeId=100)  
	--BEGIN     
	--	DECLARE @KeyUserName varchar(max)=NULL  
	--	SELECT @KeyUserName=UserName  FROM rvlfIButtonMapping   
	--		WHERE IButtonKey=CASE WHEN @vcCustomProp LIKE '%RF ID=%' 
	--		THEN 
	--		CAST(SUBSTRING (@vcCustomProp,CHARINDEX('RF ID=',@vcCustomProp,1)+6,CHARINDEX(';',@vcCustomProp,  
	--			CHARINDEX('RF ID=',@vcCustomProp,1)) - (CHARINDEX('RF ID=',@vcCustomProp,1)+6)) as varchar) 
	--		ELSE null END  
    
	 --   IF(@KeyUserName IS NOT NULL)  
		--BEGIN  
		--	SET @vcCustomProp=@vcCustomProp + 'UserName=' +  @KeyUserName + ';'
		--END  
		--ELSE  
		--BEGIN  
		--	SET @vcCustomProp= @vcCustomProp + 'UserName=Unknown;' 
		--END  
    		 --END  
	--update driver key messages
	IF(@tiBoxMsgInTypeId=76)
		BEGIN
			SET @vcCustomProp=@vcCustomProp+'ignition='+CAST(@bitIgnitionStatus as varchar)+';' 
			SET @vcSensorMask='00000000'
			DECLARE @DRIVERID BIGINT=NULL
			SELECT @DRIVERID=DriverId  FROM rvlfIButtonMapping 
				WHERE IButtonKey=CASE WHEN @vcCustomProp LIKE '%Driver ID=%' THEN CAST(SUBSTRING (@vcCustomProp,CHARINDEX('Driver ID=',@vcCustomProp,1)+10,CHARINDEX(';',@vcCustomProp,
								CHARINDEX('Driver ID=',@vcCustomProp,1)) - (CHARINDEX('Driver ID=',@vcCustomProp,1)+10)) as varchar) ELSE '0' END
			
			-- updated BoxID aganist Driver based on Ibutton punch	
			declare @result varchar(5)
	SET @result = CASE WHEN @vcCustomProp LIKE '%Driver Status=%' THEN  CAST(SUBSTRING (@vcCustomProp,CHARINDEX('Driver Status=',@vcCustomProp,1)+14,CHARINDEX(';',@vcCustomProp,
								CHARINDEX('Driver Status=',@vcCustomProp,1)) - (CHARINDEX('Driver Status=',@vcCustomProp,1)+14)) as varchar) ELSE 'OUT' END					
	IF(@result='OUT')
		BEGIN
			DECLARE @dtPunchin DATETIME=NULL
			SELECT @dtPunchin=PUNCHINTIME FROM rvlfIButtonMapping WHERE BoxID=@intBoxID AND DriverId=@DRIVERID
			IF(@dtPunchin IS NOT NULL)
				BEGIN
				IF EXISTS(SELECT AssignmentId FROM rvlfDriverAssignment WHERE BOXID=@intBoxID 
						AND DriverId=@DRIVERID 
						AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime)) 
						AND (@dtPunchin <=ToTime) 
						AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime)
						AND PunchIn IS NULL AND PunchOut IS NULL)
					BEGIN	
						UPDATE 	rvlfDriverAssignment SET PunchIn =@dtPunchin,PunchOut=@dtOriginDateTime  
							WHERE BOXID=@intBoxID 
								AND DriverId=@DRIVERID 
								AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime)) 
								AND (@dtPunchin <=ToTime) 
								AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime)
								AND PunchIn IS NULL AND PunchOut IS NULL
					END	
				ELSE IF EXISTS(SELECT AssignmentId FROM rvlfDriverAssignment WHERE BOXID=@intBoxID 
						AND DriverId=@DRIVERID 
						AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime)) 
						AND (@dtPunchin <=ToTime) 
						AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime)
						AND PunchIn IS NOT NULL AND PunchOut IS NOT NULL)		
					BEGIN
						INSERT INTO rvlfDriverAssignment(DriverId,FromTime,ToTime,PunchIn,PunchOut,BOXID,AssignmentDate,IsAmtIssued,AssignedDate)
							SELECT TOP 1 @DRIVERID,FromTime,ToTime,@dtPunchin,@dtOriginDateTime,@intBoxID,CONVERT(DATE,GETDATE()),0,GETDATE()
								FROM rvlfDriverAssignment WHERE BOXID=@intBoxID 
									AND DriverId=@DRIVERID 
									AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime)) 
									AND (@dtPunchin <=ToTime) 
									AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime)
									AND PunchIn IS NOT NULL AND PunchOut IS NOT NULL
					END
				ELSE
					BEGIN
						INSERT INTO rvlfDriverAssignment(DriverId,PunchIn,PunchOut,BOXID,AssignmentDate,IsAmtIssued,AssignedDate)
							VALUES(@DRIVERID,@dtPunchin,@dtOriginDateTime,@intBoxID,CONVERT(DATE,GETDATE()),0,GETDATE())  
					END
				END 
		END
								
		Update RVLFIButtonMapping SET Boxid = CASE WHEN @result = 'IN' THEN @intBoxID ELSE 0 END,PunchInTime=CASE WHEN @result = 'IN' THEN @dtOriginDateTime ELSE NULL END WHERE DriverId = @DRIVERID
		-- Update RVLFIButtonMapping SET BoxID = @intBoxID where DriverId = @DRIVERID
				
				IF(@DRIVERID IS NOT NULL)
					BEGIN
						SET @vcCustomProp=@vcCustomProp+'MAPID='+CAST(@DRIVERID as varchar)
					END
				ELSE
					BEGIN
						SET @vcCustomProp=@vcCustomProp+'MAPID=0'
					END
			END
		
		
    IF @tiBoxMsgInTypeId <> 52
	BEGIN				
		IF Exists (SELECT MessageInID FROM rvlfMsgInHst WHERE BoxId = @intBoxID AND BoxMsgInTypeId = @tiBoxMsgInTypeId AND
			OriginDateTime = @dtOriginDateTime AND CustomProp = @vcCustomProp )
			BEGIN
				raiserror('Data Integrity Violation', 16,1)
			END			
		ELSE
			BEGIN
				IF EXISTS(SELECT MessageInID FROM rvlfMsgInHst WHERE Latitude=@dLatitude AND Longitude = @dLongitude AND StreetAddress IS NOT NULL) AND @tiValidGps = 0
					BEGIN
						SET @IsAddressAlreadyAvailable=1
						SELECT TOP 1 @vcStreetAddress= StreetAddress, @vcNearestLandmark= NearestLandmark FROM rvlfMsgInHst WHERE Latitude=@dLatitude AND Longitude = @dLongitude
					END

				SELECT @intBoxProtocolTypeId = BoxProtocolTypeId FROM rvlfBoxProtocolType 
					WHERE BoxProtocolTypeName = @vcBoxProtocolTypeName 
					
				SELECT @tiCommModeId = CommModeId FROM rvlfCommMode 
						WHERE CommModeName = @vcCommMode
						
				SELECT @tiServiceID = ServiceID FROM rvlfServices 
					WHERE CommModeId = @tiCommModeId
				
				SELECT @vcOldIP = commAddressValue FROM rvlfBoxCommInfo WHERE BoxId = @intBoxID 
				
				SELECT @bigOrganizationID = OrganizationID FROM rvlfVehicle WHERE
					VehicleId = (SELECT VehicleId FROM rvlfVehicleAssignment WHERE
						BoxId = @intBoxID)
						
			 /***************************Severity Settings**********************************/
			 -- Checks if the message has the severity settings such that an alarm has to be created.
					IF EXISTS ( SELECT BoxId FROM rvlfBoxMsgSeverity 
						WHERE BoxId=@intBoxID AND BoxMsgInTypeId = @tiBoxMsgInTypeID)
					BEGIN
						DECLARE @intDuration int = 1 
						IF @tiBoxMsgInTypeId = 9 
							BEGIN
								SET @intDuration = CAST (SUBSTRING (@vcCustomProp, CHARINDEX(':',@vcCustomProp,1)+1,
										CHARINDEX(';',@vcCustomProp)-1 -CHARINDEX(':',@vcCustomProp,1)) as Int)
							END
						IF @intDuration > 0
							BEGIN
								SELECT @bitCreateAlarm = s.CreateAlarm, /*@bitCanNotify = s.CanSendNotification ,*/
									@tiAlarmLevelID = bs.AlarmLevelID, @vcAlarmLevelName = s.AlarmLevelName
								FROM rvlfBoxMsgSeverity bs INNER JOIN rvlfSeverity s
								On bs.AlarmLevelID = s.AlarmLevelId WHERE bs.BoxId = @intBoxID AND
								bs.BoxMsgInTypeId = @tiBoxMsgInTypeID 
							END
					END
					ELSE
					BEGIN
						SELECT @bitCreateAlarm = s.CreateAlarm, /*@bitCanNotify = s.CanSendNotification ,*/
							@tiAlarmLevelID = bs.DefaultAlarmLevel, @vcAlarmLevelName = s.AlarmLevelName
						FROM rvlfBoxProtocolMsgInType bs INNER JOIN rvlfSeverity s
						On bs.DefaultAlarmLevel = s.AlarmLevelId WHERE 
						bs.BoxMsgInTypeId = @tiBoxMsgInTypeID 
					END
					
					IF @tiBoxMsgInTypeId =5 OR @tiBoxMsgInTypeId =6
					BEGIN
						SET @bigGeoZoneID =CAST( SUBSTRING(@vcCustomProp,
							CHARINDEX('=',@vcCustomProp,1)+1,(CHARINDEX(';',@vcCustomProp,1)
							- CHARINDEX('=',@vcCustomProp,1))-1) as bigint)
							
						SELECT /*@bitCanNotify = s.CanSendNotification, */ @bitCreateAlarm = s.CreateAlarm ,
							@tiAlarmLevelID = s.AlarmLevelId, @vcAlarmLevelName = s.AlarmLevelName
						FROM 
						  rvlfOrganizationGeozone g INNER JOIN rvlfSeverity s
						  ON g.SeverityId  = s.AlarmLevelId
						WHERE 
							g.OrganizationId = @bigOrganizationID AND g.GeozoneId = @bigGeoZoneID 
							--AND (g.Notify = 1 OR g.Warning=1 OR g.Critical=1)
					END
					IF @tiBoxMsgInTypeId = 11
					BEGIN
						DECLARE @tiSensorID tinyint
						SET @tiSensorID = CAST(SUBSTRING(@vcCustomProp,CHARINDEX('=',@vcCustomProp)+1,1) As tinyint)
						DECLARE @intSensorStateStart int 
						SET @intSensorStateStart = CHARINDEX('=',@vcCustomProp,LEN('SENSOR_NUM=')+1)
						DECLARE @intSensorStateEnd int 
						SET @intSensorStateEnd = CHARINDEX(';',@vcCustomProp,15)
						DECLARE @vcSensorStatus varchar(10);
						SET @vcSensorStatus =CASE WHEN @vcCustomProp LIKE '%SENSOR_STATUS=%' THEN SUBSTRING(@vcCustomProp,
												CHARINDEX('SENSOR_STATUS=',@vcCustomProp,0)+14,
												(CHARINDEX(';',@vcCustomProp,(CHARINDEX('SENSOR_STATUS=',@vcCustomProp,0)))-(CHARINDEX('SENSOR_STATUS=',@vcCustomProp,0)+14))) 
												ELSE 
											    SUBSTRING(@vcCustomProp,@intSensorStateStart+1, @intSensorStateEnd - @intSensorStateStart-1)END
						--SET @vcSensorStatus = SUBSTRING(@vcCustomProp,@intSensorStateStart+1, @intSensorStateEnd - @intSensorStateStart-1)
						DECLARE @bitIsOn bit
						SET @bitIsOn = 
							CASE WHEN @vcSensorStatus = 'OPEN' OR @vcSensorStatus = 'ON' OR @vcSensorStatus = 'NORMAL' 
								OR @vcSensorStatus = 'OK' THEN 1
							WHEN @vcSensorStatus = 'CLOSE' OR @vcSensorStatus = 'OFF' OR @vcSensorStatus = 'LOW' THEN 0
							END
						IF EXISTS (SELECT BoxId FROM rvlfBoxSensorsCfg WHERE BoxId = @intBoxID AND SensorId = @tiSensorID)
						BEGIN
							SELECT @bitCreateAlarm = s.CreateAlarm , 
								@tiAlarmLevelID = s.AlarmLevelId, @vcAlarmLevelName = s.AlarmLevelName
							FROM rvlfBoxSensorsCfg bs INNER JOIN rvlfSeverity s ON s.AlarmLevelId =
								(CASE WHEN @bitIsOn=1 THEN bs.AlarmLevelOn ELSE AlarmLevelOff END)
								WHERE bs.BoxId = @intBoxID AND bs.SensorId = @tiSensorID 
						END
						ELSE
						BEGIN
							SELECT @bitCreateAlarm = s.CreateAlarm, /*@bitCanNotify = s.CanSendNotification ,*/
								@tiAlarmLevelID = bs.DefaultAlarmLevel, @vcAlarmLevelName = s.AlarmLevelName
							FROM rvlfBoxProtocolMsgInType bs INNER JOIN rvlfSeverity s
							On bs.DefaultAlarmLevel = s.AlarmLevelId WHERE 
							bs.BoxMsgInTypeId = @tiBoxMsgInTypeID 
						END
					
					END
					
					IF @tiBoxMsgInTypeId = 27 
					BEGIN
						SET @bitCreateAlarm = 1
					END
					
				BEGIN TRAN MessageTransaction
				BEGIN TRY
				
			/***********************Message In History*************************************/
					-- To insert the information in the message in history table
					INSERT INTO rvlfMsgInHSt 
					(
						BoxID , OriginDateTime , DateTimeReceived , 
						ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,
						CommInfo2 , ValidGps , Latitude ,Longitude , Speed , 
						Heading , SensorMask , CustomProp , SequenceNum ,
						IsArmed , Priority , StreetAddress, NearestLandmark , IsNotificationSent
					)
						OUTPUT  INSERTED.MessageInID into @MsgInID
					VALUES
					(
						@intBoxID , @dtOriginDateTime , @dtDateTimeReceived , 
						@tiServiceID ,@tiBoxMsgInTypeId, @intBoxProtocolTypeId , @vcCommInfo1 , 
						@siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed , 
						@siHeading  , @vcSensorMask , @vcCustomProp , @bigSequenceNum , 
						@bitIsArmed , @tiPriority , 
						CASE WHEN @tiValidGps = 0 THEN 
								CASE WHEN @IsAddressAlreadyAvailable = 1 AND @vcStreetAddress!='N/A' THEN @vcStreetAddress ELSE NULL END 
							 ELSE 'N/A' END,
						CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,0
						--CASE WHEN @tiValidGps > 0 THEN 0 ELSE 0 END
					)
					
					SELECT @uiMsgInID = uiMsgInID FROM @MsgInID
					
							-- Demo Entry Insertion
				IF(@intDemoBoxID IS NOT NULL)
					BEGIN
						INSERT INTO rvlfMsgInHSt 
						(
							BoxID , OriginDateTime , DateTimeReceived , 
							ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,
							CommInfo2 , ValidGps , Latitude ,Longitude , Speed , 
							Heading , SensorMask , CustomProp , SequenceNum ,
							IsArmed , Priority , StreetAddress, NearestLandmark , IsNotificationSent
						)
							OUTPUT  INSERTED.MessageInID into @demoMsgInID
						VALUES
						(
							@intDemoBoxID , @dtOriginDateTime , @dtDateTimeReceived , 
							@tiServiceID ,@tiBoxMsgInTypeId, @intBoxProtocolTypeId , @vcCommInfo1 , 
							@siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed , 
							@siHeading  , @vcSensorMask , @vcCustomProp , @bigSequenceNum , 
							@bitIsArmed , @tiPriority , 
							CASE WHEN @tiValidGps = 0 THEN 
									CASE WHEN @IsAddressAlreadyAvailable = 1 AND @vcStreetAddress!='N/A' THEN @vcStreetAddress ELSE NULL END 
								 ELSE 'N/A' END,
							CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,0
							--CASE WHEN @tiValidGps > 0 THEN 0 ELSE 0 END
						)
						SELECT @uiDemoMsgInID = uidemoMsgInID FROM @demoMsgInID
					END
								
					/****************************Box ID Table**************************************/
					-- Inserts into the rvlfBoxID if sensor mask is available in the information.
					-- Removed the sensor Mask condition as 0 to show Geozone Msgs
					IF @vcSensorMask IS NOT NULL AND @tiBoxMsgInTypeId <> 51 AND @tiValidGps <>2
					BEGIN
						IF @tiValidGps <> 0 
						BEGIN
							SELECT @dtLastValidGPSTime = ISNULL(max(OriginDateTime), @dtOriginDateTime) FROM rvlfMsgInHst 
								WHERE BoxId = @intBoxID and ValidGps = 0 and SensorMask IS NOT NULL
						END
						DECLARE  @dtLastValidDateTime DateTime
						SELECT @dtLastValidDateTime = LastValidDateTime FROM rvlfBoxId
								WHERE BoxId = @intBoxID
						-- Checks if the last information exists for the box, if so updates else inserts
						IF @dtOriginDateTime >= @dtLastValidDateTime
						BEGIN
							IF EXISTS(SELECT BoxId FROM rvlfBoxId WHERE BoxId = @intBoxID) 
							BEGIN
								UPDATE rvlfBoxId SET 
									BoxArmed = @bitIsArmed,
									LastValidDateTime = CASE WHEN @tiValidGps = 0 THEN @dtOriginDateTime ELSE LastValidDateTime END,
									LastLatitude = CASE WHEN @tiValidGps = 0 THEN @dLatitude 
										ELSE LastLatitude END,
									LastLongitude = CASE WHEN @tiValidGps = 0 THEN @dLongitude 
										ELSE LastLongitude END , 
									LastSpeed = @tiSpeed,
									LastCommunicatedDateTime = @dtDateTimeReceived,
									LastSensorMask = @vcSensorMask, 
									OrganizationId = @bigOrganizationID,
									LastStatusDateTime = @dtOriginDateTime,
									LastStreetAddress = CASE WHEN @tiValidGps = 0 THEN NULL 
										ELSE LastStreetAddress END,
									NearestLandmark = CASE WHEN @tiValidGps = 0 THEN NULL 
										ELSE NearestLandmark END,
									Heading = @siHeading,
									MessageInId = @uiMsgInID
								WHERE BoxId = @intBoxID																				
							
							-- Demo Account Mapping
								IF(@intDemoBoxID IS NOT NULL)
								BEGIN								
									UPDATE rvlfBoxId SET 
									BoxArmed = @bitIsArmed,
									LastValidDateTime = CASE WHEN @tiValidGps = 0 THEN @dtOriginDateTime ELSE LastValidDateTime END,
									LastLatitude = CASE WHEN @tiValidGps = 0 THEN @dLatitude 
										ELSE LastLatitude END,
									LastLongitude = CASE WHEN @tiValidGps = 0 THEN @dLongitude 
										ELSE LastLongitude END , 
									LastSpeed = @tiSpeed,
									LastCommunicatedDateTime = @dtDateTimeReceived,
									LastSensorMask = @vcSensorMask, 
									OrganizationId = 55,
									LastStatusDateTime = @dtOriginDateTime,
									LastStreetAddress = CASE WHEN @tiValidGps = 0 THEN NULL 
										ELSE LastStreetAddress END,
									NearestLandmark = CASE WHEN @tiValidGps = 0 THEN NULL 
										ELSE NearestLandmark END,
									Heading = @siHeading,
									MessageInId = @uiDemoMsgInID
								WHERE BoxId = @intDemoBoxID								
								END	
								
								IF EXISTS(SELECT MessageInID FROM rvlfMsgInHst WHERE BoxId=@intBoxID AND CommInfo1 IS NULL)
									BEGIN
										DELETE FROM rvlfMsgInHst WHERE BoxId=@intBoxID AND CommInfo1 IS NULL
									END
							END
							ELSE
							BEGIN
								INSERT INTO rvlfBoxId 
								( 
									BoxId, BoxArmed, LastValidDateTime, LastLatitude, LastLongitude, 
									LastSpeed, LastCommunicatedDateTime, LastSensorMask, 
									OrganizationId, LastStatusDateTime, Heading , LastStreetAddress ,
									NearestLandmark, MessageInId
								)
								VALUES
								(
									@intBoxID, @bitIsArmed, @dtLastValidGPSTime, @dLatitude, @dLongitude,
									@tiSpeed, @dtDateTimeReceived, @vcSensorMask, 
									@bigOrganizationID, @dtOriginDateTime, @siHeading, 
									CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,
									CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,
									@uiMsgInID
								)		
								
								--Demo Acoount Mapping
								IF(@intDemoBoxID IS NOT NULL)
								BEGIN
									INSERT INTO rvlfBoxId 
								( 
									BoxId, BoxArmed, LastValidDateTime, LastLatitude, LastLongitude, 
									LastSpeed, LastCommunicatedDateTime, LastSensorMask, 
									OrganizationId, LastStatusDateTime, Heading , LastStreetAddress ,
									NearestLandmark, MessageInId
								)
								VALUES
								(
									@intDemoBoxID, @bitIsArmed, @dtLastValidGPSTime, @dLatitude, @dLongitude,
									@tiSpeed, @dtDateTimeReceived, @vcSensorMask, 
									55, @dtOriginDateTime, @siHeading, 
									CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,
									CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,
									@uiDemoMsgInID
								)
								END																					
							END
						END
					END
			/******************************************************************************/
			/*************************Alarm Processing*************************************/
					-- Inserts to Alarm table, if it is an alarm.					
					IF @bitIsAlarm = 1 Or @bitCreateAlarm = 1
					BEGIN
						DECLARE @siAlarmLevelID smallint
						DECLARE @bigAlarmID bigint 
						DECLARE @bigDriverID bigint = NULL
						
						SELECT @bigAlarmID  = ISNULL(Max(AlarmID),0)+1 FROM rvlfAlarm
						SELECT @bigDriverID = DriverId FROM RVLFIButtonMapping WHERE BoxID = @intBoxID
						
						IF(@bigDriverID IS NULL OR @bigDriverID='')
							BEGIN
								SELECT @bigDriverID = DriverId FROM rvlfDriverAssignment 
									WHERE BoxID = @intBoxID
										AND @dtOriginDateTime BETWEEN FromTime AND ToTime 
										AND CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime)									
							END
						
						-- TO DO
						IF(@tiAlarmLevelID is null OR @tiAlarmLevelID='')
							BEGIN
								SET @tiAlarmLevelID = 4 -- hardcoded to avoid AlarmLeveleID issue
							END
						INSERT INTO rvlfAlarm 
						(
							AlarmId,
							AlarmLevelId,
							DateTimeCreated ,
							BoxId ,
							AlarmType ,
							Lat ,
							Long ,
							[Description],
							StreetAddress,
							DriverId
						)
						VALUES
						(
							@bigAlarmID ,
							@tiAlarmLevelID,
							@dtOriginDateTime ,
							@intBoxID ,
							@tiBoxMsgInTypeId,
							@dLatitude ,
							@dLongitude ,
							CASE WHEN @tiBoxMsgInTypeId IN (5 , 6) THEN CAST(@bigGeoZoneID AS varchar(600))
								 WHEN @tiBoxMsgInTypeId = 4 THEN CAST (@tiSpeed As Varchar(600))
								 ELSE dbo.rvlf_fn_GetAlarmDetails(@vcCustomProp , @tiBoxMsgInTypeId, @intBoxID,@uiMsgInID, @dtOriginDateTime) END,
							CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END, @bigDriverID
						)	
						
						-- Demo Account Mapping
						IF(@intDemoBoxID IS NOT NULL)						
						BEGIN
						SELECT @bigAlarmID  = ISNULL(Max(AlarmID),0)+1 FROM rvlfAlarm
							INSERT INTO rvlfAlarm 
						(
							AlarmId,
							AlarmLevelId,
							DateTimeCreated ,
							BoxId ,
							AlarmType ,
							Lat ,
							Long ,
							[Description],
							StreetAddress
						)
						VALUES
						(
							@bigAlarmID ,
							@tiAlarmLevelID,
							@dtOriginDateTime ,
							@intDemoBoxID ,
							@tiBoxMsgInTypeId,
							@dLatitude ,
							@dLongitude ,
							CASE WHEN @tiBoxMsgInTypeId IN (5 , 6) THEN CAST(@bigGeoZoneID AS varchar(600))
								 WHEN @tiBoxMsgInTypeId = 4 THEN CAST (@tiSpeed As Varchar(600))
								 ELSE dbo.rvlf_fn_GetAlarmDetails(@vcCustomProp , @tiBoxMsgInTypeId, @intDemoBoxID,@uiDemoMsgInID, @dtOriginDateTime) END,
							CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END
						)
						END										
					END
			/******************************************************************************/

			/***************************Communication Processing***************************/
					-- Inserts or updates the communication information based on the communication information.
					IF @vcOldIP IS NULL 
					BEGIN
						DECLARE @tiCommAddressTypeID tinyint = NULL
					SELECT @tiCommAddressTypeID = CommAddressTypeID FROM rvlfCommModeAddressType 
							WHERE CommModeId = @tiCommModeId
							IF(@tiCommAddressTypeID IS NULL OR @tiCommAddressTypeID='')
							BEGIN
								SET @tiCommAddressTypeID = 1
							END
						INSERT INTO rvlfBoxCommInfo
						(
							BoxID,
							CommAddressTypeId,
							CommAddressValue
						)
						VALUES
						(
							@intBoxID,
							@tiCommAddressTypeID,
							@vcNewIP
						)						
						
					END
					ELSE
					BEGIN
						IF @vcOldIP <> @vcNewIP
						BEGIN
							UPDATE rvlfBoxCommInfo SET 
								CommAddressTypeId = (SELECT CASE WHEN CommAddressTypeID IS NULL OR CommAddressTypeID=''  THEN 1 ELSE CommAddressTypeID END FROM rvlfCommModeAddressType WHERE CommModeId = @tiCommModeId),
								CommAddressValue = @vcNewIP
							WHERE BoxID = @intBoxID							
							
						END
					END
			/******************************************************************************/			

			/*************************Message out Processing (ACK / Response)**************/
					IF @dtSentDateTime IS NOT NULL
					BEGIN
						UPDATE rvlfMsgOutHst SET Acknowledged = 1, MessageInID= @uiMsgInID WHERE
							BoxId = @intBoxID AND SentDateTime = @dtSentDateTime 

						-- Demo Account Mapping 
						IF(@intDemoBoxID IS NOT NULL)
							BEGIN
							UPDATE rvlfMsgOutHst SET Acknowledged = 1, MessageInID= @uiDemoMsgInID WHERE
								BoxId = @intDemoBoxID AND SentDateTime = @dtSentDateTime 
							END																			
						
						DECLARE @tiCmdTypeID tinyint
						SELECT @tiCmdTypeID = BoxCmdOutTypeId FROM rvlfMsgOutHst 
						WHERE BoxId = @intBoxID AND SentDateTime = @dtSentDateTime 
						DECLARE @bigUserID bigint
						DECLARE @bigVehicleID bigint
						DECLARE @bigGeozoneNo bigint
						
						SELECT @bigVehicleID = VehicleId FROM rvlfVehicleAssignment WHERE
						BoxId=@intBoxID AND IsDeleted <> 1
						
						DECLARE @tiSeverity bigint
						IF @tiCmdTypeID = 11 
						BEGIN
						--select * from rvlfMsgOutHst order by SentDateTime desc
							SELECT @bigUserID= UserId,  @bigGeozoneNo=(
								SELECT g.GeozoneNo FROM rvlfOrganizationGeozone g 
									WHERE g.GeozoneId=CAST(CustomProp AS bigint)
									AND g.OrganizationId=@bigOrganizationID )
							FROM rvlfMsgOutHst WHERE BoxId = @intBoxID AND SentDateTime = @dtSentDateTime
							SELECT @tiSeverity = SeverityId FROM rvlfOrganizationGeozone WHERE
							GeozoneNo = @bigGeozoneNo
							print @tiSeverity
							IF NOT EXISTS ( SELECT GeozoneNo FROM rvlfVehicleGeozone 
								WHERE VehicleId = @bigVehicleID AND GeozoneNo = @bigGeozoneNo)
							BEGIN
								INSERT INTO rvlfVehicleGeozone 
									(VehicleId,SeverityId,GeozoneNo,AssingedBy,AssingedDate)
								VALUES
									(@bigVehicleID, @tiSeverity, @bigGeozoneNo, @bigUserID, @dtSentDateTime)
							END
						END
						
						IF @tiCmdTypeID = 12 
						BEGIN
							DECLARE @vcGeozoneIDs varchar(150)
							SELECT @vcGeozoneIDs = CustomProp  FROM rvlfMsgOutHst 
							WHERE BoxId = @intBoxID AND SentDateTime = @dtSentDateTime
							IF @vcGeozoneIDs ='65535'
							BEGIN
								DELETE FROM rvlfVehicleGeozone WHERE VehicleId= @bigVehicleID 
							END
							ELSE 
							BEGIN
							print @vcGeozoneIDs
								DELETE rvlfVehicleGeozone WHERE VehicleId= @bigVehicleID 
								AND GeozoneNo IN (SELECT GeozoneNo FROM rvlfOrganizationGeozone 
									WHERE OrganizationId = @bigOrganizationID AND GeozoneId IN
										(SELECT *  from dbo.rvlf_fn_ConvertArrayToTable(@vcGeozoneIDs,',')))
							END
						END
					END
					
					IF (@intBoxID = 2)
					BEGIN
						exec rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId
					END
					
					--	Disable SMS for Dhana college when Fuel Drain with Ignition ON
					IF (@bigOrganizationID = 47 and @tiBoxMsgInTypeId = 90 and @bitIgnitionStatus = 1)
						BEGIN
						
							UPDATE rvlfMsgInHst set IsNotificationSent = 1 where MessageInID = @uiMsgInID
							-- exec rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId
						END
						
					IF (@tiValidGps > 0 and @intBoxID <> 2) 
						BEGIN
							exec rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId
						END

					--Log notifications for geozone messages.						
					IF(@tiBoxMsgInTypeId IN(5,6))
						BEGIN						
							 EXEC rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId						 
						END
					
					-- COMMIT TRAN
					IF @tiValidGps > 0
						BEGIN
							exec rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId
						END
						
					IF @IsAddressAlreadyAvailable = 1
						BEGIN
							exec rvlf_sp_UpdateAddress_BgProcess @dlatitude, @dlongitude, @vcStreetAddress, @vcNearestLandmark, 
								@uiMsgInid
						END
					
					COMMIT TRAN			
				END TRY
				BEGIN CATCH
					ROLLBACK TRAN 
					SET @ErrorMessage = 'An Error occured during insert of the packet message : ' + ERROR_MESSAGE()
					RAISERROR( @ErrorMessage,16,1)
				END CATCH								
			END
		END

--UPDATE THE OLD COMMAND ACK IN MSGOUTHST
UPDATE rvlfMsgOutHst SET Acknowledged=0 WHERE Acknowledged IS NULL AND BoxCmdOutTypeId NOT IN(21,22) AND GETUTCDATE()>DATEADD(SECOND,30,SentDateTime)
	
--CHECK THE SCHEDULED OTA COMMAND RETRY
	DECLARE @bigRetryScheduleId bigint=null,@tintAck tinyint=null,@dtOtaTime datetime=null
	SELECT TOP 1 @tintAck=Acknowledged,@dtOtaTime=H.SentDateTime   FROM rvlfMsgOutHst H
			--INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId=H.BoxId  
		WHERE BoxCmdOutTypeId =22 AND h.BoxId =@intBoxID AND Acknowledged IS NOT NULL ORDER BY SentDateTime DESC	
IF (@tintAck NOT IN(2,6) AND @tintAck IS NOT NULL)
	BEGIN
		IF EXISTS(SELECT ScheduleId  FROM rvlfScheduleOfCommandsMaster WHERE Boxid =@intBoxID AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND BoxCmdOutTypeId =22)
			BEGIN
				SELECT @bigRetryScheduleId =ScheduleId  FROM rvlfScheduleOfCommandsMaster WHERE Boxid=@intBoxID 
					AND BoxCmdOutTypeId =22 AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND GETUTCDATE() BETWEEN EffectiveFrom AND EffectiveTo 
				IF @bigRetryScheduleId IS NOT NULL
					BEGIN
						UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=NULL WHERE ScheduleId =@bigRetryScheduleId AND BoxCmdOutTypeId  =22
						IF EXISTS(SELECT ScheduleLogId FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId)
							BEGIN
								UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=NULL,ActualExecutionDate=CASE WHEN @dtOtaTime>CreatedDate AND @dtOtaTime <=EffectiveTo THEN @dtOtaTime ELSE NULL END WHERE ScheduleId =@bigRetryScheduleId AND BoxCmdOutTypeId  =22
								DELETE rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId AND RESPONSEMSG!='Aborted'	
							END
					END				
			END
	END
ELSE IF(@tintAck IS NULL)
	BEGIN
		SELECT @bigRetryScheduleId =ScheduleId  FROM rvlfScheduleOfCommandsMaster WHERE Boxid=@intBoxID 
				AND BoxCmdOutTypeId =22 AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND GETUTCDATE() BETWEEN EffectiveFrom AND EffectiveTo 
		IF(@bigRetryScheduleId IS NOT NULL OR @bigRetryScheduleId!='')
		BEGIN					
		IF NOT EXISTS(SELECT ScheduleLogId FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId)
			BEGIN
				INSERT INTO rvlfSchedulingOfCommandsLog (ScheduleId,ExecutionOn,IsCommandSend,[No.ofTries],ResponseMsg)
					SELECT @bigRetryScheduleId,@dtOtaTime,1,1,'Command sent successfully.'
			END
		END
		
	END

IF (((SELECT TOP 1 BoxId  FROM rvlfMsgInHst WHERE CONVERT(DATE,OriginDateTime)=CONVERT(DATE,GETUTCDATE()) ORDER BY OriginDateTime DESC)=@intBoxID) OR (@tiBoxMsgInTypeId=52))		
BEGIN		
--CHECK IF THE BOXID HAVE ANY SCHEDULES FOR GIVE COMMANDS
IF EXISTS(SELECT ScheduleId  FROM rvlfScheduleOfCommandsMaster SM
	--INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=SM.VehicleId 
	WHERE ScheduleId NOT IN(SELECT ScheduleId  FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE())) 
		AND SM.BoxId =@intBoxID 
		AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))	
		AND (GETUTCDATE()>= EffectiveFrom
		AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE  EffectiveTo END))
		AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE())))
			BEGIN
				DECLARE @TBLSCHEDULES TABLE
				(
					ScheduleId bigint,
					inc bit
				)
			INSERT INTO @TBLSCHEDULES(ScheduleId,inc)
			SELECT DISTINCT SM.ScheduleId,0 FROM rvlfScheduleOfCommandsMaster SM
				--INNER JOIN rvlfVehicleAssignment VA ON VA.VehicleId=SM.VehicleId 
				WHERE ScheduleId NOT IN(SELECT ScheduleId  FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE())) 
					AND SM.BoxId =@intBoxID  
					AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))
					AND (GETUTCDATE()>=EffectiveFrom 
						AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE  EffectiveTo END))
					AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE()))						
				
				WHILE EXISTS(SELECT ScheduleId FROM @TBLSCHEDULES WHERE inc =0)
				BEGIN
					DECLARE @vcType varchar(50)=null,@bigScheduleId bigint=null--,@tiFrequency tinyint=null
					SELECT @bigScheduleId=ScheduleId FROM @TBLSCHEDULES WHERE inc=0
										
					--UPDATE THE LATEST IP AND PORT
					UPDATE rvlfScheduleOfCommandsMaster 
						SET PacketInfo = REPLACE(PacketInfo,SUBSTRING(PacketInfo,CHARINDEX('IP=',PacketInfo,1)+3,(CHARINDEX(';',PacketInfo,CHARINDEX('Port=',PacketInfo,1))-4)),@vcCommInfo1+';Port='+CAST(@siCommInfo2 AS VARCHAR)) 
					WHERE ScheduleId=@bigScheduleId
					--UPDATE rvlfScheduleOfCommandsMaster 
					--	SET PacketInfo = REPLACE(PacketInfo,SUBSTRING(PacketInfo,CHARINDEX('IP=',PacketInfo,0)+3,CHARINDEX(';',PacketInfo,0)-4),@vcCommInfo1) 
					--WHERE ScheduleId=@bigScheduleId
					
					SELECT TOP 1 @vcType=ExecutionOn,@bigScheduleId=ScheduleId FROM rvlfScheduleOfCommandsMaster 
						WHERE ScheduleId=@bigScheduleId 
					
					--CHECK ONLY ONCE EXECUTION TYPE
					--IF(@tiFrequency =0)
					--	BEGIN
					--		--IF NOT EXISTS(SELECT ScheduleLogId FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigScheduleId)
					--		--BEGIN
					--			--IF THE COMMANDS EXECUTION TYPE IS Ignition On	
					--			IF (@vcType ='Ignition On' AND @tiBoxMsgInTypeId=2)
					--				BEGIN
					--					INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn)
					--						VALUES(@bigScheduleId,GETUTCDATE())								
					--				END
					--			ELSE IF(@vcType ='Any message in' AND @tiBoxMsgInTypeId NOT IN(19,52))
					--				BEGIN
					--					INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn)
					--						VALUES(@bigScheduleId,GETUTCDATE())
					--					--select @bigScheduleId
					--				END
					--		--END
					--	END
					--ELSE 
					--	BEGIN
							--IF THE COMMANDS EXECUTION TYPE IS Ignition On	
							IF (@vcType ='Ignition On' AND @tiBoxMsgInTypeId=2)
								BEGIN
									INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn)
										VALUES(@bigScheduleId,GETUTCDATE())								
								END
							ELSE IF(@vcType ='Any message in' AND @tiBoxMsgInTypeId NOT IN(12))
								BEGIN
									INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn)
										VALUES(@bigScheduleId,GETUTCDATE())
									--select @bigScheduleId
								END
						--END
					UPDATE TOP(1) @TBLSCHEDULES SET inc=1 WHERE ScheduleId=@bigScheduleId 
				END
END		
END	
SET NOCOUNT OFF
END	
END	
END





GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateMessageReceived_Test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_UpdateMessageReceived_Test]
  @intBoxID int=null,                                                  
  @dtOriginDateTime datetime,                                                  
  @dtDateTimeReceived datetime,                                                   
  @vcCommMode varchar(100),                                                    
  @tiBoxMsgInTypeId TINYINT = null,                                                    
  @vcBoxProtocolTypeName varchar(50) = null,                                                  
  @vcCommInfo1 varchar(15),           
  @siCommInfo2 int ,           
  @tiValidGps smallint = 2,           
  @dLatitude decimal(10,6) = 0,          
  @dLongitude decimal(10,6) = 0,          
  @tiSpeed smallint = 0,           
  @siHeading  smallint = 0,          
  @vcSensorMask varchar(8) = null,          
  @vcCustomProp varchar(max)= null,          
  @bigSequenceNum bigint = null,          
  @bitIsArmed bit = null,           
  @tiPriority tinyint = null,          
  @bitIsAlarm bit =0,          
  @dtSentDateTime datetime = null,                                                  
  @bitIgnitionStatus bit = null,                                                  
  @bigOdoMeterReading bigint = null,                                          
  @bitIsTrinetraApp bit = 0,                                          
  @ModelNo VARCHAR(256) = null,                                          
  @odoValue_app varchar(6) = null,                                          
  @AlarmDesc_app varchar(256) = null,                                          
  @IsPrefAck bit = 0                                                  
AS                                                  
/*********************************************************************************************************************************/                                                
-- Name  : [rvlf_sp_UpdateMessageReceived]                                                  
-- Description : To insert the messages that is sent to the device                                                
-- Author : V.Narayanasamy                                                
-- Company  : Angler Technologies                                                
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                                
--   : 11-Oct-2011 VN Created Intial Version                                                 
--          : 22-Nov-2011 Ranjith Add Geozone issue (Geozone id assigned instead of Geozone no for VehicleGeozone table)                                                
--          : 27-Jan-2012 Sakthi Casting for add geozone and Geozone id instead of Geozone no for deleting geozone                                                
--          : 11-May-2012 Sakthi Update the odometer and duration column with values                                              
--   : 11-Oct-2012 Sakthi Update reporting interval and speed threshold to master vehicle table                                              
--   : 17-Oct-2012 Set speed is 0 by default for extreme and harsh braking / acceleration                                              
--   : 23-Oct-2013 Sakthi Log the geozone based Trip details                                          
--   : 16-Nov-2013 Sakthi Track the trip details by vehicle wise to other clients                                          
/*********************************************************************************************************************************/                                                
BEGIN                                                
SET NOCOUNT ON                                         
                                  
IF @intBoxID NOT IN (481,482)                                  
BEGIN                                  
 Declare @SMSbasedQueryError int = 0                                            
 IF @tiBoxMsgInTypeId = 114 and (@vcCustomProp like '%SendSMSQuery:1%')                                              
  Begin     
 select @intBoxID = va.BoxId from rvlfVehicleAssignment va                                 inner join rvlfVehicle v on v.VehicleId =va.VehicleId                                              
 where v.VehicleDescription  =                                               
 SUBSTRING(@vcCustomProp, CHARINDEX('VehicleName:',@vcCustomProp,0)+12,(CHARINDEX(';',@vcCustomProp,CHARINDEX('VehicleName:',@vcCustomProp,1))) -(CHARINDEX('VehicleName:',@vcCustomProp,1)+12))                                              
                                             
 DECLARE @CommandId Bigint                         
 DECLARE @MobileNo varchar(20),@VCSmsMsg varchar(max),@VCSmsMsgUserRights varchar(max)                                            
 Declare @SMSAlertMsgs varchar(max)                                            
 Declare @Userid varchar(50),@OrganizationID varchar(50),@UserName varchar(50),@Email varchar(50),@FleetId varchar(50),@FleetName varchar(500)                                             
 Declare @VehicleID varchar(50),@VehicleDescription varchar(50),@VehicleName varchar(50),@LicensePlate varchar(50)                                                         
    SELECT @MobileNo = CAST(REPLACE(SUBSTRING(@vcCustomProp, CHARINDEX('MobileNo:',@vcCustomProp,0)+9,(CHARINDEX(';',@vcCustomProp,CHARINDEX('MobileNo:',@vcCustomProp,1))) -(CHARINDEX('MobileNo:',@vcCustomProp,1)+9)),'+','') AS bigint),                   
    
   @CommandId = SUBSTRING(@vcCustomProp, CHARINDEX('Command:',@vcCustomProp,0)+8,LEN(@vcCustomProp))                                                 
    Select  @OrganizationID=OrganizationId,@UserName=UserName,@Email=Email,@Userid=UserId from rvlfuser where MobileNo = @MobileNo                --set @MobileNo = 9585846164                                                                      
                                          
    set @VCSmsMsgUserRights = dbo.rvlf_fn_GetSMSCommandUserRights(@MobileNo,@intBoxID)                                                   
    if @VCSmsMsgUserRights <> '' and @VCSmsMsgUserRights is not null --and @intBoxID <> ''                                                  
    Begin                                            
  Set @VCSmsMsg = @VCSmsMsgUserRights                                                      
    end                                    
    Else                                    
    Begin                                    
     Set @VCSmsMsg = dbo.rvlf_fn_GetSMSCommand(@CommandId,@vcCustomProp)                                                         
    End                                    
                                                
 if @intBoxID = '' or @VCSmsMsgUserRights <> ''                                      
 Begin                                       
  If @VCSmsMsgUserRights <> '' and @VCSmsMsgUserRights is not null --and @intBoxID <> ''                                                
   Set @SMSAlertMsgs = @VCSmsMsg                                             
  Else IF @CommandId = 255  --and @VCSmsMsgUserRights ='' and @VCSmsMsgUserRights is null                                                
   Set @SMSAlertMsgs = 'Invalid command. Send Tri HELP to know the available commands and inputs.'                                        
  Else IF @CommandId = 254  --and @VCSmsMsgUserRights ='' and @VCSmsMsgUserRights is null                                                
   Set @SMSAlertMsgs = @VCSmsMsg                                      
  Else --if @VCSmsMsgUserRights ='' and @VCSmsMsgUserRights is null                                                
   Set @SMSAlertMsgs = 'Please check the vehicle name and resend the command.'                                      
       
       --_SendSMSTest                              
  insert into rvlfNotificationLog(MessageInID,OriginDateTime,DateTimeReceived,CanSendSMS,IsSMSSent,Userid,OrganizationID,                         
  UserName,Email,MobileNo,StreetAddress,Speed,Boxid,BoxMsgInTypeName,VehicleID,VehicleDescription,       
  VehicleName,Fleetid,Fleetname,LicensePlate,Subjectsufix,MessageDetails,CanSendEmail,SMSScheduleID)        
  values       
  (null,@dtOriginDateTime,@dtOriginDateTime,1,0,@Userid,@OrganizationID,@UserName,@Email,@MobileNo,       
  'N/A',0,000,@tiBoxMsgInTypeId,null,null,null,null,null,null,'Notify',@SMSAlertMsgs,0,0)       
  set @SMSbasedQueryError = 1       
 End       
  End       
if @intBoxID <> 000 -- Validating Boxid for SMS based Query       
Begin       
IF @bitIsTrinetraApp = 1 AND @ModelNo IS NOT NULL                                          
BEGIN       
 --For mobile application       
 DECLARE @MsgInID_App TABLE (uiMsgInID uniqueidentifier)       
 DECLARE @uiMsgInID_App uniqueidentifier       
 DECLARE @orgId int       
 DECLARE @dtLastValidGPSTime_app datetime       
 SELECT @intBoxID = mb.BoxID,@orgId=b.OrganizationId FROM rvlfModelBoxSettings_App mb       
 INNER JOIN rvlfModel_App ap ON ap.ModelId=mb.ModelId       
 INNER JOIN rvlfBoxId b ON b.BoxId=mb.BoxId WHERE ap.ModelCode=@ModelNo       
       
 IF @intBoxID IS NULL                                          
 BEGIN       
  RAISERROR('Given asset details not mapped in the software side', 16,1)                                           
 END       
 ELSE       
 BEGIN       
  --Last valid location update                                          
  IF @tiValidGps =3 BEGIN SELECT @tiValidGps =0,@tiBoxMsgInTypeId=8 END                                          
  --Preference settings ack received                                          
  IF @IsPrefAck = 1 BEGIN UPDATE dbo.rvlfModel_App SET IsChanged= 0 WHERE ModelCode=@ModelNo END                                          
  --If message is alarm, set type                                          
  IF @bitIsAlarm =1 AND @vcCustomProp NOT LIKE '%Param=Preference Changed%' AND @tiValidGps <> 3 BEGIN SET @tiBoxMsgInTypeId = 4 END       
  --If datetime received is lesser than origin datetime                                          
  IF @dtDateTimeReceived < @dtOriginDateTime BEGIN SET @dtDateTimeReceived = DATEADD(SECOND,3,@dtOriginDateTime) END       
  -- Log mobile messages into server                                          
       
  INSERT INTO rvlfMsgInHSt                                                 
  (                                                
   BoxID , OriginDateTime , DateTimeReceived , ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,       
   CommInfo2 , ValidGps , Latitude ,Longitude , Speed , Heading , SensorMask , CustomProp , SequenceNum ,       
   IsArmed , Priority , StreetAddress, NearestLandmark , IsNotificationSent,odometer,IsProcessed,IsArchived       
  )      
  OUTPUT  INSERTED.MessageInID into @MsgInID_App                                                
  VALUES                                                
  (                                                
   @intBoxID , @dtOriginDateTime , @dtDateTimeReceived , 4 ,@tiBoxMsgInTypeId, 1 , @vcCommInfo1 ,                                                 
   @siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed ,-1  , @vcSensorMask , @vcCustomProp , @bigSequenceNum ,      
   @bitIsArmed , @tiPriority ,CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,NULL,0,CAST(@odoValue_app as bigint),      
   CASE WHEN @tiValidGps = 0 THEN 1 ELSE NULL END,0                          
  )                                             
                                            
  SELECT @uiMsgInID_App = uiMsgInID FROM @MsgInID_App                                             
  --For display the current location of mobile devices 
  IF @tiValidGps <> 0        
 BEGIN                                                  
 SELECT @dtLastValidGPSTime_app = ISNULL(max(OriginDateTime), @dtOriginDateTime)                                                 
 FROM rvlfMsgInHst WHERE BoxId = @intBoxID and ValidGps = 0 --and SensorMask IS NOT NULL      
 END                                                  
  DECLARE  @dtLastValidDateTime_app DateTime=(SELECT LastValidDateTime FROM rvlfBoxId WHERE BoxId = @intBoxID)      
        -- Checks if the last information exists for the box, if so updates else inserts                                                         
 IF @dtOriginDateTime >= @dtLastValidDateTime_app                                             
 BEGIN                                              
   UPDATE rvlfBoxId SET BoxArmed = 1,LastValidDateTime = CASE WHEN @tiValidGps = 0 THEN @dtOriginDateTime ELSE LastValidDateTime END,       
   LastLatitude = @dLatitude,LastLongitude = @dLongitude,LastSpeed = @tiSpeed,                            
   LastCommunicatedDateTime = @dtDateTimeReceived,LastSensorMask = @vcSensorMask,OrganizationId = @orgId,       
   LastStatusDateTime = @dtOriginDateTime,LastStreetAddress = CASE WHEN @tiValidGps = 0 THEN NULL ELSE LastStreetAddress END,       
   NearestLandmark = CASE WHEN @tiValidGps = 0 THEN NULL ELSE NearestLandmark END,Heading = @siHeading,MessageInId = @uiMsgInID_App       
   WHERE BoxId = @intBoxID                                             
  END                                          
  --If message is alarm                                          
  IF @bitIsAlarm =1                                           
  BEGIN                                          
   INSERT INTO rvlfAlarm(AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,DriverId)       
   VALUES(3,@dtOriginDateTime,@intBoxID,91,@dLatitude,@dLongitude,@AlarmDesc_app,(CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END), NULL) END                                          
        --Get the preference settings                                          
 SELECT a.ModelId,a.ModelCode,CASE WHEN ISNULL(a.IsChanged,0)=0 THEN '0' ELSE '1' END AS IsChanged FROM dbo.rvlfModel_App a       
 INNER JOIN rvlfModelBoxSettings_App bx ON bx.ModelId=a.ModelId WHERE ModelCode=@ModelNo                                          
  --SELECT ModelId,ModelCode,ISNULL(IsChanged,0) AS IsChanged FROM dbo.rvlfModel_App WHERE ModelCode=@ModelNo       
    END                                            
END                                          
ELSE                                          
BEGIN                                                
IF (@tiBoxMsgInTypeId <> 52)                                                  
 BEGIN--CONDITION 01 START                                                   
  DECLARE @bigOrganizationID bigint=(SELECT OrganizationID FROM rvlfBoxId WHERE BoxId = @intBoxID)                                                
  DECLARE @tintSensor tinyint=CASE WHEN @vcCustomProp LIKE '%SENSOR_NUM=%' THEN CAST(SUBSTRING(@vcCustomProp,CHARINDEX('%SENSOR_NUM=%',@vcCustomProp,0)+12,(CHARINDEX(';',@vcCustomProp,(CHARINDEX('%SENSOR_NUM=%',@vcCustomProp,0)))-(CHARINDEX('%SENSOR_NUM=


%',@vcCustomProp,0)+12)))AS TINYINT) ELSE 0 END       
  --DECLARE @tintBoxgnore tinyint=(SELECT COUNT(igid) FROM rvlfboxignoremsgs WHERE BOXID =@intBoxID AND BOXMSGINTYPEID=@tiBoxMsgInTypeId AND @vcCustomProp LIKE CASE WHEN SENSORNO=0 THEN '%;%' ELSE '%SENSOR_NUM='+CAST(SENSORNO AS VARCHAR)+'%' END) 0       

           
  DECLARE @tintBoxgnore tinyint=(SELECT COUNT(igid) FROM rvlfboxignoremsgs WHERE BOXID =@intBoxID AND                         
  BOXMSGINTYPEID=@tiBoxMsgInTypeId AND SENSORNO=@tintSensor)                                        
  IF(@tintBoxgnore=0)                            
DECLARE @tintOrgIgnore tinyint=(SELECT count(igid) FROM rvlforgignoremsgs WHERE ORGID =@bigOrganizationID        
   AND BOXMSGINTYPEID=@tiBoxMsgInTypeId AND SENSORNO=@tintSensor)                                                
  --CHECK THE IGNORE MESSAGES BASED ON THE RVLFBOXIGNOREMSGS TABLE            
  IF(@tintBoxgnore=0)                                                
  IF(@tintOrgIgnore=0)                                                
  BEGIN                                                
   IF Exists (SELECT MessageInID FROM rvlfMsgInHst WHERE BoxId = @intBoxID  AND BoxMsgInTypeId = @tiBoxMsgInTypeId               
    AND OriginDateTime = @dtOriginDateTime and CustomProp=@vcCustomProp)                                                  
   BEGIN                           
    RAISERROR('Data Integrity Violation', 16,1)                                                  
   END                                                  
   ELSE                                                
   BEGIN--CONDITION 02 START         
     -- Local variables to hold the intermediate results                                                  
DECLARE @ErrorMessage varchar(3000)                                                    
     DECLARE @intBoxProtocolTypeId int       
     DECLARE @tiServiceID tinyint       
     DECLARE @tiCommModeId tinyint       
     DECLARE @MsgInID TABLE ( uiMsgInID uniqueidentifier)       
     DECLARE @uiMsgInID1 uniqueidentifier       
     DECLARE @uiMsgInID uniqueidentifier       
     DECLARE @vcNewIP varchar(25)       
     SET @vcNewIP = @vcCommInfo1 + ':'+ CAST(@siCommInfo2 AS varchar(5))       
     DECLARE @dtLastValidGPSTime datetime       
     DECLARE @bitCreateAlarm bit       
     DECLARE @tiAlarmLevelID tinyint       
     DECLARE @bigGeoZoneID bigint       
     DECLARE @vcAlarmLevelName varchar(30)       
       
    /********** demo*************/                                                
    DECLARE @DemoMsgInID TABLE ( uiDemoMsgInID uniqueidentifier)                                                
    DECLARE @uiDemoMsgInID uniqueidentifier                                                
    DECLARE @vcOldIP varchar(25)                                                 
    SET @vcNewIP = @vcCommInfo1 + ':'+ CAST(@siCommInfo2 AS varchar(5))                                                
    --DECLARE @bitCanNotify bit                                                
    SET @dtLastValidGPSTime = @dtOriginDateTime                                                 
    DECLARE @IsAddressAlreadyAvailable bit = 0                                                
    DECLARE @vcStreetAddress varchar(250)                                                
 DECLARE @vcNearestLandmark varchar(300)                                         
    /*********end *****************/                                                
                                                     
     SET @dtLastValidGPSTime = @dtOriginDateTime                                                   
      --update the origindatetime if origindatetime is greater then current date time                                                   
     IF(@dtOriginDateTime>CONVERT(datetime,CONVERT(varchar(19),SYSUTCDATETIME())))                                                  
       BEGIN                                               
       SET @dtOriginDateTime=CONVERT(datetime,CONVERT(varchar(19),SYSUTCDATETIME()))                                                  
       END                                                  
                                                       
     --update the datetimerecived if datetimerecived is greater then origindatetime                                                   
    IF(@dtOriginDateTime>=@dtDateTimeReceived)                                                  
       BEGIN                              
       SET @dtDateTimeReceived=DATEADD(S,2,@dtOriginDateTime)                  
       END                                                  
                 
    /************* Demo ***************/                        
     --For Defense Demo BoxID mapping                                                
    /*DECLARE @intDemoBoxID int=NULL                                                
    IF(@tiBoxMsgInTypeId NOT IN (SELECT BoxMsgInTypeId FROM rvlfBoxMsgInType where BoxMsgInTypeName like '%fuel%'))      
    BEGIN                                                
    SET @intDemoBoxID =  CASE WHEN @intBoxID = 144 THEN 10001 --Admirals                                                  
         WHEN @intBoxID = 48 THEN 10002 --CUBE       
         WHEN @intBoxID = 253 THEN 10003 --CUBE       
         WHEN @intBoxID = 178 THEN 10004 --DATE       
         WHEN @intBoxID = 187 THEN 10005 --DATE       
         WHEN @intBoxID = 173 THEN 10006 --DATE       
         WHEN @intBoxID = 184 THEN 10007 --DATE       
         WHEN @intBoxID = 74 THEN 10008 --Coffee Planet       
         WHEN @intBoxID = 77 THEN 10009 --Coffee Planet       
       WHEN @intBoxID = 243 THEN 10010 --Coffee Planet       
         WHEN @intBoxID = 108 THEN 10011 --ME Fuji LLC       
         WHEN @intBoxID = 122 THEN 10012 --ME Fuji LLC       
         WHEN @intBoxID = 118 THEN 10013 --ME Fuji LLC       
         WHEN @intBoxID = 250 THEN 10014 --Sanipex       
         WHEN @intBoxID = 249 THEN 10015 --Sanipex       
         WHEN @intBoxID = 53 THEN 10016 --CUBE       
         WHEN @intBoxID = 323 THEN 10017 --CUBE       
         ELSE NULL END       
    END*/       
    /***************end *******************************/                                                
 IF(@tiBoxMsgInTypeId=100 AND CHARINDEX('RF_ID=',@vcCustomProp,0) > 1)                                                  
 BEGIN --RFID Automate Schedule START                                
  SET @vcSensorMask='00000000'                                             
  DECLARE @rfDRIVERID BIGINT=NULL                                                  
  SELECT @rfDRIVERID=DriverId FROM rvlfIButtonMapping                                                   
  WHERE IButtonKey=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RF_ID=',';') AND OrganizationId=@bigOrganizationID       
   -- updated BoxID aganist Driver based on Ibutton punch                                                   
  DECLARE @rfResult varchar(5)                                                  
  DECLARE @dtRFPunchIn DATETIME=NULL,@AssignmentId INT = NULL                          
  SET @rfResult = dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'Punch:',';')                          
  IF @rfDRIVERID IS NOT NULL              
  BEGIN                        
   IF(@rfResult='OUT')                              
   BEGIN                             
    SELECT TOP 1 @AssignmentId=AssignmentId,@dtRFPunchIn=PunchIn FROM rvlfDriverAssignment                           
    WHERE BoxID=@intBoxID AND DriverId=@rfDRIVERID AND PunchOut IS NULL ORDER BY PunchIn DESC                          
    IF(@dtRFPunchIn IS NOT NULL)                                                  
    BEGIN                                            
     UPDATE rvlfDriverAssignment SET PunchIn =@dtRFPunchIn,PunchOut=@dtOriginDateTime                                                    
     WHERE BOXID=@intBoxID AND DriverId=@rfDRIVERID AND AssignmentId=@AssignmentId                            
     AND PunchIn=@dtRFPunchIn                                       
    END                          
   END                          
   ELSE                                                  
   BEGIN                             
		IF EXISTS (SELECT 1 FROM rvlfDriverAssignment WHERE BoxId=@intBoxID AND PunchIn IS NOT NULL AND PunchOut IS NULL AND DriverId=@rfDRIVERID)              
		BEGIN                          
			UPDATE rvlfDriverAssignment SET PunchOut=DATEADD(SECOND,-30,@dtOriginDateTime) WHERE BoxId=@intBoxID AND    
			PunchIn IS NOT NULL AND PunchOut IS NULL AND DriverId=@rfDRIVERID                         
		END                          
    INSERT INTO rvlfDriverAssignment(DriverId,PunchIn,PunchOut,BOXID,AssignmentDate,IsAmtIssued,AssignedDate)       
    VALUES(@rfDRIVERID,@dtOriginDateTime,NULL,@intBoxID,CONVERT(DATE,GETDATE()),0,GETDATE())       
   END                      
  END                                          
 END--RFID Automate Schedules END       
     --update driver key messages                                                  
     IF(@tiBoxMsgInTypeId=76)                                                  
      BEGIN --CONDITION 03 START                                                 
      SET @vcCustomProp=@vcCustomProp+'ignition='+CAST(@bitIgnitionStatus as varchar)+';'                                                   
      SET @vcSensorMask='00000000'     
      DECLARE @DRIVERID BIGINT=NULL                                                  
      SELECT @DRIVERID=DriverId  FROM rvlfIButtonMapping                                                   
       WHERE IButtonKey=CASE WHEN @vcCustomProp LIKE '%Driver ID=%'                         
       THEN CAST(SUBSTRING (@vcCustomProp,CHARINDEX('Driver ID=',@vcCustomProp,1)+10,                                                
         CHARINDEX(';',@vcCustomProp,CHARINDEX('Driver ID=',@vcCustomProp,1)) -                                                 
        (CHARINDEX('Driver ID=',@vcCustomProp,1)+10)) as varchar) ELSE '0' END  AND OrganizationId=@bigOrganizationID       
       
      -- updated BoxID aganist Driver based on Ibutton punch                                                   
      DECLARE @result varchar(5)                                                  
       SET @result = CASE WHEN @vcCustomProp LIKE '%Driver Status=%'                         
       THEN  CAST(SUBSTRING (@vcCustomProp,CHARINDEX('Driver Status=',@vcCustomProp,1)+14,                                                
       CHARINDEX(';',@vcCustomProp,CHARINDEX('Driver Status=',@vcCustomProp,1)) - (CHARINDEX('Driver Status=',@vcCustomProp,1)+14)) as varchar) ELSE 'OUT' END                                                      
  IF(@result='OUT')                                                  
       BEGIN                                                  
        DECLARE @dtPunchin DATETIME=NULL                                                  
        SELECT @dtPunchin=PUNCHINTIME FROM rvlfIButtonMapping WHERE BoxID=@intBoxID AND DriverId=@DRIVERID       
        IF(@dtPunchin IS NOT NULL)                                                  
         BEGIN                                            
          IF EXISTS(SELECT AssignmentId FROM rvlfDriverAssignment WHERE BOXID=@intBoxID AND DriverId=@DRIVERID       
           AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime))       
           AND (@dtPunchin <=ToTime)                          
           AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime)       
           AND PunchIn IS NULL AND PunchOut IS NULL)                                           
           BEGIN                                                   
            UPDATE  rvlfDriverAssignment SET PunchIn =@dtPunchin,PunchOut=@dtOriginDateTime                                                    
             WHERE BOXID=@intBoxID AND DriverId=@DRIVERID                                                   
              AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime)                                                 
          AND CONVERT(DATE,ToTime)) AND (@dtPunchin <=ToTime)                       
              AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime)       
              AND PunchIn IS NULL AND PunchOut IS NULL                        
           END       
    ELSE IF EXISTS(SELECT AssignmentId FROM rvlfDriverAssignment WHERE BOXID=@intBoxID                                                   
            AND DriverId=@DRIVERID AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime)       
            AND CONVERT(DATE,ToTime)) AND (@dtPunchin <=ToTime)                                                   
            AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime)       
            AND PunchIn IS NOT NULL AND PunchOut IS NOT NULL)                                                    
           BEGIN                                                  
            INSERT INTO rvlfDriverAssignment(DriverId,FromTime,ToTime,PunchIn,PunchOut,BOXID,AssignmentDate,IsAmtIssued,AssignedDate)       
             SELECT TOP 1 @DRIVERID,FromTime,ToTime,@dtPunchin,@dtOriginDateTime,@intBoxID,CONVERT(DATE,GETDATE()),0,GETDATE()       
              FROM rvlfDriverAssignment              
              WHERE BOXID=@intBoxID AND DriverId=@DRIVERID                                                   
               AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime))       
               AND (@dtPunchin <=ToTime)                                                   
               AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime)       
               AND PunchIn IS NOT NULL AND PunchOut IS NOT NULL                                                  
    END       
          ELSE                                                  
           BEGIN                       
            INSERT INTO rvlfDriverAssignment(DriverId,PunchIn,PunchOut,BOXID,AssignmentDate,IsAmtIssued,AssignedDate)       
             VALUES(@DRIVERID,@dtPunchin,@dtOriginDateTime,@intBoxID,CONVERT(DATE,GETDATE()),0,GETDATE())       
           END       
         END       
       END       
       
      UPDATE RVLFIButtonMapping SET Boxid = CASE WHEN @result = 'IN' THEN @intBoxID ELSE 0 END,                        
      PunchInTime=CASE WHEN @result = 'IN' THEN @dtOriginDateTime ELSE NULL END WHERE DriverId = @DRIVERID                                          
         IF(@DRIVERID IS NOT NULL)                                                  
       BEGIN                                                  
        SET @vcCustomProp=@vcCustomProp+'MAPID='+CAST(@DRIVERID as varchar)                                    
       END                                                  
         ELSE                                                  
       BEGIN                                                  
        SET @vcCustomProp=@vcCustomProp+'MAPID=0'                                                  
       END                                                  
       END--CONDITION 03 END                                         
       
     --GET THE PROTOCOLID BASED ON THE PROTOCOL NAME                               
     SELECT @intBoxProtocolTypeId = BoxProtocolTypeId FROM rvlfBoxProtocolType WHERE BoxProtocolTypeName = @vcBoxProtocolTypeName      
                                                        
        --GET THE COMMAND MODE ID BASED ON THE COMMANDMODE NAME                                                  
     SELECT @tiCommModeId = CommModeId FROM rvlfCommMode WHERE CommModeName = @vcCommMode                                                  
                                                      
        --GET THE PROTOCOLID BASED ON THE PROTOCOL NAME                                                   
     SELECT @tiServiceID = ServiceID FROM rvlfServices WHERE CommModeId = @tiCommModeId      
                                                    
    /***************************Severity Settings**********************************/                    
    -- Checks if the message has the severity settings such that an alarm has to be created.                                               
    IF EXISTS (SELECT BoxId FROM rvlfBoxMsgSeverity WHERE BoxId=@intBoxID AND BoxMsgInTypeId = @tiBoxMsgInTypeID)             
     BEGIN                                                  
        DECLARE @intDuration int = 1                                                   
        IF @tiBoxMsgInTypeId = 9                                                   
         BEGIN                               
        SET @intDuration = CAST (SUBSTRING (@vcCustomProp, CHARINDEX(':',@vcCustomProp,1)+1,                                          
         CHARINDEX(';',@vcCustomProp)-1 -CHARINDEX(':',@vcCustomProp,1)) as Int)                                                  
         END                                                  
        IF @intDuration > 0                                                  
       BEGIN                                                  
        SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.AlarmLevelID, @vcAlarmLevelName = s.AlarmLevelName      
        FROM rvlfBoxMsgSeverity bs                  
          INNER JOIN rvlfSeverity s On bs.AlarmLevelID = s.AlarmLevelId                                                 
         WHERE bs.BoxId = @intBoxID AND bs.BoxMsgInTypeId = @tiBoxMsgInTypeID                                                   
          END                                                  
     END                                                  
     ELSE                                                  
     BEGIN                                                  
      SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.DefaultAlarmLevel,@vcAlarmLevelName = s.AlarmLevelName      
       FROM rvlfBoxProtocolMsgInType bs                                                 
        INNER JOIN rvlfSeverity s On bs.DefaultAlarmLevel = s.AlarmLevelId                                                 
       WHERE bs.BoxMsgInTypeId = @tiBoxMsgInTypeID                                                   
     END                                                
                   
    IF @tiBoxMsgInTypeId =5 OR @tiBoxMsgInTypeId =6                                                  
      BEGIN                                                  
        SET @bigGeoZoneID =CAST( SUBSTRING(@vcCustomProp,CHARINDEX('=',@vcCustomProp,1)+1,                                                
       (CHARINDEX(';',@vcCustomProp,1)- CHARINDEX('=',@vcCustomProp,1))-1) as bigint)                            
       SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = s.AlarmLevelId,                                                 
      @vcAlarmLevelName = s.AlarmLevelName                                                  
       FROM rvlfOrganizationGeozone g                                                 
         INNER JOIN rvlfSeverity s ON g.SeverityId  = s.AlarmLevelId                                                  
       WHERE g.OrganizationId = @bigOrganizationID AND g.GeozoneId = @bigGeoZoneID                                                           
      END                                                  
       IF @tiBoxMsgInTypeId = 11                                                  
     BEGIN                                                  
       DECLARE @tiSensorID tinyint,@intSensorStateStart int,@intSensorStateEnd int,                                                
      @vcSensorStatus varchar(10),@bitIsOn bit                                                
       SET @tiSensorID = CAST(SUBSTRING(@vcCustomProp,CHARINDEX('=',@vcCustomProp)+1,1) As tinyint)      
       SET @intSensorStateStart = CHARINDEX('=',@vcCustomProp,LEN('SENSOR_NUM=')+1)                               
       SET @intSensorStateEnd = CHARINDEX(';',@vcCustomProp,15)                             
       SET @vcSensorStatus =                   
      CASE WHEN @vcCustomProp LIKE '%SENSOR_STATUS=%' THEN SUBSTRING(@vcCustomProp,CHARINDEX('SENSOR_STATUS=',@vcCustomProp,0)+14,      
       (CHARINDEX(';',@vcCustomProp,(CHARINDEX('SENSOR_STATUS=',@vcCustomProp,0)))-(CHARINDEX('SENSOR_STATUS=',@vcCustomProp,0)+14)))      
      ELSE SUBSTRING(@vcCustomProp,@intSensorStateStart+1, @intSensorStateEnd - @intSensorStateStart-1)END      
       SET @bitIsOn = CASE WHEN @vcSensorStatus = 'OPEN' OR @vcSensorStatus = 'ON'                              
      OR @vcSensorStatus = 'NORMAL' OR @vcSensorStatus = 'OK' THEN 1                                                  
        WHEN @vcSensorStatus = 'CLOSE' OR @vcSensorStatus = 'OFF' OR @vcSensorStatus = 'LOW' THEN 0      
        END                                                  
                                                       
       IF EXISTS (SELECT BoxId FROM rvlfBoxSensorsCfg WHERE BoxId = @intBoxID AND SensorId = @tiSensorID)      
        BEGIN                                                  
         SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = s.AlarmLevelId, @vcAlarmLevelName = s.AlarmLevelName      
        FROM rvlfBoxSensorsCfg bs INNER JOIN rvlfSeverity s ON s.AlarmLevelId =                                                 
         (CASE WHEN @bitIsOn=1 THEN bs.AlarmLevelOn ELSE AlarmLevelOff END)                                                  
         WHERE bs.BoxId = @intBoxID AND bs.SensorId = @tiSensorID                                                   
        END                                                  
       ELSE                                                  
       BEGIN                                                  
       SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.DefaultAlarmLevel,                                                 
        @vcAlarmLevelName = s.AlarmLevelName                                                  
       FROM rvlfBoxProtocolMsgInType bs                                                 
         INNER JOIN rvlfSeverity s On bs.DefaultAlarmLevel = s.AlarmLevelId                                                 
        WHERE bs.BoxMsgInTypeId = @tiBoxMsgInTypeID                                                   
       END                                                             
      END             
                                                           
    IF @tiBoxMsgInTypeId = 27                                                   
     BEGIN                                                  
      SET @bitCreateAlarm = 1                                                  
     END                                                                 
                                                          
    IF @tiBoxMsgInTypeId IN (14,15,16,17)                                              
     BEGIN                                                  
      SET @tiSpeed = 0                                              
     END                                 
                                                         
 DECLARE @trancount int;                                          
 SET @trancount = @@trancount;                                          
 --PRINT CAST(@trancount as varchar)                                          
    BEGIN TRY                                          
 IF @trancount = 0                                          
  BEGIN TRANSACTION;                                          
 ELSE                                          
  SAVE TRANSACTION MessageTransaction;                                          
                  
     /***********************Message In History*************************************/                                     
     --BEGIN TRAN MessageTransaction                                          
     --BEGIN TRY                                          
     --PRINT 'Welcome 1'                       
     IF @vcCustomProp not like '%ImgData:1%'  -- CHARINDEX('ImgData:', @vcCustomProp) = 0                                          
   begin                                          
  PRINT 'Message Table'                                   
-- To insert the information in the message in history table                                                  
     INSERT INTO rvlfMsgInHSt                                                   
      (                                              
       BoxID , OriginDateTime , DateTimeReceived ,                                                   
       ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,                                                  
       CommInfo2 , ValidGps , Latitude ,Longitude , Speed ,                                                   
       Heading , SensorMask , CustomProp , SequenceNum ,                                                  
       IsArmed , Priority , StreetAddress,IsNotificationSent,IsProcessed,IsArchived                          
      )                                                  
     OUTPUT  INSERTED.MessageInID into @MsgInID                                                  
      VALUES                                                  
      (                         
       @intBoxID , @dtOriginDateTime , @dtDateTimeReceived ,                               
       @tiServiceID ,@tiBoxMsgInTypeId, @intBoxProtocolTypeId , @vcCommInfo1 ,                                 
       @siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed ,                            
       @siHeading  , @vcSensorMask , @vcCustomProp , @bigSequenceNum ,                                                   
       @bitIsArmed , @tiPriority ,                                                   
       CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,0,CASE WHEN @tiValidGps = 0 THEN 1 ELSE NULL END,0      
      )                                                  
      End                                          
                                                
       IF @tiBoxMsgInTypeId = 114 and @vcCustomProp like '%ImgData:1%'                                          
       BEGIN                                           
      DECLARE @ImageID int       
         DECLARE @CurrentPacket tinyint                                          
         SELECT @ImageID = SUBSTRING(@vcCustomProp, CHARINDEX('Image ID:',@vcCustomProp,0)+9,                        
         (CHARINDEX(';',@vcCustomProp,CHARINDEX('Image ID:',@vcCustomProp,1))) -(CHARINDEX('Image ID:',@vcCustomProp,1)+9)),      
         @CurrentPacket=SUBSTRING(@vcCustomProp, CHARINDEX('Current Packet:',@vcCustomProp,0)+15,                        
         (CHARINDEX(';',@vcCustomProp,CHARINDEX('Current Packet:',@vcCustomProp,1))) -(CHARINDEX('Current Packet:',@vcCustomProp,1)+15))      
         IF NOT EXISTS (SELECT 1 FROM rvlfCameraImages WHERE BoxId=@intBoxID AND ImageID=@ImageID AND CurrentPacket=@CurrentPacket      
         and CONVERT(date,ReceivedDate) = CONVERT(date,GETUTCDATE()))                                          
         BEGIN                                          
         INSERT INTO rvlfCameraImages                                          
         (ReceivedDate,ImageID,BoxID,ImageData,ImageLength,CurrentPacket,TotalPackets)                                          
         VALUES      
        ( @dtOriginDateTime, @ImageID,@intBoxID,      
         --SUBSTRING(@vcCustomProp, CHARINDEX('Image ID:', @vcCustomProp)+9,1),                                          
 SUBSTRING(@vcCustomProp, CHARINDEX('Image Data:', @vcCustomProp)+11,LEN(@vcCustomProp)),            
         SUBSTRING(@vcCustomProp, CHARINDEX('Image Length:',@vcCustomProp,0)+13,                        
         (CHARINDEX(';',@vcCustomProp,CHARINDEX('Image Length:',@vcCustomProp,1))) -(CHARINDEX('Image Length:',@vcCustomProp,1)+13)),      
         @CurrentPacket,SUBSTRING(@vcCustomProp, CHARINDEX('Total Packets:',@vcCustomProp,0)+14,             
       
         (CHARINDEX(';',@vcCustomProp,CHARINDEX('Total Packets:',@vcCustomProp,1))) -(CHARINDEX('Total Packets:',@vcCustomProp,1)+14))      
         --SUBSTRING(@vcCustomProp, CHARINDEX('Current Packet:', @vcCustomProp)+15,1),                                          
      --SUBSTRING(@vcCustomProp, CHARINDEX('Total Packets:', @vcCustomProp)+14,1)                                          
      )                                          
      END                                       
    END                                           
                        
     IF @tiBoxMsgInTypeId = 114 and (@vcCustomProp like '%SendSMSQuery:1%') and @SMSbasedQueryError = 0                                          
    Begin                                              
  --DECLARE @CommandId Bigint                                  
  --DECLARE @MobileNo varchar(20)                                                
  --Declare @Userid varchar(50),@OrganizationID varchar(50),@UserName varchar(50),@Email varchar(50),@FleetId varchar(50),@FleetName varchar(500)                                             
    --Declare @VehicleID varchar(50),@VehicleDescription varchar(50),@VehicleName varchar(50),@LicensePlate varchar(50)                                --SELECT @MobileNo = CAST(SUBSTRING(@vcCustomProp, CHARINDEX('MobileNo:',@vcCustomProp,0)+9,(CHARINDEX(







  
    
--';',@vcCustomProp,CHARINDEX('MobileNo:',@vcCustomProp,1))) -(CHARINDEX('MobileNo:',@vcCustomProp,1)+9)) AS bigint),                                 
  --       @CommandId = SUBSTRING(@vcCustomProp, CHARINDEX('Command:',@vcCustomProp,0)+8,LEN(@vcCustomProp))                                  --         set @MobileNo = 9894959948                                            
                                                
         Declare @VCCusProp varchar(max),@intBoxmsgintypeid int,@unMsginID varchar(max),@dtOrgDatetime datetime,@intSpeed bigint,      
         @varStreetAddress varchar(max),@varBoxmsginTypeName varchar(max),                                              
     @VarSensorStatus varchar(10), @VCCommandParam varchar(max), @VCCommand varchar(max),@intScheduleid int,      
     @dtCmdCreateddate datetime,@dtcmdEnddate datetime                                              
      
      set @VCSmsMsgUserRights = dbo.rvlf_fn_GetSMSCommandUserRights(@MobileNo,@intBoxID)                                          
      select @intScheduleid = IDENT_CURRENT('rvlfScheduleOfCommandsMaster') + 1                                    
      if @VCSmsMsgUserRights <> ''  and  @VCSmsMsgUserRights is not null                                                
      Begin                                            
      Set @VCSmsMsg = @VCSmsMsgUserRights                                            
      set @intScheduleid = null                                            
      end                                                            
                                        
    if @CommandId not in (254,255)                                              
    Begin                                              
      select @VehicleID =v.VehicleId,@VehicleDescription=v.VehicleDescription,@VehicleName=v.VehicleDescription,@LicensePlate=v.LicensePlate, @OrganizationID=v.OrganizationId,@FleetId=fv.FleetId,@FleetName=f.fleetname from rvlfVehicle v                   





  
   
       
    inner join rvlfvehicleassignment va on va.VehicleId=v.VehicleId                                          
    inner join rvlfFleetVehicles fv on fv.VehicleId = v.VehicleId                        
    inner join rvlffleet f on f.fleetid = fv.fleetid                                           
    where va.boxid = @intBoxID              
    End                                              
    SELECT @uiMsgInID1 = uiMsgInID FROM @MsgInID                                                   
    Set @dtCmdCreateddate =getutcdate()                                           
    Set @dtcmdEnddate = dateadd(dd,1,getutcdate())                                            
    Set @VCCommandParam = dbo.rvlf_fn_GetSMSCommandFrame(@intBoxID,@vcCustomProp)                                              
                                               
    if @CommandId = 1                                                 
     Begin  Set @VCCommand = '?' End                                               
    else if @CommandId =2                  
     Begin Set @VCCommand = 'R' End                                              
    else if @CommandId =3                                              
     Begin  Set @VCCommand = 'S' End                                                    
                                              
   --insert into rvlfSMSInHst(BoxId,Customprop,MessageInId,MobileNo,OriginDateTime,s) values(@intBoxID,@vcCustomProp,@unMsginID,@MobileNo,@dtOriginDateTime)                                              
    if @CommandId not in (254,255) and @SMSbasedQueryError = 0                                          
    Begin                                            
       Exec [rvlf_sp_SaveAndUpdateAndDeleteSchedulingOfCommands] 0,0,@VCCommand,@VCCommandParam,@dtCmdCreateddate,@dtcmdEnddate,0,3,@Userid,@OrganizationID,@VehicleID,'any message in',@FleetId,@intBoxID                                                   











    end                                               
    else if @VCSmsMsg like '%Invalid%' and @SMSbasedQueryError = 0                                    
    Begin                                           
        set @intScheduleid  = null                                      
    End                                      
 --_SendSMSTest                                          
    insert into rvlfNotificationLog(MessageInID,OriginDateTime,DateTimeReceived,CanSendSMS,IsSMSSent,Userid,OrganizationID,      
    UserName,Email,MobileNo,StreetAddress,Speed,Boxid,BoxMsgInTypeName,VehicleID,VehicleDescription,      
    VehicleName,Fleetid,Fleetname,LicensePlate,Subjectsufix,MessageDetails,CanSendEmail,SMSScheduleID)      
    values                                                
    (@uiMsgInID1,@dtOriginDateTime,@dtOriginDateTime,1,0,@Userid,@bigOrganizationID,@UserName,@Email,@MobileNo,      
    null,0,@intBoxID,@tiBoxMsgInTypeId,@VehicleID,@VehicleDescription,@VehicleName,@FleetId,@FleetName,@LicensePlate,'Notify',      
  @VCSmsMsg,0,@intScheduleid)                                          
 End                                            
                      
 SELECT @uiMsgInID = uiMsgInID FROM @MsgInID                                     
                                                   
 --Data Movement for Global Scan Technologies---                                
 IF EXISTS(SELECT TOP 1 BoxId FROM rvlfBoxID WHERE BoxId=@intBoxID AND OrganizationId=242) AND                                
 @tiBoxMsgInTypeId IN (1,2,3,4,9,24,41,12,14,15,16,17)                                
 BEGIN TRY                                
  INSERT INTO dbo.GlobalScan1(Unit_Id,Latitude,Latitude_Dir,Longitude,Longitude_Dir,UTC_Time,Speed,COG,Vt_date,                                
  Vech_dist,Panic_Info,DubaiDateTime,currentdatetime,MessageId,IsProcessed)                                
  VALUES(@intBoxID,CAST(@dLatitude AS FLOAT),(CASE WHEN SUBSTRING(CAST(@dLatitude AS VARCHAR),1,1)='-'THEN 'SOUTH' ELSE 'NORTH' END),      
  CAST(@dLongitude AS FLOAT),(CASE WHEN SUBSTRING(CAST(@dLongitude AS VARCHAR),1,1)='-'THEN 'WEST' ELSE 'EAST' END),GETUTCDATE(),@tiSpeed,      
  @siHeading,@dtOriginDateTime,                                
  (CASE WHEN @vcCustomProp LIKE '%Odometer=%' THEN         
  CAST(SUBSTRING (@vcCustomProp,CHARINDEX('Odometer=',@vcCustomProp,1)+9,                        
  CHARINDEX(';',@vcCustomProp,CHARINDEX('Odometer=',@vcCustomProp,1)) -  
  (CHARINDEX('Odometer=',@vcCustomProp,1)+9)) as bigint) ELSE 0 END),                                
  dbo.[rvlf_fn_GetAlarmDetails_New](@vcCustomProp,@tiBoxMsgInTypeId,@intBoxID,NULL,NULL,NULL),DATEADD(HOUR,4,@dtOriginDateTime),      
  @dtDateTimeReceived,@uiMsgInID,1)                                
 END TRY                                
 BEGIN CATCH                                
  PRINT 'END Global Scan'                                
 END CATCH                                
 ---End--------------------------------------                                                   
                               
     ---------To update the duration from the custome prop to the Duration column------                                                  
 UPDATE rvlfMsgInHst SET duration = (                                                  
 CASE WHEN BoxMsgInTypeId = 3 AND customprop LIKE'%SENSOR_STATUS=OFF%' THEN SUBSTRING(SUBSTRING(customprop,CHARINDEX('SENSOR_DURATION=',customprop)+16,5),0,CHARINDEX(';',SUBSTRING(customprop,CHARINDEX('SENSOR_DURATION=',customprop)+16,5)))               









   
    
      
 WHEN BoxMsgInTypeId = 9 THEN SUBSTRING(customprop,8,CHARINDEX(';',customprop)-8)                                                   
 ELSE NULL END), odometer =  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      
 WHERE MessageInID = @uiMsgInID                                             
 --PRINT 'Welcome 2'                                         
 --------------------------------------------------------------------------------------                                              
                 
     /****************demo *****************/                                                
        -- Demo Entry Insertion                                                
     /*IF(@intDemoBoxID IS NOT NULL)                                                
     BEGIN                                                
      INSERT INTO rvlfMsgInHSt                                                 
      (                                  
       BoxID , OriginDateTime , DateTimeReceived ,                                                 
       ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,                                                
       CommInfo2 , ValidGps , Latitude ,Longitude , Speed ,                                                 
       Heading , SensorMask , CustomProp , SequenceNum ,                                                
 IsArmed , Priority , StreetAddress, NearestLandmark , IsNotificationSent        
      )                                       
       OUTPUT  INSERTED.MessageInID into @demoMsgInID                                                
      VALUES                                                
      (                                                
       @intDemoBoxID , @dtOriginDateTime , @dtDateTimeReceived ,                                                 
       @tiServiceID ,@tiBoxMsgInTypeId, @intBoxProtocolTypeId , @vcCommInfo1 ,                                                 
       @siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed ,                
       @siHeading  , @vcSensorMask , @vcCustomProp , @bigSequenceNum ,                                                 
   @bitIsArmed , @tiPriority ,                                                 
       CASE WHEN @tiValidGps = 0 THEN                                                 
         CASE WHEN @IsAddressAlreadyAvailable = 1 AND @vcStreetAddress!='N/A' THEN @vcStreetAddress ELSE NULL END                 
         ELSE 'N/A' END,                                                
       CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,0                                                
       --CASE WHEN @tiValidGps > 0 THEN 0 ELSE 0 END                    
      )                                                
      SELECT @uiDemoMsgInID = uidemoMsgInID FROM @demoMsgInID                                                
     END*/                                                
     /*************end ***************************/                                                
                     PRINT 'BoxId Table'                                   
     /******************************************************************************/                                                   
     /****************************Box ID Table**************************************/                                
     -- Inserts into the rvlfBoxID if sensor mask is available in the information.                                                  
     IF @vcSensorMask IS NOT NULL AND LEN(@vcSensorMask) = 8 AND @tiBoxMsgInTypeId NOT IN (51,121) AND @tiValidGps <>2                                                  
      BEGIN                                                  
       IF @tiValidGps <> 0                                                   
         BEGIN                                                  
           SELECT @dtLastValidGPSTime = ISNULL(max(OriginDateTime), @dtOriginDateTime)                                                 
           FROM rvlfMsgInHst WHERE BoxId = @intBoxID and ValidGps = 0 --and SensorMask IS NOT NULL      
         END                                                  
       DECLARE  @dtLastValidDateTime DateTime=(SELECT LastValidDateTime FROM rvlfBoxId WHERE BoxId = @intBoxID)      
       -- Checks if the last information exists for the box, if so updates else inserts                                                         
          IF @dtOriginDateTime >= @dtLastValidDateTime                                                
  BEGIN     
         UPDATE rvlfBoxId SET BoxArmed = @bitIsArmed,LastValidDateTime = CASE WHEN @tiValidGps = 0 THEN @dtOriginDateTime ELSE LastValidDateTime END,                                                  
          LastLatitude = CASE WHEN @tiValidGps = 0 THEN @dLatitude ELSE LastLatitude END,                                                  
          LastLongitude = CASE WHEN @tiValidGps = 0 THEN @dLongitude ELSE LastLongitude END,LastSpeed = @tiSpeed,      
          LastCommunicatedDateTime = @dtDateTimeReceived,LastSensorMask = @vcSensorMask,OrganizationId = @bigOrganizationID,      
          LastStatusDateTime = @dtOriginDateTime,LastStreetAddress = CASE WHEN @tiValidGps = 0 THEN NULL ELSE LastStreetAddress END,      
          NearestLandmark = CASE WHEN @tiValidGps = 0 THEN NULL ELSE NearestLandmark END,Heading = @siHeading,MessageInId = @uiMsgInID      
   WHERE BoxId = @intBoxID                                                                          

          END                     
          /************** demo ***************/                                                
          -- Demo Account Mapping                                                
        /*IF(@intDemoBoxID IS NOT NULL)                                                
        BEGIN                                                        
         UPDATE rvlfBoxId SET                            
         BoxArmed = @bitIsArmed,                                                
         LastValidDateTime = CASE WHEN @tiValidGps = 0 THEN @dtOriginDateTime ELSE LastValidDateTime END,                                                
         LastLatitude = CASE WHEN @tiValidGps = 0 THEN @dLatitude                            
          ELSE LastLatitude END,                                                
         LastLongitude = CASE WHEN @tiValidGps = 0 THEN @dLongitude                                                 
          ELSE LastLongitude END ,                                                 
         LastSpeed = @tiSpeed,                                                
         LastCommunicatedDateTime = @dtDateTimeReceived,                                                
         LastSensorMask = @vcSensorMask,                                            
         OrganizationId = 55,                                                
         LastStatusDateTime = @dtOriginDateTime,                                                
         LastStreetAddress = CASE WHEN @tiValidGps = 0 THEN NULL                                                 
     ELSE LastStreetAddress END,                    
      NearestLandmark = CASE WHEN @tiValidGps = 0 THEN NULL                                                 
          ELSE NearestLandmark END,                                                
         Heading = @siHeading,                                                
         MessageInId = @uiDemoMsgInID                                                
        WHERE BoxId = @intDemoBoxID                                                        
        END */                                                
        /*******************end *******************/                                                
       ELSE IF(@dtLastValidDateTime IS NULL OR @dtLastValidDateTime='')                                                 
        BEGIN                                                  
         DELETE FROM rvlfBoxId WHERE BoxId=@intBoxID                                                 
         INSERT INTO rvlfBoxId                                                   
         (                                                   
          BoxId, BoxArmed, LastValidDateTime, LastLatitude, LastLongitude,                                                   
          LastSpeed, LastCommunicatedDateTime, LastSensorMask,                    
          OrganizationId, LastStatusDateTime, Heading , LastStreetAddress ,                                                  
          NearestLandmark, MessageInId                                                  
         )                                                  
         VALUES                                 
         (                                                  
          @intBoxID, @bitIsArmed, @dtLastValidGPSTime, @dLatitude, @dLongitude,                                                  
          @tiSpeed, @dtDateTimeReceived, @vcSensorMask,                                                   
          @bigOrganizationID, @dtOriginDateTime, @siHeading,                                                   
          CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,                                                  
          CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,                                                  
          @uiMsgInID                                                  
         )                                                  
         /*********** demo **************/                                                
         --Demo Acoount Mapping                                                
   /*IF(@intDemoBoxID IS NOT NULL)                                                
         BEGIN                                                
          INSERT INTO rvlfBoxId                                                 
          (                                   
          BoxId, BoxArmed, LastValidDateTime, LastLatitude, LastLongitude,                                                 
          LastSpeed, LastCommunicatedDateTime, LastSensorMask,                                                 
  OrganizationId, LastStatusDateTime, Heading , LastStreetAddress ,                                                
          NearestLandmark, MessageInId                                                
          )                                                
         VALUES                                                
          (                                                
          @intDemoBoxID, @bitIsArmed, @dtLastValidGPSTime, @dLatitude, @dLongitude,                                                
          @tiSpeed, @dtDateTimeReceived, @vcSensorMask,                                                 
          55, @dtOriginDateTime, @siHeading,                                                 
          CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,                                                
          CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,                                                
          @uiDemoMsgInID                                                          )                                                
         END */                                                
         /*********end ************/                                 
        END                   
      END                                             
                PRINT 'Alarm Table'                                   
     /******************************************************************************/                                                       
     /*************************Alarm Processing*************************************/                                                  
     -- Inserts to Alarm table, if it is an alarm.                                                  
     IF @bitIsAlarm = 1 Or @bitCreateAlarm = 1                                
      BEGIN                                                  
       DECLARE @siAlarmLevelID smallint,@bigDriverID bigint = NULL                                                          
       DECLARE @bigAlarmID bigint      
       SELECT @bigDriverID = DriverId FROM RVLFIButtonMapping WHERE BoxID = @intBoxID      
      
       IF(@bigDriverID IS NULL OR @bigDriverID='')                                                  
        BEGIN                                                  
           SELECT @bigDriverID = DriverId FROM rvlfDriverAssignment WHERE BoxID = @intBoxID                                                  
           AND @dtOriginDateTime BETWEEN FromTime AND ToTime                                                   
           AND CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime)     
		  
		   if(@bigDriverID IS NULL OR @bigDriverID='')		    --Included for rfid based driver 21-apr-2016 gopal for cotton blossom
		   begin
			select  top 1 @bigDriverID=DriverId FROM rvlfDriverAssignment WHERE BoxID = @intBoxID order by assignmentid desc
			end
        END                                                  
              --PRINT 'Welcome 3'                                          
       IF(@tiAlarmLevelID is null OR @tiAlarmLevelID='')                                                
        BEGIN                                                
         SET @tiAlarmLevelID = 4 -- hardcoded to avoid AlarmLeveleID issue                                                
        END                                                  
        PRINT 'Alarm 1 Table'                                  
        PRINT @tiAlarmLevelID
		PRINT @dtOriginDateTime
		PRINT @intBoxID
		PRINT @tiBoxMsgInTypeId
		PRINT @dLatitude
		PRINT @dLongitude
		PRINT @vcCustomProp
		PRINT @tiBoxMsgInTypeId
		PRINT @intBoxID
		PRINT @uiMsgInID
		PRINT @dtOriginDateTime
		PRINT dbo.rvlf_fn_GetAlarmDetails(@vcCustomProp, @tiBoxMsgInTypeId, @intBoxID, @uiMsgInID, @dtOriginDateTime)
        PRINT 'Alarm 1 INP'
                                         
        INSERT	INTO rvlfAlarm(AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,DriverId,CustomProp)
				VALUES (@tiAlarmLevelID,@dtOriginDateTime,@intBoxID,@tiBoxMsgInTypeId,@dLatitude,@dLongitude,
						CASE WHEN @tiBoxMsgInTypeId IN (5 , 6) THEN CAST(@bigGeoZoneID AS varchar(600))
							 WHEN @tiBoxMsgInTypeId = 4 THEN CAST (@tiSpeed As Varchar(600))
							 ELSE dbo.rvlf_fn_GetAlarmDetails(@vcCustomProp, @tiBoxMsgInTypeId, @intBoxID, @uiMsgInID, @dtOriginDateTime) END,
						CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END, @bigDriverID,@vcCustomProp)
        PRINT 'Alarm 1 END'
 --Student sms Trigger for alarm for unassigned geozone/vehicle 12-feb-2015 commented for LKD org temporarily      
 IF(@tiBoxMsgInTypeId=100 and charindex('Punch:101',@vcCustomProp,1)>0 or charindex('Punch:110',@vcCustomProp,1)>0)      
 Begin                                            
 print 'Student alarm'                                            
 Declare @punch varchar(30)= dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'Punch:',';')                                            
 Insert into rvlfRFIDSchoolSMSNotification(StudentID,VehicleID,BoxID,GeozoneID,OrganizationId ,EntryExitTime ,RFID ,StudentName,ContactNo ,   MessageTemplate,MsgType, IsSMSSent)                                            
 select S.StudentMasterID,va.VehicleID,@intBoxID,S.GeozoneId,S.OrganizationID,@dtOriginDateTime,S.RFID,S.StudentFirstName + +      
 S.StudentLastName,S.ContactNo ,                                            
 CASE WHEN @punch ='101' THEN ('Name : '+ S.StudentFirstName + + S.StudentLastName + '\n Info: Boarded / Get down incorrect Location at : '+ CAST((dbo.rvlf_fn_DayLightSavings_Date(@dtOriginDateTime,O.OrganizationID,TZ.HoursToBeAdded,                     






 
 
    
      
 TZ.MinToBeAdded,@dtOriginDateTime))                                               
 as varchar(20))) +'-Trinetra'                                             
 WHEN @punch ='110' THEN ('Name : '+ S.StudentFirstName + + S.StudentLastName + '\n Info: Boarded / Get down from incorrect vehicle at : '+      
 CAST((dbo.rvlf_fn_DayLightSavings_Date(@dtOriginDateTime,O.OrganizationID,TZ.HoursToBeAdded,TZ.MinToBeAdded,@dtOriginDateTime))      
 as varchar(20)))+'-Trinetra' end as MessageType,4,0                                            
 from rvlfStudentMaster S                                             
 inner join rvlfVehicle v on s.OrganizationId=v.OrganizationId                                       
 inner join rvlfVehicleAssignment va on v.VehicleId=va.VehicleId                                            
 inner join rvlfOrganization O on O.OrganizationId = S.OrganizationID                                                     
 inner join rvlfTimeZones TZ on TZ.TimeZoneID = O.CountryId                                                 
 where s.RFID= dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RF_ID=',';') and va.BoxId=@intBoxID                                   
 End                   
  ----------------      ----------------       ----------------                            
       /*********** demo ********************/                                                
       -- Demo Account Mapping                                                       
       /*IF(@intDemoBoxID IS NOT NULL)                                                      
       BEGIN                                                
       SELECT @bigAlarmID  = ISNULL(Max(AlarmID),0)+1 FROM rvlfAlarm                                                
       INSERT INTO rvlfAlarm                                                 
       ( AlarmId,AlarmLevelId, DateTimeCreated , BoxId ,  AlarmType ,Lat , Long , [Description],StreetAddress )      
       VALUES  ( @bigAlarmID , @tiAlarmLevelID, @dtOriginDateTime , @intDemoBoxID , @tiBoxMsgInTypeId, @dLatitude , @dLongitude ,       
CASE WHEN @tiBoxMsgInTypeId IN (5 , 6) THEN CAST(@bigGeoZoneID AS varchar(600))                                                
  WHEN @tiBoxMsgInTypeId = 4 THEN CAST (@tiSpeed As Varchar(600))                                                
  ELSE dbo.rvlf_fn_GetAlarmDetails(@vcCustomProp , @tiBoxMsgInTypeId, @intDemoBoxID,@uiDemoMsgInID, @dtOriginDateTime) END,       
CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END            
)                                                
END */                                                
      /*************end **********************/                  
      END                                              
                                                  
     /******************************************************************************/                                                  
     /***************************Communication Processing***************************/                                                  
        -- Inserts the communication information based on the communication information.                                                  
    IF NOT EXISTS(SELECT commAddressValue FROM rvlfBoxCommInfo WHERE BoxId = @intBoxID AND CommAddressValue =@vcNewIP)      
       BEGIN                                                  
       DELETE FROM rvlfBoxCommInfo WHERE BoxId = @intBoxID                                                      
       INSERT INTO rvlfBoxCommInfo(BoxID,CommAddressTypeId,CommAddressValue)                                                  
       SELECT @intBoxID,CommAddressTypeID,@vcNewIP FROM rvlfCommModeAddressType                 
        WHERE CommModeId = @tiCommModeId                                                       
       END                                                     
        /******************************************************************************/                                           
       PRINT 'Trip Table'                                   
    /**************************Trip Processing*************************************/                                            
    DECLARE @tripTobeProcessed bigint                                            
    DECLARE @bigTripID bigint                                     
 DECLARE @bigPreviousTripID bigint                                            
    -- Checks the Geozone status and update starts or ends the trip against boxid.                                            
    IF EXISTS (SELECT 1 FROM dbo.rvlfBoxId WHERE BoxID=@intBoxID AND OrganizationID=201) --Afcons Clients      
    BEGIN                                          
      SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetails_AFC WHERE BoxID = @intBoxID AND IsTripClosed = 0      
      IF(@bigOdoMeterReading IS NULL AND @tiBoxMsgInTypeId=114 AND CHARINDEX(';Odometer:',@vcCustomProp,0) <> 0)      
      BEGIN                                   
    SELECT @bigOdoMeterReading=SUBSTRING(@vcCustomProp,CHARINDEX(';Odometer:',@vcCustomProp,0)+10,                                          
    (LEN(@vcCustomProp)-(CHARINDEX(';Odometer:',@vcCustomProp,0)+9)))                                          
      END                                          
      ELSE IF (@bigOdoMeterReading IS NULL AND @tiBoxMsgInTypeId=6)                                          
      BEGIN                                          
      SELECT @bigOdoMeterReading=SUBSTRING(@vcCustomProp,CHARINDEX(';Odometer=',@vcCustomProp,0)+10,                                          
    ((CHARINDEX(';Battery',@vcCustomProp,0))-(CHARINDEX(';Odometer=',@vcCustomProp,0)+10)))                                          
      END                                           
                                              
      UPDATE dbo.rvlfTripDetails_AFC SET EndDate=@dtOriginDateTime , OdometerEnd = CASE WHEN @bigOdoMeterReading IS NULL       
      THEN OdometerEnd  ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID ,       
      IsTripClosed = CASE WHEN @tiBoxMsgInTypeId = 5 THEN 1 ELSE 0 END,       
    IdlingDuration = IdlingDuration + (CASE WHEN @tiBoxMsgInTypeId <> 9 THEN 0 ELSE       
      CAST(dbo.rvlf_fn_GetDuration(@vcCustomProp, @tiBoxMsgInTypeID, @intBoxID,0) as int) END)       
      WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID AND IsTripClosed = 0       
                                             
      IF @tiBoxMsgInTypeId IN (5,6,114)                                          
       BEGIN                                  
        IF (@tiBoxMsgInTypeId = 6 OR (@tiBoxMsgInTypeId = 114 AND CHARINDEX('GeozoneInOutWithDuration:',@vcCustomProp,0) <> 0))                                           
        AND @tripTobeProcessed = 0                                            
         BEGIN                                            
           SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM dbo.rvlfTripDetails_AFC WHERE BoxId = @intBoxID                                             
           SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM dbo.rvlfTripDetails_AFC                                          
                                       
           INSERT INTO dbo.rvlfTripDetails_AFC(TripId, BoxId, StartDate, EndDate,  OdometerStart, OdometerEnd,                                            
           StartMessageInID , EndMessageInID, IsTripClosed)  VALUES                                             
           (@bigTripID,@intBoxID, @dtOriginDateTime, @dtOriginDateTime, @bigOdoMeterReading ,                                            
           @bigOdoMeterReading , @uiMsgInID , @uiMsgInID, 0)                                        
                                                     
           INSERT INTO dbo.rvlfTripFareDetails(TripId) VALUES(@bigTripID) --Trip Fare Details                                          
                                                        
           UPDATE dbo.rvlfTripDetails_AFC SET StopTime = DATEDIFF(ss, EndDate, @dtOriginDateTime)                                           
           WHERE BoxId = @intBoxID AND TripID = @bigPreviousTripID                                
        END                                            
        ELSE IF @tiBoxMsgInTypeId = 5 AND @tripTobeProcessed = 0                                  
        BEGIN                                            
           SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetails_AFC WHERE BoxID = @intBoxID AND IsTripClosed = 1                                                            
           UPDATE dbo.rvlfTripDetails_AFC SET EndDate=@dtOriginDateTime , OdometerEnd = CASE WHEN @bigOdoMeterReading IS NULL                                             
           THEN OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID ,IsTripClosed = 1                                            
           WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID                                            
        END                                            
    END                                            
   END                                          
   ELSE                   
   BEGIN --Other Clients                                       
  -- Checks the ignition status and starts or ends the trip.                                            
      SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetails WHERE BoxID = @intBoxID       
       AND IsTripClosed = 0                                            
       
      UPDATE dbo.rvlfTripDetails SET EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL THEN  OdometerEnd ELSE @bigOdoMeterReading END,EndMessageInID = @uiMsgInID , IsTripClosed = CASE WHEN @bitIgnitionStatus =  0 THEN 1 ELSE







  
     
0 END,                                            
      IdlingDuration = IdlingDuration + (CASE WHEN @tiBoxMsgInTypeId <> 9 THEN 0 ELSE                                             
      CAST(dbo.rvlf_fn_GetDuration(@vcCustomProp, @tiBoxMsgInTypeID, @intBoxID,0) as int) END)                                            
      WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID AND IsTripClosed = 0                                
                                              
 IF @tiBoxMsgInTypeId <> 13                                            
       BEGIN                                            
        IF @bitIgnitionStatus = 1 AND @tripTobeProcessed = 0 and (@tiBoxMsgInTypeId = 2 AND CHARINDEX('SENSOR_NUM=3;',@vcCustomProp,0) <> 0)                                    
        BEGIN                                            
   SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM dbo.rvlfTripDetails WHERE BoxId = @intBoxID                                    
   SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM dbo.rvlfTripDetails                                          
                                              
   INSERT INTO dbo.rvlfTripDetails                                             
   (TripId, BoxId, StartDate, EndDate,  OdometerStart, OdometerEnd,StartMessageInID , EndMessageInID, IsTripClosed)                                            
   VALUES (@bigTripID, @intBoxID, @dtOriginDateTime, @dtOriginDateTime, @bigOdoMeterReading ,                                             
   @bigOdoMeterReading , @uiMsgInID , @uiMsgInID, 0)                                            
                                                       
   UPDATE dbo.rvlfTripDetails SET StopTime = DATEDIFF(ss, EndDate, @dtOriginDateTime)                                             
   WHERE BoxId = @intBoxID AND TripID = @bigPreviousTripID                                            
   END                                            
       ELSE IF @bitIgnitionStatus = 0 AND @tripTobeProcessed = 0 AND (@tiBoxMsgInTypeId = 3  AND                                   
       CHARINDEX('SENSOR_NUM=3;',@vcCustomProp,0) <> 0)                                          
   BEGIN                                            
SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetails                                            
    WHERE BoxID = @intBoxID AND IsTripClosed = 1                                            
    UPDATE dbo.rvlfTripDetails SET EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL THEN OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID , IsTripClosed = 1                                         
    WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID                                            
   END                                            
  END  --                                  
  Declare @Sensor int --Get sensor                                           
   if CHARINDEX('SENSOR_NUM=',@vcCustomProp,0) <> 0                                          
 begin                                          
  set @sensor=(SUBSTRING(@vcCustomProp,CHARINDEX('SENSOR_NUM=',@vcCustomProp,0)+11,                                                                      
        (CHARINDEX(';',@vcCustomProp,0) - (CHARINDEX('SENSOR_NUM=',@vcCustomProp,0)+11))))                                          
 end                                                  
  -- Checks the ignition status and starts or ends the trip.                                                        
     SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetailssensorbsd WHERE BoxID = @intBoxID                                               
 AND IsTripClosed = 0                                                        
 AND (CHARINDEX('SENSOR_NUM=',@vcCustomProp,0) = 0 or SensorNo=@Sensor) --#                                             
                                                     
      UPDATE dbo.rvlfTripDetailssensorbsd SET EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL THEN  OdometerEnd ELSE                                      
      @bigOdoMeterReading END,EndMessageInID = @uiMsgInID , --IsTripClosed = CASE WHEN @bitIgnitionStatus = 0 THEN 1 ELSE 0 END, #                                    
      IdlingDuration = IdlingDuration + (CASE WHEN @tiBoxMsgInTypeId <> 9 THEN 0 ELSE                                                     
      CAST(dbo.rvlf_fn_GetDuration(@vcCustomProp, @tiBoxMsgInTypeID, @intBoxID,0) as int) END)                                             
      WHERE  BoxId = @intBoxID AND IsTripClosed = 0 -- AND TripID = @tripTobeProcessed  #                                                
                                                
      IF @tiBoxMsgInTypeId <> 13                                                        
       BEGIN   --@bitIgnitionStatus = 1 AND                                                           
   IF  @tripTobeProcessed = 0 and (@tiBoxMsgInTypeId = 2 AND CHARINDEX('SENSOR_NUM=',@vcCustomProp,0) <> 0)        
   BEGIN                                                        
    SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM dbo.rvlfTripDetailssensorbsd WHERE BoxId = @intBoxID and SensorNo=@sensor  --#                                                      
    SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM dbo.rvlfTripDetailssensorbsd                                                  
                                                
    INSERT INTO dbo.rvlfTripDetailssensorbsd                                                         
    (TripId, BoxId, StartDate, EndDate,  OdometerStart, OdometerEnd,StartMessageInID , EndMessageInID, IsTripClosed,SensorNo)   --#          
    VALUES (@bigTripID, @intBoxID, @dtOriginDateTime, @dtOriginDateTime, @bigOdoMeterReading ,                                             @bigOdoMeterReading , @uiMsgInID , @uiMsgInID, 0,@Sensor)                                                        
                                     
      UPDATE dbo.rvlfTripDetailssensorbsd SET StopTime = DATEDIFF(ss, EndDate, @dtOriginDateTime)                                                         
 WHERE BoxId = @intBoxID AND TripID = @bigPreviousTripID                                         
                                          
   END                                                        
   ELSE IF  (@tiBoxMsgInTypeId = 3 AND CHARINDEX('SENSOR_NUM=',@vcCustomProp,0) <> 0)   -- #@bitIgnitionStatus = 0  AND AND @tripTobeProcessed = 0                                               
   BEGIN                                                        
    SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetailssensorbsd                                                        
    WHERE BoxID = @intBoxID and SensorNo=@sensor--AND IsTripClosed = 1  #                                     
                                             
    UPDATE dbo.rvlfTripDetailssensorbsd SET EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL                                                         
    THEN OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID , IsTripClosed = 1                                                        
    WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID and SensorNo=@sensor   --#                                          
    END        
   END                                  
  END                                          
 /******************************************************************************/                                            
                PRINT 'Schedule Table'                                   
     /*************************Message out Processing (ACK / Response)**************/                                                  
     IF @dtSentDateTime IS NOT NULL                                                  
      BEGIN                                                  
UPDATE rvlfMsgOutHst SET Acknowledged = 1, MessageInID= @uiMsgInID                                                 
        WHERE BoxId = @intBoxID AND SentDateTime = @dtSentDateTime                               
                                                                                   
        --Update reporting interval and speed threshold to master table                   
  UPDATE v SET v.RptInterval=--(CASE WHEN H.BoxCmdOutTypeId=1 THEN dbo.rvlf_fn_GetTimeFromSeconds(H.CustomProp) ELSE v.RptInterval END),
         (CASE WHEN H.BoxCmdOutTypeId=1 and CHARINDEX(',1',H.CustomProp,1)=0 THEN dbo.rvlf_fn_GetTimeFromSeconds(H.CustomProp)
  WHEN H.BoxCmdOutTypeId=1 and CHARINDEX(',1',H.CustomProp,1)>0 THEN REPLACE(H.CustomProp,',1','') ELSE v.RptInterval END), 
  v.SpdThreshold = (CASE WHEN H.BoxCmdOutTypeId=2 THEN CAST(H.CustomProp AS TINYINT) ELSE v.SpdThreshold END) FROM rvlfVehicle v                                               
  INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId                                              
  INNER JOIN rvlfMsgOutHst H ON H.BoxId=va.BoxId                                           
  WHERE H.BoxId = @intBoxID AND H.SentDateTime = CAST(@dtSentDateTime AS DATETIME) AND H.BoxCmdOutTypeId IN (1,2)                                              
                   
       /*********** demo *****************/                                                
       -- Demo Account Mapping                                                 
       /*IF(@intDemoBoxID IS NOT NULL)                                                
       BEGIN                                                
       UPDATE rvlfMsgOutHst SET Acknowledged = 1, MessageInID= @uiDemoMsgInID WHERE                                                
        BoxId = @intDemoBoxID AND SentDateTime = @dtSentDateTime                                                 
       END */   
       /*********end **************/                                                 
                                                       
       DECLARE @tiCmdTypeID tinyint=(SELECT BoxCmdOutTypeId FROM rvlfMsgOutHst WHERE BoxId = @intBoxID AND SentDateTime = @dtSentDateTime)                                                
       IF(@tiCmdTypeID IN(11,12))                                                
        BEGIN                                                        
         DECLARE @bigUserID bigint,@bigVehicleID bigint,@bigGeozoneNo bigint,@bigPassOrganizationID bigint                                                         
         SELECT @bigVehicleID = VehicleId FROM rvlfVehicleAssignment                                                 
          WHERE BoxId=@intBoxID AND IsDeleted <> 1                                                         
         DECLARE @tiSeverity bigint                                                  
         IF @tiCmdTypeID = 11                                                   
          BEGIN                                                        
           SELECT @bigUserID= MO.UserId, @bigGeozoneNo=CAST(MO.CustomProp AS bigint),@bigPassOrganizationID=OG.OrganizationId                                                          
            FROM rvlfMsgOutHst MO INNER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId=CAST(MO.CustomProp AS bigint)                                                
            WHERE  MO.BoxId = @intBoxID AND MO.SentDateTime = @dtSentDateTime AND OG.OrganizationId=@bigOrganizationID                                                   
                                                       
           SELECT @tiSeverity = SeverityId FROM rvlfOrganizationGeozone WHERE GeozoneId = @bigGeozoneNo  and OrganizationId = @bigPassOrganizationID                                                
                                                       
           IF(@tiSeverity IS NOT NULL)                                                
            BEGIN                   IF NOT EXISTS(SELECT GeozoneNo FROM rvlfVehicleGeozone                                                   
              WHERE VehicleId = @bigVehicleID AND GeozoneNo = @bigGeozoneNo)                                                  
              BEGIN                                                  
                                                          
       DECLARE @IsUnAuthorizedGeo AS BIT = 0                                            
           SELECT @IsUnAuthorizedGeo  = DN.IsUnAuthorisedGeoZone                                                      
     FROM rvlfdelaynotify DN                                                           
     INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId = DN.BoxId                                                           
     INNER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId = DN.GeozoneId                                                        
     WHERE VA.VehicleId = @bigVehicleID AND OG.GeozoneId = @bigGeozoneNo                                              
                                                          
               INSERT INTO rvlfVehicleGeozone(VehicleId,SeverityId,GeozoneNo,AssingedBy,AssingedDate,IsUnAuthorizedGeozone)                                                  
                VALUES(@bigVehicleID, @tiSeverity, @bigGeozoneNo, @bigUserID, @dtSentDateTime,@IsUnAuthorizedGeo)                                     
              END       
            END                                                
          END                                                          
         IF @tiCmdTypeID = 12                                                   
          BEGIN                                                  
           DECLARE @vcGeozoneIDs varchar(150)=(SELECT CustomProp  FROM rvlfMsgOutHst WHERE BoxId = @intBoxID AND SentDateTime = @dtSentDateTime)                                                
           
           IF @vcGeozoneIDs ='65535'                                                  
            BEGIN                                                  
             DELETE FROM rvlfVehicleGeozone WHERE VehicleId= @bigVehicleID                                                   
            END                                                  
           ELSE                                                   
            BEGIN                                                         
             DELETE rvlfVehicleGeozone WHERE VehicleId= @bigVehicleID                                                   
              AND GeozoneNo IN (SELECT GeozoneId FROM rvlfOrganizationGeozone                                                   
               WHERE OrganizationId = @bigOrganizationID AND GeozoneId IN                                                  
                (SELECT *  from dbo.rvlf_fn_ConvertArrayToTable(@vcGeozoneIDs,',')))                                                  
            END                                                  
          END                                                  
        END                                                  
      END                                        
        IF (@intBoxID = 2)                                 
      BEGIN                                                
       exec rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId END                                                
                                                    
     -- Disable SMS for Dhana college when Fuel Drain with Ignition ON                                                
     IF (@bigOrganizationID = 47 and @tiBoxMsgInTypeId = 90 and @bitIgnitionStatus = 1)                                                
      BEGIN                                                      
UPDATE rvlfMsgInHst set IsNotificationSent = 1 where MessageInID = @uiMsgInID                                                   
      END                                                   
       
       --Log notifications for geozone messages.                                                        
       --IF(@tiBoxMsgInTypeId IN(5,6))                                              
       --BEGIN                                                        
   --EXEC rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId                                  
       --END                                                  
          PRINT 'Log Notification Table'                           
       --UPDATE THE LOG NOTIFICATION FOR INVALID GPS                                           
   --   ELSE IF @tiValidGps >= 0 AND @tiBoxMsgInTypeId=100                                  
   --   BEGIN                                  
   --EXEC rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId                                                
   --   END                                         
      IF @tiValidGps > 0 AND @tiBoxMsgInTypeId NOT IN (100,21)  and @vcCustomProp not like '%IButtonCommand:1%' and @vcCustomProp not like '%CameraSettings:1%' and @vcCustomProp not like '%ImgHeader%' and @vcCustomProp not like '%SendSMSQuery:1%'        
                          
       BEGIN                                      
   EXEC rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId                                               
       END                                               
        --PRINT 'Welcome 4'                                          
    IF @trancount = 0                         
            COMMIT;                                           
    -- COMMIT TRAN                                             
    END TRY                                                  
    BEGIN CATCH                                            
        DECLARE @error int, @message varchar(4000), @xstate int;                                          
        SELECT @error = ERROR_NUMBER(),                           
               @message = ERROR_MESSAGE(),                                           
               @xstate = XACT_STATE();                                          
                                          
        if @xstate = -1                                          
            ROLLBACK TRAN;                                          
        if @xstate = 1 and @trancount = 0                                          
         ROLLBACK TRAN;                                          
        if @xstate = 1 and @trancount > 0                                          
            ROLLBACK TRANSACTION MessageTransaction;                                              
                                           
      --ROLLBACK TRAN                                          
      SET @ErrorMessage = 'An Error occured during insert of the packet message : ' + @message                                          
      RAISERROR( @ErrorMessage,16,1)                                                  
    END CATCH                                                   
    END--CONDITION 02 END                                                
  END                                                
 END --CONDITION 01 END                                                   
/******************************************************************************/                                                                
 --Student Punch RFID                                  
 IF(@tiBoxMsgInTypeId IN(5,6,114) and CHARINDEX('GeozoneID=',@vcCustomProp,0)>0)                                                                                  
 BEGIN                                                
  If exists ( select * from rvlfSchoolMaster A inner join rvlfBoxId B on a.OrganizationID=B.OrganizationId                            
   where B.BoxId=@intBoxID and GeozoneId=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'GeozoneID=',';'))                                        
  begin                                          
      Begin try                                          
        Exec rvlf_sp_GetandUpdateRFIDStudentSMSTrigger @intBoxID                                 
         print 'Student log RFID Updated'                                        
      end try                                  
      BEGIN CATCH                  
      --ROLLBACK TRAN                                                                                 
      SET @ErrorMessage = 'An Error occured during insert of RFID Student entry to school : ' + ERROR_MESSAGE()                                
      RAISERROR( @ErrorMessage,16,1)                                                                
    END CATCH                                            
 end                                   
 END                              

 --Student RFID Swipes Notifications by Anbarasu.E on 12-Aug-2015
 IF(@tiBoxMsgInTypeId IN(100) and CHARINDEX('RF_ID=',@vcCustomProp,0)>0)                                                                    
 BEGIN                                  
  SELECT @bigOrganizationID = OrganizationID FROM rvlfBoxId WHERE BoxId = @intBoxID                                           
  If exists (select * from rvlfStudentMaster where OrganizationID=@bigOrganizationID and RFID=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RF_ID=',';'))                          
  begin                            
      Begin try
      if exists(select * from rvlfBoxId b inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId            
	  inner join rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1            
	  inner join rvlfPackageOperations po on op.PackageId=po.PackageId            
	  inner join rvlfOperationType ot on po.OperationID=ot.OperationTypeId            
	  where b.BoxId=@intBoxID and charindex('Notification for Each',ot.OperationTypeName,1)>0)
	  Begin
         Exec rvlf_sp_TriggerSMSforStudentRFIDSwipes	@intBoxID,@dtOriginDateTime,@vcCustomProp,@uiMsgInID                    
         print 'Student RFID swipes log Updated'                          
      End
      end try                            
      BEGIN CATCH                                                                    
      --ROLLBACK TRAN                                                                     
      SET @ErrorMessage = 'An Error occured during insert of RFID Student swipe : ' + ERROR_MESSAGE()                  
      RAISERROR( @ErrorMessage,16,1)                                                  
    END CATCH                              
 end                     
 END 
                         
--Student SMS before stops reached                                  
IF(@tiBoxMsgInTypeId=114 and charindex('34;Routeid',@vcCustomProp,1)>0)                                  
BEGIN                                 
Declare @AlertMsg varchar(3)=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'AlertMsg=',';'))                                
if(@AlertMsg='011' or @AlertMsg='001')                                  
Begin                                   
if exists(select * from rvlfBoxId b inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId                                  
inner join rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1                                  
inner join rvlfPackageOperations po on op.PackageId=po.PackageId                                  
inner join rvlfOperationType ot on po.OperationID=ot.OperationTypeId                     
where b.BoxId=@intBoxID and charindex('Notification before',ot.OperationTypeName,1)>0)                                  
begiN                                   
 exec rvlf_sp_TriggerSMSBfrStops @intBoxID,@dtOriginDateTime,@vcCustomProp                                  
enD                                 
End                                 
END          
                                     
 --CHECK THE SCHEDULED OTA COMMAND RETRY**************************************************************                                                 
 DECLARE @bigRetryScheduleId bigint=null,@tintAck tinyint=null,@dtOtaTime datetime=null 
 SELECT TOP 1 @tintAck=Acknowledged,@dtOtaTime=H.SentDateTime FROM rvlfMsgOutHst H                                                     
  WHERE H.BoxCmdOutTypeId =22 AND H.BoxId =@intBoxID AND H.Acknowledged BETWEEN 0 AND 10 ORDER BY H.SentDateTime DESC                                                   
 IF (@tintAck NOT IN(2,6) AND @tintAck IS NOT NULL)                                                  
  BEGIN                                                  
   IF EXISTS(SELECT ScheduleId FROM rvlfScheduleOfCommandsMaster WHERE Boxid=@intBoxID AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND BoxCmdOutTypeId =22)                                                  
    BEGIN                                                  
     SELECT @bigRetryScheduleId =a.ScheduleId  FROM rvlfScheduleOfCommandsMaster a inner join rvlfSchedulingOfCommandsLog b
	on a.ScheduleId=b.ScheduleId                                                
      WHERE Boxid=@intBoxID and ResponseMsg != 'Success' AND BoxCmdOutTypeId =22 AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND GETUTCDATE() BETWEEN EffectiveFrom AND EffectiveTo                                                   
     IF @bigRetryScheduleId IS NOT NULL                                                  
 BEGIN                          
       UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=NULL WHERE ScheduleId =@bigRetryScheduleId AND BoxCmdOutTypeId=22                                                  
       IF EXISTS(SELECT ScheduleLogId FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId)      
        BEGIN                                         
         UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=NULL,ActualExecutionDate=CASE WHEN @dtOtaTime>CreatedDate AND @dtOtaTime <=EffectiveTo THEN @dtOtaTime ELSE NULL END WHERE ScheduleId =@bigRetryScheduleId AND BoxCmdOutTypeId  =22          

		  
      
         DELETE rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId AND ResponseId IN (1,2,3,4,6,7,8,9,10) --RESPONSEMSG!='Aborted'                                                   
        END                                                  
      END                                                      
    END                                                  
  END                                                   
 ELSE IF(@tintAck IS NULL)                                                  
  BEGIN                                                  
   SELECT @bigRetryScheduleId =ScheduleId  FROM rvlfScheduleOfCommandsMaster                                                 
    WHERE Boxid=@intBoxID AND BoxCmdOutTypeId =22 AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND GETUTCDATE() BETWEEN EffectiveFrom AND EffectiveTo                                                   
   IF(@bigRetryScheduleId IS NOT NULL OR @bigRetryScheduleId!='')                                                  
    BEGIN                                                       
     IF NOT EXISTS(SELECT ScheduleLogId FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId)      
      BEGIN                                                  
       INSERT INTO rvlfSchedulingOfCommandsLog (ScheduleId,ExecutionOn,IsCommandSend,[No.ofTries],ResponseMsg,ResponseId)      
       SELECT @bigRetryScheduleId,@dtOtaTime,1,1,'Command sent successfully.',3                                                  
      END                                                  
    END                                                      
  END         
                        
--------------Get next route to assign ---------------------------------------      
 IF(@tiBoxMsgInTypeId=114 and charindex('AlertMsg=001',@vcCustomProp,1)>0)                                      
 Begin            
 DECLARE @vcType1 varchar(50)=null,@bigScheduleId1 bigint=null      
                                      
 SELECT top 1 @vcType1=ExecutionOn,@bigScheduleId1= ScheduleId  FROM rvlfScheduleOfCommandsMaster SM                                       
 WHERE ScheduleId NOT IN(SELECT ScheduleId  FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE()))       AND SM.BoxId =@intBoxID    and SM.Isdelete is null  
     AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))                                         
     AND (GETUTCDATE()<= EffectiveFrom                                       
     AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END))                                       
     AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE()))                                      
     order by EffectiveFrom asc    
          --UPDATE THE LATEST IP AND PORT    
       UPDATE rvlfScheduleOfCommandsMaster                                              
        SET PacketInfo = REPLACE(PacketInfo,SUBSTRING(PacketInfo,CHARINDEX('IP=',PacketInfo,1)+3,(CHARINDEX(';',PacketInfo,CHARINDEX('Port=',PacketInfo,1))-4)),@vcCommInfo1+';Port='+CAST(@siCommInfo2 AS VARCHAR))                                      
       WHERE ScheduleId=@bigScheduleId1                                       
                                       
       --IF THE COMMANDS EXECUTION TYPE IS Ignition On                                                                                           
        IF (@vcType1 ='Ignition On' AND @tiBoxMsgInTypeId=2)      
        BEGIN                                              
         --INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn)      
        -- VALUES(@bigScheduleId1,GETUTCDATE())  
		 INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)                                                  
         VALUES(@bigScheduleId1,GETUTCDATE(),0)    
        END                                                                            
        ELSE IF(@vcType1 ='Any message in' AND @tiBoxMsgInTypeId =114)      
        BEGIN                                                                                          
         INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)                                                                                    VALUES(@bigScheduleId1,GETUTCDATE(),0)                                       
        END                            
 End                          
 ----------------------------------                      
 /**************************************************************************************************/      
 --SCHEDULE THE COMMANDS****************************************************************************/                                                
 IF (((SELECT TOP 1 BoxId  FROM rvlfBoxId WHERE BoxId=@intBoxID AND CONVERT(DATE,LastCommunicatedDateTime)=CONVERT(DATE,GETUTCDATE()))=@intBoxID) OR (@tiBoxMsgInTypeId=52))                                                    
  BEGIN                                            
  --PRINT 'Welcome 5'                                          
   --CHECK IF THE BOXID HAVE ANY SCHEDULES FOR GIVE COMMANDS                                                  
   IF EXISTS(SELECT ScheduleId  FROM rvlfScheduleOfCommandsMaster SM                                                   
    WHERE ScheduleId NOT IN(SELECT ScheduleId  FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE()))                                                   
     AND SM.BoxId =@intBoxID  and SM.Isdelete is null                                                
     AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))                                  
     --AND (GETUTCDATE()>= EffectiveFrom                                                  
     --AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END)) and BoxCmdOutTypeId<>94                  
     AND (GETUTCDATE()>= (case when BoxCmdOutTypeId=94 then DATEADD(MINUTE,-30,EffectiveFrom) else EffectiveFrom end)              
     AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END))                             
     AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE())))                                                  
    BEGIN                                            
    --PRINT 'Welcome 6'                                          
     DECLARE @TBLSCHEDULES TABLE(ScheduleId bigint,inc bit)                                                  
     INSERT INTO @TBLSCHEDULES(ScheduleId,inc)                                                 
      SELECT DISTINCT SM.ScheduleId,0 FROM rvlfScheduleOfCommandsMaster SM                                                      
       WHERE ScheduleId NOT IN(SELECT ScheduleId  FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE()))                                                   
        AND SM.BoxId =@intBoxID  and SM.Isdelete is null
        AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))                                                  
     --    AND (GETUTCDATE()>= EffectiveFrom         
     --AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END)) and BoxCmdOutTypeId<>94           
        AND (GETUTCDATE()>= (case when BoxCmdOutTypeId=94 then DATEADD(MINUTE,-30,EffectiveFrom) else EffectiveFrom end)         
        AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE  EffectiveTo END))         
         
        AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE()))        
     WHILE EXISTS(SELECT ScheduleId FROM @TBLSCHEDULES WHERE inc =0)                                                  
      BEGIN                                            
      --PRINT 'Welcome 7'                                          
       DECLARE @vcType varchar(50)=null,@bigScheduleId bigint=null                                                
       SELECT @bigScheduleId=ScheduleId FROM @TBLSCHEDULES WHERE inc=0                                                  
                                                            
          --UPDATE THE LATEST IP AND PORT                                                  
       UPDATE rvlfScheduleOfCommandsMaster                                  
        SET PacketInfo = REPLACE(PacketInfo,SUBSTRING(PacketInfo,CHARINDEX('IP=',PacketInfo,1)+3,(CHARINDEX(';',PacketInfo,CHARINDEX('Port=',PacketInfo,1))-4)),@vcCommInfo1+';Port='+CAST(@siCommInfo2 AS VARCHAR))     
       WHERE ScheduleId=@bigScheduleId  
                                                       
       SELECT TOP 1 @vcType=ExecutionOn,@bigScheduleId=ScheduleId FROM rvlfScheduleOfCommandsMaster                                                   
        WHERE ScheduleId=@bigScheduleId                                                   
                                                       
       --IF THE COMMANDS EXECUTION TYPE IS Ignition On                                                 
         IF (@vcType ='Ignition On' AND @tiBoxMsgInTypeId=2)                                                  
        BEGIN                                                  
         INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)                                                  
         VALUES(@bigScheduleId,GETUTCDATE(),0)                                        
        END                                                  
       ELSE IF(@vcType ='Any message in' AND @tiBoxMsgInTypeId NOT IN(12))                      
        BEGIN                                                
         INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)                                                  
          VALUES(@bigScheduleId,GETUTCDATE(),0)          
        END      
       UPDATE TOP(1) @TBLSCHEDULES SET inc=1 WHERE ScheduleId=@bigScheduleId                                                   
      END                                    
    END                                                        
 END                                                  
END                                   
END                                         
END                                  
SET NOCOUNT OFF                                  
end

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateMessageReceived_TP]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateMessageReceived_TP]
	@intBoxID varchar(50)=null,
	@dtOriginDateTime datetime,
	@dtDateTimeReceived datetime,
	@vcCommMode varchar(100),
	@tiBoxMsgInTypeId TINYINT = null,
	@vcBoxProtocolTypeName varchar(50) = null,
	@vcCommInfo1 varchar(15),
	@siCommInfo2 int ,
	@tiValidGps smallint = 2,
	@dLatitude decimal(10,6) = 0,
	@dLongitude decimal(10,6) = 0,
	@tiSpeed smallint = 0,
	@siHeading smallint = 0,
	@vcSensorMask varchar(8) = null,
	@vcCustomProp varchar(max)= null,
	@bigSequenceNum bigint = null,
	@bitIsArmed bit = null,
	@tiPriority tinyint = null,
	@bitIsAlarm bit =0,
	@dtSentDateTime datetime = null,
	@bitIgnitionStatus bit = null,
	@bigOdoMeterReading bigint = null,
	@bitIsTrinetraApp bit = 0,
	@ModelNo VARCHAR(256) = null,
	@odoValue_app varchar(6) = null,
	@AlarmDesc_app varchar(256) = null,
	@IsPrefAck bit = 0 ,
	@TransMode varchar(50) = null,
	@Cntlr_ID varchar(20) = null,
	@Cntlr_Type varchar(20) = null,
	@Comm_mode varchar(50) = null,
	@Alarm_Lvl varchar(50) = null,
	@Cntlr_Mode varchar(50) = null,
	@Supvsr_State varchar(50) = null,
	@Load_State varchar(20)= null,
	@LL_Average varchar(20)= null,
	@LN_Average varchar(20)= null,
	@LL_Phase_Imbalance varchar(20) = null,
	@LN_Phase_Imbalance varchar(20) = null,
	@Frequency varchar(20) = null,
	@Total_kW varchar(20) = null,
	@Total_kVA varchar(20) = null,
	@Total_kVAr varchar(20) = null,
	@Avg_pf varchar(20) = null,
	@Acultd_kWh varchar(20) = null,
	@Acultd_kVAh varchar(20) = null,
	@Acultd_kVArh varchar(20) = null,
	@Batt_Volt varchar(20) = null,
	@Eng_Speed varchar(20) = null,
	@Eng_Oil_Pressure varchar(20) = null,
	@Eng_Coolant_Temp varchar(20) = null,
	@Chrg_Alt_Volt varchar(20) = null,
	@Fuel_Level varchar(20) = null,
	@Run_Time varchar(20) = null,
	@Avg_Crnt varchar(20) = null,
	@Gen_Rating varchar(20) = null,
	@Aux_Fuel_Sndr varchar(20) = null,
	@GateWayID bigint = null,
	@dtDataIn xml = null,
	@AlarmDet varchar(50) =null,
	@S1_Available varchar(50) = null,
	@S2_Available varchar(50) = null,
	@Return_Delay_inprogress varchar(50) = null,
	@dtAlarm xml = null
AS
/*********************************************************************************************************************************/
-- Name : [rvlf_sp_UpdateMessageReceived]
-- Description : To insert the messages that is sent to the device
-- Author : V.Narayanasamy
-- Company : Angler Technologies
-- History : <<Date(dd-MON-yyyy)>> Initial Reason
/*********************************************************************************************************************************/
BEGIN
	SET NOCOUNT ON
	Declare @intBoxID1 varchar(50)=@intBoxID, @dtOriginDateTime1 datetime=@dtOriginDateTime, @dtDateTimeReceived1 datetime=@dtDateTimeReceived,
	@tiBoxMsgInTypeId1 TINYINT = @tiBoxMsgInTypeId,@tiValidGps1 smallint = @tiValidGps, @dLatitude1 decimal(10,6) = @dLatitude,
	@dLongitude1 decimal(10,6) = @dLongitude, @tiSpeed1 smallint = @tiSpeed, @vcCustomProp1 varchar(max)= @vcCustomProp,
	@dtSentDateTime1 datetime = @dtSentDateTime
	DECLARE @docHandle int
	declare @MessageInID uniqueidentifier=null
	IF (@tiBoxMsgInTypeId1 <> 52)
		BEGIN--CONDITION 01 START
			DECLARE @bigOrganizationID bigint=(SELECT OrganizationID FROM rvlfBoxId WHERE BoxId = @intBoxID1)

			DECLARE @tintSensor tinyint=CASE WHEN @vcCustomProp1 LIKE '%SENSOR_NUM=%' THEN
			CAST(dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'SENSOR_NUM=',';')
			--SUBSTRING(@vcCustomProp1,CHARINDEX('%SENSOR_NUM=%',@vcCustomProp1,0)+12,(CHARINDEX(';',@vcCustomProp1,
			--(CHARINDEX('%SENSOR_NUM=%',@vcCustomProp1,0)))-(CHARINDEX('%SENSOR_NUM=%',@vcCustomProp1,0)+12)))
			AS TINYINT) ELSE 0 END

			DECLARE @tintBoxgnore tinyint=(SELECT COUNT(igid) FROM rvlfboxignoremsgs WHERE BOXID =@intBoxID1 AND
			BOXMSGINTYPEID=@tiBoxMsgInTypeId1 AND SENSORNO=@tintSensor)

			IF(@tintBoxgnore=0)
			DECLARE @tintOrgIgnore tinyint=(SELECT count(igid) FROM rvlforgignoremsgs WHERE ORGID =@bigOrganizationID
			AND BOXMSGINTYPEID=@tiBoxMsgInTypeId1 AND SENSORNO=@tintSensor)
			--CHECK THE IGNORE MESSAGES BASED ON THE RVLFBOXIGNOREMSGS TABLE

			IF(@tintBoxgnore=0)
			IF(@tintOrgIgnore=0)
				BEGIN
					IF Exists (SELECT MessageInID FROM rvlfMsgInHst WHERE BoxId = @intBoxID1 AND BoxMsgInTypeId = @tiBoxMsgInTypeId1
					AND OriginDateTime = @dtOriginDateTime1 ) --and CustomProp=@vcCustomProp1)
						BEGIN
							RAISERROR('Data Integrity Violation', 16,1)
						END
					ELSE
						BEGIN--CONDITION 02 START
							-- Local variables to hold the intermediate results
							DECLARE @ErrorMessage varchar(3000)
							DECLARE @intBoxProtocolTypeId int
							DECLARE @tiServiceID tinyint
							DECLARE @tiCommModeId tinyint
							DECLARE @MsgInID TABLE ( uiMsgInID uniqueidentifier)
							DECLARE @uiMsgInID1 uniqueidentifier
							DECLARE @uiMsgInID uniqueidentifier
							DECLARE @vcNewIP varchar(25)
							SET @vcNewIP = @vcCommInfo1 + ':'+ CAST(@siCommInfo2 AS varchar(5))
							DECLARE @dtLastValidGPSTime datetime
							DECLARE @bitCreateAlarm bit
							DECLARE @tiAlarmLevelID tinyint
							DECLARE @bigGeoZoneID bigint
							DECLARE @vcAlarmLevelName varchar(30)
							/********** demo*************/
							DECLARE @DemoMsgInID TABLE ( uiDemoMsgInID uniqueidentifier)
							DECLARE @uiDemoMsgInID uniqueidentifier
							DECLARE @vcOldIP varchar(25)
							SET @vcNewIP = @vcCommInfo1 + ':'+ CAST(@siCommInfo2 AS varchar(5))
							--DECLARE @bitCanNotify bit
							SET @dtLastValidGPSTime = @dtOriginDateTime1
							DECLARE @IsAddressAlreadyAvailable bit = 0
							DECLARE @vcStreetAddress varchar(250)
							DECLARE @vcNearestLandmark varchar(300)
							/*********end *****************/
							SET @dtLastValidGPSTime = @dtOriginDateTime1
							--update the origindatetime if origindatetime is greater then current date time
							IF(@dtOriginDateTime1>CONVERT(datetime,CONVERT(varchar(19),SYSUTCDATETIME())))
								BEGIN
									SET @dtOriginDateTime1=CONVERT(datetime,CONVERT(varchar(19),SYSUTCDATETIME()))
								END
							--update the datetimerecived if datetimerecived is greater then origindatetime
							IF(@dtOriginDateTime1>=@dtDateTimeReceived1)
								BEGIN
									SET @dtDateTimeReceived1=DATEADD(S,2,@dtOriginDateTime1)
								END
							--GET THE PROTOCOLID BASED ON THE PROTOCOL NAME
							SELECT @intBoxProtocolTypeId = isnull(BoxProtocolTypeId,1) FROM rvlfBoxProtocolType WHERE BoxProtocolTypeName = isnull(@vcBoxProtocolTypeName,'RVLTv1.0')
							--GET THE COMMAND MODE ID BASED ON THE COMMANDMODE NAME
							SELECT @tiCommModeId = CommModeId FROM rvlfCommMode WHERE CommModeName = @vcCommMode
							--GET THE PROTOCOLID BASED ON THE PROTOCOL NAME
							SELECT @tiServiceID = ServiceID FROM rvlfServices WHERE CommModeId = @tiCommModeId
							/***************************Severity Settings**********************************/
							-- Checks if the message has the severity settings such that an alarm has to be created.
							IF EXISTS (SELECT BoxId FROM rvlfBoxMsgSeverity WHERE BoxId=@intBoxID1 AND BoxMsgInTypeId = @tiBoxMsgInTypeId1)
								BEGIN
									DECLARE @intDuration int = 1
									IF @tiBoxMsgInTypeId1 = 9
										BEGIN
											SET @intDuration = CAST (SUBSTRING (@vcCustomProp1, CHARINDEX(':',@vcCustomProp1,1)+1,
											CHARINDEX(';',@vcCustomProp1)-1 -CHARINDEX(':',@vcCustomProp1,1)) as Int)
										END
									IF @intDuration > 0
										BEGIN
											SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.AlarmLevelID, @vcAlarmLevelName = s.AlarmLevelName
											FROM rvlfBoxMsgSeverity bs
											INNER JOIN rvlfSeverity s On bs.AlarmLevelID = s.AlarmLevelId
											WHERE bs.BoxId = @intBoxID1 AND bs.BoxMsgInTypeId = @tiBoxMsgInTypeId1
										END
								END
							ELSE
								BEGIN
									SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.DefaultAlarmLevel,@vcAlarmLevelName = s.AlarmLevelName
									FROM rvlfBoxProtocolMsgInType bs
									INNER JOIN rvlfSeverity s On bs.DefaultAlarmLevel = s.AlarmLevelId
									WHERE bs.BoxMsgInTypeId = @tiBoxMsgInTypeId1
								END
							IF @tiBoxMsgInTypeId1 = 11
								BEGIN
									DECLARE @tiSensorID tinyint,@intSensorStateStart int,@intSensorStateEnd int,
									@vcSensorStatus varchar(50),@bitIsOn bit
									SET @tiSensorID = CAST(SUBSTRING(@vcCustomProp1,CHARINDEX('=',@vcCustomProp1)+1,1) As tinyint)
									SET @intSensorStateStart = CHARINDEX('=',@vcCustomProp1,LEN('SENSOR_NUM=')+1)
									SET @intSensorStateEnd = CHARINDEX(';',@vcCustomProp1,15)
									SET @vcSensorStatus =
									CASE WHEN @vcCustomProp1 LIKE '%SENSOR_STATUS=%' THEN
									dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'SENSOR_STATUS=',';')
									-- SUBSTRING(@vcCustomProp1,CHARINDEX('SENSOR_STATUS=',@vcCustomProp1,0)+14,
									-- (CHARINDEX(';',@vcCustomProp1,(CHARINDEX('SENSOR_STATUS=',@vcCustomProp1,0)))-(CHARINDEX('SENSOR_STATUS=',@vcCustomProp1,0)+14)))
									ELSE SUBSTRING(@vcCustomProp1,@intSensorStateStart+1, @intSensorStateEnd - @intSensorStateStart-1)END
									SET @bitIsOn = CASE WHEN @vcSensorStatus = 'OPEN' OR @vcSensorStatus = 'ON'
									OR @vcSensorStatus = 'NORMAL' OR @vcSensorStatus = 'OK' THEN 1
									WHEN @vcSensorStatus = 'CLOSE' OR @vcSensorStatus = 'OFF' OR @vcSensorStatus = 'LOW' THEN 0
									END
									IF EXISTS (SELECT BoxId FROM rvlfBoxSensorsCfg WHERE BoxId = @intBoxID1 AND SensorId = @tiSensorID)
										BEGIN
											SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = s.AlarmLevelId, @vcAlarmLevelName = s.AlarmLevelName
											FROM rvlfBoxSensorsCfg bs INNER JOIN rvlfSeverity s ON s.AlarmLevelId =
											(CASE WHEN @bitIsOn=1 THEN bs.AlarmLevelOn ELSE AlarmLevelOff END)
											WHERE bs.BoxId = @intBoxID1 AND bs.SensorId = @tiSensorID
										END
									ELSE
										BEGIN
											SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.DefaultAlarmLevel,
											@vcAlarmLevelName = s.AlarmLevelName
											FROM rvlfBoxProtocolMsgInType bs
											INNER JOIN rvlfSeverity s On bs.DefaultAlarmLevel = s.AlarmLevelId
											WHERE bs.BoxMsgInTypeId = @tiBoxMsgInTypeId1
										END
								END
							IF @tiBoxMsgInTypeId1 = 27
								BEGIN
									SET @bitCreateAlarm = 1
								END
							DECLARE @trancount int;
							SET @trancount = @@trancount;
							--PRINT CAST(@trancount as varchar)
								BEGIN TRY
									IF @trancount = 0
										BEGIN TRANSACTION;
									ELSE
									SAVE TRANSACTION MessageTransaction;
									/***********************Message In History*************************************/
									--BEGIN TRAN MessageTransaction
									--BEGIN TRY
									--PRINT 'Welcome 1'
									-- IF @vcCustomProp not like '%ImgData:1%' -- CHARINDEX('ImgData:', @vcCustomProp) = 0
									--begin
									PRINT 'Message Table.'
									-- To insert the information in the message in history table
									--if(@CmdID1 is null or @CmdID1 not in (2,3)) begin
									IF @dtDataIn IS NOT NULL
										BEGIN
											if @Cntlr_Type = '335'
												Begin
													EXEC sp_xml_preparedocument @docHandle OUTPUT, @dtDataIn
													INSERT INTO rvlfMsgInHst_Techno_355
													(
													BoxId, OriginDateTime, DateTimeReceived, BoxMsgInTypeId, CommInfo1, CommInfo2, ValidGps, Latitude, Longitude, Speed, Heading, CustomProp, SequenceNum, IsArmed, IsProcessed, IsArchived, ControllerID, Alarm, S1_Tot_Watts, S1_Tot_VA, S1_Tot_VAr, S1_KWh, S1_KVAh, S1_KVArh, S1_Freq, S1_AvgPF, S1_L1_PF, S1_L1_VAr, S1_L1_VA, S1_L1_Watts, S1_L1_Current, S1_L2_PF, S1_L2_VAr, S1_L2_VA, S1_L2_Watts, S1_L2_Current, S1_L3_PF, S1_L3_VAr, S1_L3_VA, S1_L3_Watts, S1_L3_Current, S2_Tot_Watts, S2_Tot_VA, S2_Tot_VAr, S2_KWh, S2_KVAh, S2_KVArh, S2_Freq, S2_AvgPF, S2_L1_PF, S2_L1_VAr, S2_L1_VA, S2_L1_Watts, S2_L1_Current, S2_L2_PF, S2_L2_VAr, S2_L2_VA, S2_L2_Watts, S2_L2_Current, S2_L3_PF, S2_L3_VAr, S2_L3_VA, S2_L3_Watts, S2_L3_Current, Main_Gen_LNVolt, Gen_LLVolt, GateWayID, ComMode, Digital_IP, Digital_OP, S1_L1_N_Voltage, S1_L2_N_Voltage, S1_L3_N_Voltage, S1_L1_L2_Voltage, S1_L2_L3_Voltage, S1_L3_L1_Voltage, S2_L1_N_Voltage, S2_L2_N_Voltage, S2_L3_N_Voltage, S2_L1_L2_Voltage, S2_L2_L3_Voltage, S2_L3_L1_Voltage, S1_LN_Volt, S1_LL_Volt, S2_LN_Volt, S2_LL_Volt)
													OUTPUT INSERTED.MessageInID into @MsgInID
													SELECT @intBoxID1, @dtOriginDateTime1, @dtDateTimeReceived1, @tiBoxMsgInTypeId1, @vcCommInfo1, @siCommInfo2, @tiValidGps1, @dLatitude1, @dLongitude1, @tiSpeed1, @siHeading, @vcCustomProp1, @bigSequenceNum, @bitIsArmed, CASE WHEN @tiValidGps = 0 THEN 1 ELSE NULL END, 0, @Cntlr_ID, @Alarm_Lvl, S1_Total_Watts, S1_Total_VA, S1_Total_Var, null, null, null, S1_frequency, S1_AVERAGE_POWER_FACTOR, null, null, null, S1_L1_Watts, S1_L1_current, null, null, null, S1_L2_Watts, S1_L2_current, null, null, null, S1_L3_Watts, S1_L3_current, S2_Total_Watts, S2_Total_VA, S2_Total_Var, null, null, null, S2_frequency, S2_AVERAGE_POWER_FACTOR, null, null, null, null, S2_L1_current, null, null, null, null, S2_L2_current, null, null, null, null, S2_L3_current, null, null, @GateWayID, @Comm_mode, Digital_IP_335, Digital_OP_335, S1_L1N_Voltage, S1_L2N_Voltage, S1_L3N_Voltage, S1_L1L2_Voltage, S1_L2L3_Voltage, S1_L3L1_Voltage, S2_L1N_Voltage, S2_L2N_Voltage, S2_L3N_Voltage, S2_L1L2_Voltage, S2_L2L3_Voltage, S2_L3L1_Voltage, S1_L1N_Voltage, S1_L1L2_Voltage, S2_L1N_Voltage, S2_L1L2_Voltage FROM OPENXML(@docHandle, '/DocumentElement/dtDataIn')
													WITH
													(Digital_IP_335 varchar(50) 'Digital_IP_335',Digital_OP_335 varchar(50) 'Digital_OP_335',S2Gen_Freq_Vol varchar(50) 'S2Gen_Freq_Vol',S1Main_Freq_Vol varchar(50) 'S1Main_Freq_Vol',S1S2_Open_Close varchar(50) 'S1S2_Open_Close',S1_frequency varchar(50) 'S1_frequency',S1_L1N_voltage varchar(50) 'S1_L1N_voltage',S1_L2N_voltage varchar(50) 'S1_L2N_voltage',S1_L3N_voltage varchar(50) 'S1_L3N_voltage',S1_L1L2_voltage varchar(50) 'S1_L1L2_voltage',S1_L2L3_voltage varchar(50) 'S1_L2L3_voltage',S1_L3L1_voltage varchar(50) 'S1_L3L1_voltage',S2_frequency varchar(50) 'S2_frequency',S2_L1N_voltage varchar(50) 'S2_L1N_voltage',S2_L2N_voltage varchar(50) 'S2_L2N_voltage',S2_L3N_voltage varchar(50) 'S2_L3N_voltage',S2_L1L2_voltage varchar(50) 'S2_L1L2_voltage',S2_L2L3_voltage varchar(50) 'S2_L2L3_voltage',S2_L3L1_voltage varchar(50) 'S2_L3L1_voltage',S1_L1_current varchar(50) 'S1_L1_current',S1_L2_current varchar(50) 'S1_L2_current',S1_L3_current varchar(50) 'S1_L3_current',S2_L1_current varchar(50) 'S2_L1_current',S2_L2_current varchar(50) 'S2_L2_current',S2_L3_current varchar(50) 'S2_L3_current',S1_Total_Watts varchar(50) 'S1_Total_Watts',S2_Total_Watts varchar(50) 'S2_Total_Watts',S1_Total_VA varchar(50) 'S1_Total_VA',S2_Total_VA varchar(50) 'S2_Total_VA',S1_Total_Var varchar(50) 'S1_Total_Var',S2_Total_Var varchar(50) 'S2_Total_Var',S1_AVERAGE_POWER_FACTOR varchar(50) 'S1_AVERAGE_POWER_FACTOR',S2_AVERAGE_POWER_FACTOR varchar(50) 'S2_AVERAGE_POWER_FACTOR',S1_L1_Watts varchar(50) 'S1_L1_Watts',S1_L2_Watts varchar(50) 'S1_L2_Watts',S1_L3_Watts varchar(50) 'S1_L3_Watts')
												End
											else
												Begin
													if(@Cntlr_Type = '9480')
														Begin
															declare @tmpmsginid varchar(100), @tmpbattopcur varchar(20)
															EXEC sp_xml_preparedocument @docHandle OUTPUT, @dtDataIn
															set @tmpbattopcur = (SELECT (CAST(ISNULL(BatteryCharger_OP_Cur, 0) as float) * 0.01) FROM OPENXML(@docHandle, '/DocumentElement/dtDataIn')
															WITH
															(BatteryCharger_OP_Cur varchar(50) 'BatteryCharger_OP_Cur'))
															--if(convert(float, @tmpbattopcur) > 50000)
															--Begin
															--	set @tmpbattopcur = 0
															--End
															--set @tmpmsginid = (select Top 1 MessageInID from rvlfMsgInHst_Techno where GateWayID = @GateWayID and OriginDateTime >= DATEADD(MINUTE, -2, GETUTCDATE()) and BatteryCharger_OP_Cur is null order by OriginDateTime desc)
															
															set @tmpmsginid = (select Top 1 MessageInID from rvlfMsgInHst_Techno where GateWayID = @GateWayID order by OriginDateTime desc)

															update rvlfMsgInHst_Techno set BatteryCharger_OP_Cur = @tmpbattopcur where MessageInID = @tmpmsginid

															--if (select BatteryCharger_OP_Cur from rvlfMsgInHst_Techno where MessageInID = @tmpmsginid) is null
															--	Begin																	
															--		update rvlfMsgInHst_Techno set BatteryCharger_OP_Cur = @tmpbattopcur where MessageInID = @tmpmsginid
															--	End
														End
													else
														Begin
															
															set @tmpmsginid = (select Top 1 BatteryCharger_OP_Cur from rvlfMsgInHst_Techno where GateWayID = @GateWayID and BatteryCharger_OP_Cur is not null order by OriginDateTime desc)

															EXEC sp_xml_preparedocument @docHandle OUTPUT, @dtDataIn
															INSERT INTO rvlfMsgInHst_Techno
															(
															BoxId, OriginDateTime, DateTimeReceived, BoxMsgInTypeId, CommInfo1, CommInfo2, ValidGps, Latitude, Longitude, Speed, Heading, CustomProp, SequenceNum, IsArmed, IsProcessed, IsArchived ,ControllerID, Alarm, Batt_Volt, Batt_Current, Batt_LstRreplacement, Chrg_Alternator, Coolant_Temp, EngineSpeed, Engine_RunTime, FuelLevel, Tot_Watts, Tot_VA, Tot_VAr, Gen_KWh, Gen_KVAh, Gen_KVArh, Gen_Freq, Gen_AvgPF, Gen_L1_PF, Gen_L1_VAr, Gen_L1_VA, Gen_L1_Watts, Gen_L1_Current, Gen_L2_PF, Gen_L2_VAr, Gen_L2_VA, Gen_L2_Watts, Gen_L2_Current, Gen_L3_PF, Gen_L3_VAr, Gen_L3_VA, Gen_L3_Watts, Gen_L3_Current, Gen_LNVolt, Gen_LLVolt, NumofStarts, Oil_Temp, Oil_Pressure, GateWayID, ComMode, Digital_IP, Digital_OP, GEN_L1_N_VOLT, GEN_L2_N_VOLT, GEN_L3_N_VOLT, GEN_L1_L2_VOLT, GEN_L2_L3_VOLT, GEN_L1_L3_VOLT, GENCURRENT_L1, GENCURRENT_L2, GENCURRENT_L3, BatteryCharger_OP_Cur, Controller_Mode, Supervisor_State, Gen_Rating)
															OUTPUT INSERTED.MessageInID into @MsgInID
															SELECT @intBoxID1, @dtOriginDateTime1, @dtDateTimeReceived1, @tiBoxMsgInTypeId1, @vcCommInfo1, @siCommInfo2, @tiValidGps1, @dLatitude1, @dLongitude1, @tiSpeed1, @siHeading, @vcCustomProp1, @bigSequenceNum, @bitIsArmed, CASE WHEN @tiValidGps = 0 THEN 1 ELSE NULL END, 0, @Cntlr_ID, @bitIsAlarm, Plant_Batt_Vol, null, null, Charge_Alt_Vol, Eng_Coolant_Temp, Eng_Speed, Eng_Run_Time, Eng_Fuel_Level, Gen_kW_Total, Gen_kVA_Total, Gen_kVAr_Total, Gen_Accum_kWh, Gen_Accum_kVAh, Gen_Accum_kVArh, Gen_Freq, Gen_pf_Average, null, null, null, GEN_L1_WATT, GENCURRENT_L1, null, null, Eng_Oil_Pressure, GEN_L2_WATT, GENCURRENT_L2, null, null, null, GEN_L3_WATT, GENCURRENT_L3, Gen_Vol_LN_Avg, Gen_Vol_LL_Avg, NUMBEROFSTARTS, null, null, @GateWayID, @Comm_mode, Digital_IP, Digital_OP, GEN_L1_N_VOLT, GEN_L2_N_VOLT, GEN_L3_N_VOLT, GEN_L1_L2_VOLT, GEN_L2_L3_VOLT, GEN_L1_L3_VOLT, GENCURRENT_L1, GENCURRENT_L2, GENCURRENT_L3, @tmpmsginid, @Cntlr_Mode, @Supvsr_State, (Cast(ISNULL(Gen_Rating, 0) as float) * 0.001) FROM OPENXML(@docHandle, '/DocumentElement/dtDataIn')
															WITH
															(Gen_Vol_LL_Avg varchar(50) 'Gen_Vol_LL_Avg',Gen_Vol_LN_Avg varchar(50) 'Gen_Vol_LN_Avg',Gen_Vol_LL_Phase_Imb varchar(50) 'Gen_Vol_LL_Phase_Imb',Gen_Vol_LN_Phase_Imb varchar(50) 'Gen_Vol_LN_Phase_Imb',Gen_Freq varchar(50) 'Gen_Freq',Gen_kW_Total varchar(50) 'Gen_kW_Total',Gen_kVA_Total varchar(50) 'Gen_kVA_Total',Gen_kVAr_Total varchar(50) 'Gen_kVAr_Total',Gen_pf_Average varchar(50) 'Gen_pf_Average',Gen_Accum_kWh varchar(50) 'Gen_Accum_kWh',Gen_Accum_kVAh varchar(50) 'Gen_Accum_kVAh',Gen_Accum_kVArh varchar(50) 'Gen_Accum_kVArh',Plant_Batt_Vol varchar(50) 'Plant_Batt_Vol',Eng_Speed varchar(50) 'Eng_Speed',Eng_Oil_Pressure varchar(50) 'Eng_Oil_Pressure',Eng_Coolant_Temp varchar(50) 'Eng_Coolant_Temp',Charge_Alt_Vol varchar(50) 'Charge_Alt_Vol',Eng_Fuel_Level varchar(50) 'Eng_Fuel_Level',Eng_Run_Time varchar(50) 'Eng_Run_Time',Gen_Current_Avg varchar(50) 'Gen_Current_Avg',Gen_Rating varchar(50) 'Gen_Rating',Aux_Fuel_Sender varchar(50) 'Aux_Fuel_Sender',Mains_Vol_LL_Avg varchar(50) 'Mains_Vol_LL_Avg',Mains_Vol_LN_Avg varchar(50) 'Mains_Vol_LN_Avg',Mains_Vol_LL_Phase_Imb varchar(50) 'Mains_Vol_LL_Phase_Imb',Mains_Vol_LN_Phase_Imb varchar(50) 'Mains_Vol_LN_Phase_Imb',Mains_Freq varchar(50) 'Mains_Freq',Mains_kW_Total varchar(50) 'Mains_kW_Total',Mains_kVA_Total varchar(50) 'Mains_kVA_Total',Mains_kVAr_Total varchar(50) 'Mains_kVAr_Total',Mains_pf_Average varchar(50) 'Mains_pf_Average',Mains_Accum_kWh varchar(50) 'Mains_Accum_kWh',Mains_Accum_kVAh varchar(50) 'Mains_Accum_kVAh',Mains_Accum_kVArh varchar(50) 'Mains_Accum_kVArh',Mains_Current_Avg varchar(50) 'Mains_Current_Avg',Digital_IP varchar(50) 'Digital_IP',Digital_OP varchar(50) 'Digital_OP',GEN_L1_N_VOLT varchar(50) 'GEN_L1_N_VOLT',GEN_L2_N_VOLT varchar(50) 'GEN_L2_N_VOLT',GEN_L3_N_VOLT varchar(50) 'GEN_L3_N_VOLT',GEN_L1_L2_VOLT varchar(50) 'GEN_L1_L2_VOLT',GEN_L2_L3_VOLT varchar(50) 'GEN_L2_L3_VOLT',GEN_L1_L3_VOLT varchar(50) 'GEN_L1_L3_VOLT',GENCURRENT_L1 varchar(50) 'GENCURRENT_L1',GENCURRENT_L2 varchar(50) 'GENCURRENT_L2',GENCURRENT_L3 varchar(50) 'GENCURRENT_L3',GEN_L1_WATT varchar(50) 'GEN_L1_WATT',GEN_L2_WATT varchar(50) 'GEN_L2_WATT',GEN_L3_WATT varchar(50) 'GEN_L3_WATT',BatteryCharger_OP_Cur varchar(50) 'BatteryCharger_OP_Cur',NUMBEROFSTARTS varchar(50) 'NUMBEROFSTARTS')
														End
												End
										END
									SELECT @uiMsgInID = uiMsgInID FROM @MsgInID
									--end
									PRINT 'BoxId Table'
									/******************************************************************************/
									/****************************Box ID Table**************************************/
									-- Inserts into the rvlfBoxID if sensor mask is available in the information.
									--IF @vcSensorMask IS NOT NULL AND LEN(@vcSensorMask) = 8 AND @tiBoxMsgInTypeId NOT IN (51,121) AND @tiValidGps <>2
									--IF @tiBoxMsgInTypeId1 IN (1)
									-- BEGIN
									--UPDATE rvlfBoxId SET
									-- LastLatitude = CASE WHEN @tiValidGps1 = 0 THEN @dLatitude1 ELSE LastLatitude END,
									-- LastLongitude = CASE WHEN @tiValidGps1 = 0 THEN @dLongitude1 ELSE LastLongitude END,
									-- LastCommunicatedDateTime = @dtDateTimeReceived1
									--WHERE BoxId = @intBoxID1
									--End
									--IF @tiBoxMsgInTypeId1 IN (1,8)
									--	BEGIN
									--		if @tiBoxMsgInTypeId1 IN (1)
									--			begin
									--				DECLARE @dtLastValidDateTime DateTime=(SELECT LastValidDateTime FROM rvlfBoxId WHERE BoxId = @intBoxID1)
									--				-- Checks if the last information exists for the box, if so updates else inserts
									--				IF @dtOriginDateTime1 >= @dtLastValidDateTime
									--					BEGIN
									--						UPDATE rvlfBoxId SET BoxArmed = 1, LastValidDateTime = CASE WHEN @tiValidGps = 0 THEN @dtOriginDateTime ELSE LastValidDateTime END,
									--						LastLatitude = @dLatitude,LastLongitude = @dLongitude,LastSpeed = @tiSpeed,
									--						LastCommunicatedDateTime = @dtDateTimeReceived,LastSensorMask = @vcSensorMask,
									--						LastStatusDateTime = @dtOriginDateTime, LastStreetAddress = CASE WHEN @tiValidGps = 0 THEN NULL ELSE LastStreetAddress END,
									--						NearestLandmark = CASE WHEN @tiValidGps = 0 THEN NULL ELSE NearestLandmark END, Heading = @siHeading, MessageInId = @uiMsgInID, GateWayID = @GateWayID WHERE BoxId = @intBoxID1
									--					END
									--			END
									--		Else if @tiBoxMsgInTypeId1 IN (8)
									--			begin
									--				UPDATE rvlfBoxId SET LastCommunicatedDateTime = @dtOriginDateTime1 WHERE BoxId = @intBoxID1
									--			end
									--		ELSE IF(@dtLastValidDateTime IS NULL OR @dtLastValidDateTime='')
									--			BEGIN
									--				DELETE FROM rvlfBoxId WHERE BoxId=@intBoxID1
									--				INSERT INTO rvlfBoxId
									--				(
									--				BoxId, BoxArmed, LastValidDateTime, LastLatitude, LastLongitude,
									--				LastSpeed, LastCommunicatedDateTime, LastSensorMask,
									--				OrganizationId, LastStatusDateTime, Heading , LastStreetAddress ,
									--				NearestLandmark, MessageInId
									--				)
									--				VALUES
									--				(
									--				@intBoxID1, @bitIsArmed, @dtLastValidGPSTime, @dLatitude1, @dLongitude1,
									--				@tiSpeed1, @dtDateTimeReceived1, @vcSensorMask,
									--				@bigOrganizationID, @dtOriginDateTime1, @siHeading,
									--				CASE WHEN @tiValidGps1 = 0 THEN NULL ELSE 'N/A' END,
									--				CASE WHEN @tiValidGps1 = 0 THEN NULL ELSE 'N/A' END,
									--				@uiMsgInID
									--				)
									--			END
									--	END
									--IF @tiBoxMsgInTypeId1 IN (8)
									--	BEGIN
									--		declare @DIP varchar(15)=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'Input=',';')
									--		update rvlfBoxId set LastSensorMask=@DIP where BoxId = @intBoxID1
									--	end

									DECLARE @dtLastValidDateTime DateTime=(SELECT LastValidDateTime FROM rvlfBoxId WHERE BoxId = @intBoxID1)
													-- Checks if the last information exists for the box, if so updates else inserts
													--IF @dtOriginDateTime1 >= @dtLastValidDateTime
													--	BEGIN
													--		UPDATE rvlfBoxId SET BoxArmed = 1, LastValidDateTime = @dtOriginDateTime1,
													--		LastLatitude = @dLatitude,LastLongitude = @dLongitude,LastSpeed = @tiSpeed,
													--		LastCommunicatedDateTime = @dtDateTimeReceived,LastSensorMask = @vcSensorMask,
													--		LastStatusDateTime = @dtOriginDateTime, LastStreetAddress = CASE WHEN @tiValidGps = 0 THEN NULL ELSE LastStreetAddress END,
													--		NearestLandmark = CASE WHEN @tiValidGps = 0 THEN NULL ELSE NearestLandmark END, Heading = @siHeading, MessageInId = @uiMsgInID, GateWayID = @GateWayID WHERE BoxId = @intBoxID1
													--		END
													UPDATE rvlfBoxId SET BoxArmed = 1, LastValidDateTime = @dtOriginDateTime1,
															LastLatitude = @dLatitude,LastLongitude = @dLongitude,LastSpeed = @tiSpeed,
															LastCommunicatedDateTime = @dtDateTimeReceived,LastSensorMask = @vcSensorMask,
															LastStatusDateTime = @dtOriginDateTime, LastStreetAddress = CASE WHEN @tiValidGps = 0 THEN NULL ELSE LastStreetAddress END,
															NearestLandmark = CASE WHEN @tiValidGps = 0 THEN NULL ELSE NearestLandmark END, Heading = @siHeading, MessageInId = @uiMsgInID, GateWayID = @GateWayID WHERE BoxId = @intBoxID1

														
									/******************************************************************************/
									/***********For Alarm logging******************/
									if(@dtAlarm is not null and @bitIsAlarm = 1)
										Begin
											PRINT 'Alarm Table.'
											declare @tblAlarm table(SNo int identity(1,1), BoxID varchar(25), AlarmType varchar(50), AlarmLevel varchar(50))
											EXEC sp_xml_preparedocument @docHandle OUTPUT, @dtAlarm
											Insert into @tblAlarm(BoxID, AlarmType, AlarmLevel)
											SELECT @intBoxID1, AlarmID, AlarmLevel FROM OPENXML(@docHandle, '/DocumentElement/dtAlarm')
											WITH
											(AlarmID varchar(50) 'AlarmID',AlarmLevel varchar(50) 'AlarmLevel')
											Insert into rvlfAlarm(DateTimeCreated, BoxId, AlarmType, AlarmLevelId, Description, Lat, Long, IsClosed, CustomProp, MessageInID, ControllerID, AlarmRepeatFlag)
											select @dtOriginDateTime, @intBoxID1, @tiBoxMsgInTypeId1, AlarmLevel, AlarmType, @dLatitude, @dLongitude, 0, @vcCustomProp, @uiMsgInID, @intBoxID1, 0 from @tblAlarm where AlarmType not in (select Description from rvlfAlarm where BoxId = @intBoxID1 and IsClosed = 0)
											Insert into rvlfAlarmTransaction(AlarmId, DateTimeCreated, BoxId, AlarmType, AlarmLevelId, Description, Lat, Long, IsClosed, CustomProp, MessageInID, ControllerID, AlarmRepeatFlag)
											select AlarmId, DateTimeCreated, a.BoxId, @tiBoxMsgInTypeId1, AlarmLevelId, Description, Lat, Long, IsClosed, CustomProp, MessageInID, ControllerID, 0 from rvlfAlarm a inner join @tblAlarm b on a.BoxId = b.BoxID and a.Description = b.AlarmType and a.IsClosed = 0
											UPDATE rvlfBoxId SET DeviceStatus = (select Top 1 AlarmLevel from @tblAlarm) WHERE BoxId = @intBoxID1
											Update rvlfAlarm set IsClosed = 1 where BoxId = @intBoxID1 and Description not in (select AlarmType from @tblAlarm) and IsClosed = 0
											EXEC rvlf_sp_LogNotificaitons_ForAlarms NULL,@uiMsgInID,@tiBoxMsgInTypeId1
											PRINT 'Alarm Table end'
										End
									else if (@bitIsAlarm = 0 or @bitIsAlarm is null)
										Begin											
											if @Cntlr_Type = '32845'
												Begin								
												UPDATE rvlfBoxId SET DeviceStatus = case when @Alarm_Lvl = '0' then 1 else @Alarm_Lvl end WHERE BoxId = @intBoxID1
													if @Alarm_Lvl = 0 or @Alarm_Lvl = 1 
														Begin															
															Update rvlfAlarm set IsClosed = 1, DateTimeClosed = @dtOriginDateTime, ClosedBy = 0 where BoxId = @intBoxID1
														End
													else if @tiBoxMsgInTypeId1 = 2
													Begin
														Update rvlfAlarm set IsClosed = 1, DateTimeClosed = @dtOriginDateTime, ClosedBy = 0 where BoxId = @intBoxID1
													End
													else if @tiBoxMsgInTypeId1 = 11
														Begin															
															Update rvlfAlarm set IsClosed = 1, DateTimeClosed = @dtOriginDateTime, ClosedBy = 0 where BoxId = @intBoxID1
														End
												End
											else
												Begin
													Update rvlfAlarm set IsClosed = 1, DateTimeClosed = @dtOriginDateTime, ClosedBy = 0 where BoxId = @intBoxID1
													UPDATE rvlfBoxId SET DeviceStatus = 1 WHERE BoxId = @intBoxID1
												End
										End
									--if (@tiBoxMsgInTypeId1 =8 or @bitIsAlarm=1)--CHARINDEX('_R=1',@vcCustomProp1,0) <> 0)
									-- Begin
									-- Declare @msgIDLastPacket uniqueidentifier
									-- Select top 1 @msgIDLastPacket = messageinid from rvlfMsgInHst h where boxid= @intBoxID1 and BoxMsgInTypeId in (@tiBoxMsgInTypeId1) and h.MessageInID != @uiMsgInID
									-- order by OriginDateTime desc
									-- PRINT 'Alarm Table 1'
									-- EXEC rvlf_sp_AlarmMessageReceived_vxl @vcCustomProp1,@tiBoxMsgInTypeId1,0,0,@intBoxID1,@dtOriginDateTime1,@uiMsgInID,@msgIDLastPacket
									-- END
									-- Else
									-- Begin
									-- IF(@tiBoxMsgInTypeId1 in(1))
									-- BEGIN
									-- Declare @CurDateTimeForAlarm Datetime = GETUTCDATE()
									-- UPDATE [rvlfAlarm] SET [IsClosed]=1,[ClosedBy]=0,[DateTimeClosed] = @CurDateTimeForAlarm WHERE BoxID=@intBoxID1
									-- AND ([IsClosed] IS NULL OR [IsClosed] = 0 OR [IsClosed]='') and AlarmType=@tiBoxMsgInTypeId1
									-- update rvlfBoxId set ControllerID= null where BoxId=@intBoxID1
									-- --EXEC rvlf_sp_LogNotificaitons_ForAlarms @CurDateTimeForAlarm,NULL,@tiBoxMsgInTypeId1
									-- END
									-- End
									-- IF @bitIsAlarm =1
									-- BEGIN
									-- INSERT INTO rvlfAlarm(AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,ControllerID,CustomProp, MessageInID)
									-- VALUES(@tiAlarmLevelID,@dtOriginDateTime,@intBoxID1,1,@dLatitude,@dLongitude,
									-- '', CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END, @intBoxID1,@vcCustomProp, @uiMsgInID )
									-- END
									/*********************************************/
									-- if CHARINDEX('IsAlarm=1',@vcCustomProp1,0) <> 0 --and @tiBoxMsgInTypeID in (4,7,24)
									-- Begin
									--EXEC rvlf_sp_LogNotificaitons_ForAlarms @msgIDLastPacket,@uiMsgInID,@tiBoxMsgInTypeId1
									-- End
									/******************************************************************************/
									/***************************Communication Processing***************************/
									-- Inserts the communication information based on the communication information.
									IF NOT EXISTS(SELECT commAddressValue FROM rvlfBoxCommInfo WHERE BoxId = @intBoxID1 AND CommAddressValue =@vcNewIP)
										BEGIN
											DELETE FROM rvlfBoxCommInfo WHERE BoxId = @intBoxID1
											INSERT INTO rvlfBoxCommInfo(BoxID,CommAddressTypeId,CommAddressValue)
											SELECT @intBoxID1,CommAddressTypeID,@vcNewIP FROM rvlfCommModeAddressType
											WHERE CommModeId = @tiCommModeId
										END
									/******************************************************************************/
									PRINT 'ACK / Response'
									/*************************Message out Processing (ACK / Response)**************/
									IF (@dtSentDateTime1 IS NOT NULL or (@tiBoxMsgInTypeId=20 or @tiBoxMsgInTypeId=14))
										BEGIN
											-- select * from rvlfBoxCmdOutType
											declare @mode char(2)= dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'RangeMode=',';')
											UPDATE TOP (1) rvlfMsgOutHst SET Acknowledged = dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'Status=',';'), MessageInID= @uiMsgInID WHERE BoxId = @intBoxID1
											AND SentDateTime between DATEADD(SECOND,-10,@dtOriginDateTime1) and @dtOriginDateTime1 and
											BoxCmdOutTypeId= case when @mode='F' then 1 when @mode='T' then 2 when @mode='E' then 14 when @mode='P' then 27 else 0 end and MessageInID is null
											declare @RCustomProp varchar(1000)
											select @RCustomProp=CustomProp from rvlfMsgOutHst WHERE BoxId = @intBoxID1 and MessageInID= @uiMsgInID
											if(@mode='F') 
												begin
													--Update reporting interval and speed threshold to master table
													UPDATE v SET v.RptInterval=@RCustomProp--dbo.rvlf_fn_GetParamValueWithIndex(REPLACE(@RCustomProp,@intBoxID1+'|',@intBoxID1+'|F'),'F','|')
													,[Modified DateTime]=GETDATE()
													FROM rvlfVehicle v
													INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId
													INNER JOIN rvlfMsgOutHst H ON H.BoxId=va.BoxId
													WHERE H.BoxId = @intBoxID1 AND H.BoxCmdOutTypeId IN (1)
												end
											else if exists (select * from rvlfParamRange where Boxid=@intBoxID1)
												begin
													if(@mode='T') 
														begin PRINT 'ACK T'
															update rvlfParamRange set T1_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T1MIN','|'),T1_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T1MAX','|')
															,T2_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T2MIN','|'),T2_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T2MAX','|')
															,T3_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T3MIN','|'),T3_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T3MAX','|')
															,T4_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T4MIN','|'),T4_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T4MAX','|')
															,T5_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T5MIN','|'),T5_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T5MAX','|'),ModifyDate=GETutcDATE() where Boxid=@intBoxID1
														end
													else if (@mode='P')
														begin PRINT 'ACK P'
															update rvlfParamRange set P3_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P3Mn','|'),P3_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P3Mx','|')
															,P4_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P4Mn','|'),P4_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P4Mx','|')
															,P5_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P5Mn','|'),P5_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P5Mx','|')
															,P6_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P6Mn','|'),P6_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P6Mx','|')
															,P7_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P7Mn','|'),P7_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P7Mx','|')
															,P8_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P8Mn','|'),P8_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P8Mx','|')
															,P9_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P9Mn','|'),P9_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P9Mx','|')
															,P10_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P10Mn','|'),P10_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P10Mx','|')
															,P11_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P11Mn','|'),P11_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P11Mx','|')
															,DPs_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPsMIN','|'),DPs_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPsMAX','|')
															,DPp_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPpMIN','|'),DPp_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPpMAX','|')
															,DPp1_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPp1MIN','|'),DPp1_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPp1MAX','|'),ModifyDate=GETDATE() where Boxid=@intBoxID1
														end
													else if (@mode='E') 
														begin PRINT 'ACK E'
															update rvlfParamRange set V1_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'V1Mn','|'),V1_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'V1Mx','|')
															,C1_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C1Mn','|'),C1_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C1Mx','|')
															,C2_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C2Mn','|'),C2_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C2Mx','|')
															,C3_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C3Mn','|'),C3_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C3Mx','|')
															,C4_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C4Mn','|'),C4_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C4Mx','|')
															,C5_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C5Mn','|'),C5_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C5Mx','|')
															,C6_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C6Mn','|'),C6_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C6Mx','|')
															,C7_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C7Mn','|'),C7_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C7Mx','|')
															,C8_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C8Mn','|'),C8_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C8Mx','|')
															,C9_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C9Mn','|'),C9_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C9Mx','|')
															,C10_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C10Mn','|'),C10_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C10Mx','|')
															,C11_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C11Mn','|'),C11_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C11Mx','|')
															,C12_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C12Mn','|'),C12_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C12Mx','|')
															,C13_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C13Mn','|'),C13_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C13Mx','|')
															,C14_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C14Mn','|'),C14_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C14Mx','|')
															,C15_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C15Mn','|'),C15_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C15Mx','|')
															,C16_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C16Mn','|'),C16_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C16Mx','|')
															,C17_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C17Mn','|'),C17_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C17Mx','|')
															,C18_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C18Mn','|'),C18_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C18Mx','|')
															,C19_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C19Mn','|'),C19_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C19Mx','|')
															,RC1=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC1_','|'),[RC2]=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC2_','|')
															,RC3=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC3_','|'),[RC4]=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC4_','|')
															,RC5=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC5_','|'),RC6=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC6_','|')
															,RC7=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC7_','|'),RC8=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC8_','|')
															,RC9=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC9_','|'),RC10=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC10_','|')
															,RC11=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC11_','|'),RC12=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC12_','|')
															,RC13=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC13_','|'),RC14=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC14_','|')
															,RC15=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC15_','|'),RC16=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC16_','|')
															,RC17=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC17_','|'),RC18=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC18_','|')
															,RC19=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC19_','|'),ModifyDate=GETutcDATE()
															where Boxid=@intBoxID1
														end
													else if (@mode='A' or @mode='C')
														begin
															declare @VehiclePlanId bigint,@ServiceDetailsID bigint,@planID bigint
															SELECT top 1 @VehiclePlanId=vm.VehiclePlanId,@ServiceDetailsID=vm.ServiceDetailsId,@planID=vp.PlanId
															FROM rvlfVehicleMaintenanceService vm
															INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId
															INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId
															INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId
															inner join rvlfMAKDevices D on D.VehicleId=v.VehicleId where isnull(vm.RunningSerial,0)=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'Sno=',';') and D.BoxId=@intBoxID1 order by vm.ServiceDetailsId desc
															UPDATE TOP (1) rvlfMsgOutHst SET Acknowledged = case when @mode='C' then '2' else dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'Status=',';') end, MessageInID= @uiMsgInID,isCommentSentStatus=4,isCommentSentUpdateDate=GETDATE() WHERE BoxId = @intBoxID1 and SequenceNum=@VehiclePlanId
															and SentDateTime=(select top 1 SentDateTime from rvlfMsgOutHst where BoxId = @intBoxID1 and SequenceNum=@VehiclePlanId order by SentDateTime desc)
															if(@mode='C')
																begin
																	--if(dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'user=',';')<>'')
																	-- begin
																	-- if(exists(Select UserId from rvlfUser where UserName=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'user=',';')))
																	-- begin
																	-- Select @CloseUserID=UserId from rvlfUser where UserName=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'user=',';')
																	-- end
																	-- else
																	-- begin
																	-- Select @CloseUserID=UserId from rvlfUser where UserName=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'user=',';')
																	-- end
																	-- end
																	declare @Readingvalues bigint=0,@closeName varchar(200) ='Closed by: ' + dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'user=',';')
																	Select @Readingvalues=CurrentOdometerReading from rvlfVehicleCurrentReadings where VehicleId in (Select VehicleId from rvlfVehicleAssignment where BoxId=@intBoxID1)
																	declare @p6 xml
																	set @p6=convert(xml,N'<DocumentElement/>')
																	declare @exeDate datetime=cast(getdate() as date)
																	declare @exeScheduleOnDate datetime=getdate()
																	exec rvlf_sp_UpdateMaintenanceServiceDetails @bigQueryingUser=N'1',@bigServiceDetailsId=@ServiceDetailsID,@tiStatus=N'1',@bigCurrentReading=@Readingvalues,@dtExecutionOnDate=@exeDate,@tblMaintenanceServiceDetails=@p6,@IsDueOn=N'1',@dtScheduleOnDate=@exeScheduleOnDate,@vcComments=@closeName,@ModifiedBy=N'1',@ModifiedDateTime=@exeScheduleOnDate
																	INSERT INTO rvlfMaintenanceServiceDetails(ServiceDetailsId, ServiceId, ServicedOn, ServiceCost, ServicedBy)
																	SELECT @ServiceDetailsID, ms.ServiceId, getdate(), ps.PlannedCost,'1' FROM rvlfMaintenanceService ms
																	INNER JOIN rvlfMaintenancePlanServices ps ON ps.ServiceId = ms.ServiceId
																	LEFT OUTER JOIN rvlfMaintenanceServiceDetails sd ON sd.ServiceId = ms.ServiceId AND sd.ServiceDetailsId = @ServiceDetailsID
																	WHERE ps.PlanId = @planID
																end
														end
												end
											else
												begin PRINT 'ACK '
													insert into rvlfParamRange (boxid,T1_Min,T1_Max,T2_Min,T2_Max,T3_Min,T3_Max,T4_Min,T4_Max,P1_Min,P1_Max,P2_Min,P2_Max,P3_Min,P3_Max,P4_Min,P4_Max,P5_Min,P5_Max,V1_Min,V1_Max,C1_Min,C1_Max,C2_Min,C2_Max
													,DPs_Min,DPs_Max,DPp_Min,DPp_Max,DPp1_Min,DPp1_Max,RC1,[RC2],IsActive,CreatedDate,CreatedBy)
													values (@intBoxID1,
													dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T1MIN','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T1MAX','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T2MIN','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T2MAX','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T3MIN','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T3MAX','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T4MIN','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T4MAX','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P1Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P1Mx','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P2Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P2Mx','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P3Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P3Mx','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P4Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P4Mx','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P5Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P5Mx','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'V1Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'V1Mx','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C1Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C1Mx','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C2Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C2Mx','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPsMIN','|'),dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPsMAX','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPpMIN','|'),dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPpMAX','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPp1MIN','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPp1MAX','|')
													,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC1_','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC2_','|'),1,getutcdate(),1)
												end
										END
									--PRINT 'Welcome 4'
									IF @trancount = 0
									COMMIT;
									-- COMMIT TRAN
								END TRY
							BEGIN CATCH
							DECLARE @error int, @message varchar(4000), @xstate int;
							SELECT @error = ERROR_NUMBER(),
							@message = ERROR_MESSAGE(),
							@xstate = XACT_STATE();
							if @xstate = -1
							ROLLBACK TRAN;
							if @xstate = 1 and @trancount = 0
							ROLLBACK TRAN;
							if @xstate = 1 and @trancount > 0
							ROLLBACK TRANSACTION MessageTransaction;
							--ROLLBACK TRAN
							SET @ErrorMessage = 'An Error occured during insert of the packet message : ' + @message
							RAISERROR( @ErrorMessage,16,1)
							END CATCH
						END--CONDITION 02 END
				END
		END --CONDITION 01 END
	/******************************************************************************/
	SET NOCOUNT OFF
end
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateMessageReceived_VXL]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateMessageReceived_VXL]                                                  
  @intBoxID varchar(10)=null,                                                  
  @dtOriginDateTime datetime,                                                  
  @dtDateTimeReceived datetime,                                                   
  @vcCommMode varchar(100),                                                    
  @tiBoxMsgInTypeId TINYINT = null,                                                    
  @vcBoxProtocolTypeName varchar(50) = null,                                                  
  @vcCommInfo1 varchar(15),           
  @siCommInfo2 int ,           
  @tiValidGps smallint = 2,           
  @dLatitude decimal(10,6) = 0,          
  @dLongitude decimal(10,6) = 0,          
  @tiSpeed smallint = 0,           
  @siHeading  smallint = 0,          
  @vcSensorMask varchar(8) = null,          
  @vcCustomProp varchar(max)= null,          
  @bigSequenceNum bigint = null,          
  @bitIsArmed bit = null,           
  @tiPriority tinyint = null,          
  @bitIsAlarm bit =0,          
  @dtSentDateTime datetime = null,                                                  
  @bitIgnitionStatus bit = null,                                                  
  @bigOdoMeterReading bigint = null,                                          
  @bitIsTrinetraApp bit = 0,                                          
  @ModelNo VARCHAR(256) = null,                                          
  @odoValue_app varchar(6) = null,                                          
  @AlarmDesc_app varchar(256) = null,                                          
  @IsPrefAck bit = 0   , 
  @dtSeconday XML = NULL,
  @dtPrimary XML = NULL,
  @dtFiberCompactors XML = NULL
AS                                                  
/*********************************************************************************************************************************/                             
-- Name  : [rvlf_sp_UpdateMessageReceived]                                                  
-- Description : To insert the messages that is sent to the device                                                
-- Author : V.Narayanasamy                                                
-- Company  : Angler Technologies                                                
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                                
/*********************************************************************************************************************************/                             
BEGIN                                                
SET NOCOUNT ON         
 Declare @intBoxID1 varchar(10)=@intBoxID,  @dtOriginDateTime1 datetime=@dtOriginDateTime,  @dtDateTimeReceived1 datetime=@dtDateTimeReceived, 
 @tiBoxMsgInTypeId1 TINYINT = @tiBoxMsgInTypeId,@tiValidGps1 smallint = @tiValidGps,  @dLatitude1 decimal(10,6) = @dLatitude,
 @dLongitude1 decimal(10,6) = @dLongitude,  @tiSpeed1 smallint = @tiSpeed, @vcCustomProp1 varchar(max)= @vcCustomProp,
 @dtSentDateTime1 datetime = @dtSentDateTime   
 DECLARE @docHandle int 
 declare @MessageInID uniqueidentifier=null                    
IF (@tiBoxMsgInTypeId1 <> 52)                                                  
 BEGIN--CONDITION 01 START          
  DECLARE @bigOrganizationID bigint=(SELECT OrganizationID FROM rvlfBoxId WHERE BoxId = @intBoxID1)
  DECLARE @tintSensor tinyint=CASE WHEN @vcCustomProp1 LIKE '%SENSOR_NUM=%' THEN  
   CAST(dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'SENSOR_NUM=',';')
   --SUBSTRING(@vcCustomProp1,CHARINDEX('%SENSOR_NUM=%',@vcCustomProp1,0)+12,(CHARINDEX(';',@vcCustomProp1,
   --(CHARINDEX('%SENSOR_NUM=%',@vcCustomProp1,0)))-(CHARINDEX('%SENSOR_NUM=%',@vcCustomProp1,0)+12)))
   AS TINYINT) ELSE 0 END
 
 DECLARE @tintBoxgnore tinyint=(SELECT COUNT(igid) FROM rvlfboxignoremsgs WHERE BOXID =@intBoxID1 AND 
  BOXMSGINTYPEID=@tiBoxMsgInTypeId1 AND SENSORNO=@tintSensor)                        
  IF(@tintBoxgnore=0)
DECLARE @tintOrgIgnore tinyint=(SELECT count(igid) FROM rvlforgignoremsgs WHERE ORGID =@bigOrganizationID        
   AND BOXMSGINTYPEID=@tiBoxMsgInTypeId1 AND SENSORNO=@tintSensor)                                               
  --CHECK THE IGNORE MESSAGES BASED ON THE RVLFBOXIGNOREMSGS TABLE            
  IF(@tintBoxgnore=0)                                                
  IF(@tintOrgIgnore=0)           
  BEGIN                                                
   IF Exists (SELECT MessageInID FROM rvlfMsgInHst WHERE BoxId = @intBoxID1  AND BoxMsgInTypeId = @tiBoxMsgInTypeId1               
    AND OriginDateTime = @dtOriginDateTime1   ) --and CustomProp=@vcCustomProp1)  
   BEGIN                           
    RAISERROR('Data Integrity Violation', 16,1)                                                  
   END                                                  
   ELSE                                                
   BEGIN--CONDITION 02 START         
     -- Local variables to hold the intermediate results                                                  
DECLARE @ErrorMessage varchar(3000)                                                    
     DECLARE @intBoxProtocolTypeId int       
     DECLARE @tiServiceID tinyint       
     DECLARE @tiCommModeId tinyint       
     DECLARE @MsgInID TABLE ( uiMsgInID uniqueidentifier)       
     DECLARE @uiMsgInID1 uniqueidentifier       
     DECLARE @uiMsgInID uniqueidentifier       
     DECLARE @vcNewIP varchar(25)       
     SET @vcNewIP = @vcCommInfo1 + ':'+ CAST(@siCommInfo2 AS varchar(5))       
     DECLARE @dtLastValidGPSTime datetime       
     DECLARE @bitCreateAlarm bit       
     DECLARE @tiAlarmLevelID tinyint       
     DECLARE @bigGeoZoneID bigint       
     DECLARE @vcAlarmLevelName varchar(30)       
       
    /********** demo*************/                                                
    DECLARE @DemoMsgInID TABLE ( uiDemoMsgInID uniqueidentifier)                                                
    DECLARE @uiDemoMsgInID uniqueidentifier                                                
    DECLARE @vcOldIP varchar(25)                                                 
    SET @vcNewIP = @vcCommInfo1 + ':'+ CAST(@siCommInfo2 AS varchar(5))                                                
    --DECLARE @bitCanNotify bit                                                
    SET @dtLastValidGPSTime = @dtOriginDateTime1                                                 
    DECLARE @IsAddressAlreadyAvailable bit = 0                                                
    DECLARE @vcStreetAddress varchar(250)                                                
 DECLARE @vcNearestLandmark varchar(300)                                         
    /*********end *****************/  
                  
     SET @dtLastValidGPSTime = @dtOriginDateTime1                                                   
      --update the origindatetime if origindatetime is greater then current date time      
     IF(@dtOriginDateTime1>CONVERT(datetime,CONVERT(varchar(19),SYSUTCDATETIME())))                                                  
       BEGIN                                               
 SET @dtOriginDateTime1=CONVERT(datetime,CONVERT(varchar(19),SYSUTCDATETIME()))                                                  
       END                                                  
                                                       
     --update the datetimerecived if datetimerecived is greater then origindatetime                                                   
    IF(@dtOriginDateTime1>=@dtDateTimeReceived1)               
       BEGIN               
       SET @dtDateTimeReceived1=DATEADD(S,2,@dtOriginDateTime1)                  
       END                                  
       
     --GET THE PROTOCOLID BASED ON THE PROTOCOL NAME                               
     SELECT @intBoxProtocolTypeId = isnull(BoxProtocolTypeId,1) FROM rvlfBoxProtocolType WHERE BoxProtocolTypeName = isnull(@vcBoxProtocolTypeName,'RVLTv1.0')       
        --GET THE COMMAND MODE ID BASED ON THE COMMANDMODE NAME                
     SELECT @tiCommModeId = CommModeId FROM rvlfCommMode WHERE CommModeName = @vcCommMode                                                  
                                                      
        --GET THE PROTOCOLID BASED ON THE PROTOCOL NAME                                                   
     SELECT @tiServiceID = ServiceID FROM rvlfServices WHERE CommModeId = @tiCommModeId      
                                                    
    /***************************Severity Settings**********************************/                    
    -- Checks if the message has the severity settings such that an alarm has to be created.                                               
    IF EXISTS (SELECT BoxId FROM rvlfBoxMsgSeverity WHERE BoxId=@intBoxID1 AND BoxMsgInTypeId = @tiBoxMsgInTypeId1)             
     BEGIN                                                  
        DECLARE @intDuration int = 1                                                   
        IF @tiBoxMsgInTypeId1 = 9                                                   
         BEGIN                               
        SET @intDuration = CAST (SUBSTRING (@vcCustomProp1, CHARINDEX(':',@vcCustomProp1,1)+1,                                          
         CHARINDEX(';',@vcCustomProp1)-1 -CHARINDEX(':',@vcCustomProp1,1)) as Int)
         END                                                  
        IF @intDuration > 0                              
       BEGIN    
        SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.AlarmLevelID, @vcAlarmLevelName = s.AlarmLevelName      
        FROM rvlfBoxMsgSeverity bs                  
          INNER JOIN rvlfSeverity s On bs.AlarmLevelID = s.AlarmLevelId                                                 
         WHERE bs.BoxId = @intBoxID1 AND bs.BoxMsgInTypeId = @tiBoxMsgInTypeId1                                                   
          END                                                  
     END                                                  
     ELSE                                                  
     BEGIN                                                  
      SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.DefaultAlarmLevel,@vcAlarmLevelName = s.AlarmLevelName      
       FROM rvlfBoxProtocolMsgInType bs  
        INNER JOIN rvlfSeverity s On bs.DefaultAlarmLevel = s.AlarmLevelId                                                 
       WHERE bs.BoxMsgInTypeId = @tiBoxMsgInTypeId1                                                   
     END                                                
                   
                                                     
       IF @tiBoxMsgInTypeId1 = 11 
     BEGIN         
       DECLARE @tiSensorID tinyint,@intSensorStateStart int,@intSensorStateEnd int,                                                
      @vcSensorStatus varchar(10),@bitIsOn bit                                                
       SET @tiSensorID = CAST(SUBSTRING(@vcCustomProp1,CHARINDEX('=',@vcCustomProp1)+1,1) As tinyint)      
       SET @intSensorStateStart = CHARINDEX('=',@vcCustomProp1,LEN('SENSOR_NUM=')+1)                               
       SET @intSensorStateEnd = CHARINDEX(';',@vcCustomProp1,15)               
       SET @vcSensorStatus =     
 CASE WHEN @vcCustomProp1 LIKE '%SENSOR_STATUS=%' THEN 
	  dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'SENSOR_STATUS=',';') 
	 -- SUBSTRING(@vcCustomProp1,CHARINDEX('SENSOR_STATUS=',@vcCustomProp1,0)+14,      
     --  (CHARINDEX(';',@vcCustomProp1,(CHARINDEX('SENSOR_STATUS=',@vcCustomProp1,0)))-(CHARINDEX('SENSOR_STATUS=',@vcCustomProp1,0)+14)))  
ELSE SUBSTRING(@vcCustomProp1,@intSensorStateStart+1, @intSensorStateEnd - @intSensorStateStart-1)END      
       SET @bitIsOn = CASE WHEN @vcSensorStatus = 'OPEN' OR @vcSensorStatus = 'ON' 
      OR @vcSensorStatus = 'NORMAL' OR @vcSensorStatus = 'OK' THEN 1                                                  
        WHEN @vcSensorStatus = 'CLOSE' OR @vcSensorStatus = 'OFF' OR @vcSensorStatus = 'LOW' THEN 0      
        END                                                  
                                                       
       IF EXISTS (SELECT BoxId FROM rvlfBoxSensorsCfg WHERE BoxId = @intBoxID1 AND SensorId = @tiSensorID)      
        BEGIN                                                  
         SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = s.AlarmLevelId, @vcAlarmLevelName = s.AlarmLevelName      
        FROM rvlfBoxSensorsCfg bs INNER JOIN rvlfSeverity s ON s.AlarmLevelId =                                                 
         (CASE WHEN @bitIsOn=1 THEN bs.AlarmLevelOn ELSE AlarmLevelOff END)                                                  
         WHERE bs.BoxId = @intBoxID1 AND bs.SensorId = @tiSensorID                                                   
        END                                                  
       ELSE                                                  
       BEGIN                                                  
       SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.DefaultAlarmLevel,                                                 
        @vcAlarmLevelName = s.AlarmLevelName                                                  
       FROM rvlfBoxProtocolMsgInType bs           
         INNER JOIN rvlfSeverity s On bs.DefaultAlarmLevel = s.AlarmLevelId                                                 
        WHERE bs.BoxMsgInTypeId = @tiBoxMsgInTypeId1                                                   
       END                                                             
      END             
                                                           
    IF @tiBoxMsgInTypeId1 = 27                                                   
     BEGIN                                                  
      SET @bitCreateAlarm = 1                                                  
     END                                                                 
                                             
 DECLARE @trancount int;                                          
 SET @trancount = @@trancount;                                          
 --PRINT CAST(@trancount as varchar)        
    BEGIN TRY                          
 IF @trancount = 0                      
  BEGIN TRANSACTION;                                          
 ELSE                                          
  SAVE TRANSACTION MessageTransaction;                                          
                  
     /***********************Message In History*************************************/           
 --BEGIN TRAN MessageTransaction                              
     --BEGIN TRY      
     --PRINT 'Welcome 1'    
   --  IF @vcCustomProp not like '%ImgData:1%'  -- CHARINDEX('ImgData:', @vcCustomProp) = 0                                          
   --begin                                          
PRINT 'Message Table.'                                   
-- To insert the information in the message in history table                                                  
--if(@CmdID1 is null or @CmdID1 not in (2,3)) begin
     INSERT INTO rvlfMsgInHSt                                                   
      (          
   BoxID , OriginDateTime , DateTimeReceived ,                                                   
       ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,                            
       CommInfo2 , ValidGps , Latitude ,Longitude , Speed ,                                                   
       Heading , SensorMask , CustomProp , SequenceNum ,          
       IsArmed , Priority , StreetAddress,IsNotificationSent,IsProcessed,IsArchived,ControllerID ,RefID,CmdId,DCSIM  ,Alarm                       
      )                                                  
     OUTPUT  INSERTED.MessageInID into @MsgInID                                                  
      VALUES                                                  
      (                         
       @intBoxID1 , @dtOriginDateTime1 , @dtDateTimeReceived1 ,                               
       @tiServiceID ,@tiBoxMsgInTypeId1, @intBoxProtocolTypeId , @vcCommInfo1 ,                                 
       @siCommInfo2 , @tiValidGps1 , @dLatitude1 , @dLongitude1 , @tiSpeed1 ,                            
       @siHeading  , dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'Input=',';') , @vcCustomProp1 , @bigSequenceNum ,                                                   
       @bitIsArmed , @tiPriority ,                                                   
       CASE WHEN @tiValidGps1 = 0 THEN NULL ELSE 'N/A' END,0,CASE WHEN @tiValidGps1 = 0 THEN 1 ELSE NULL END,0,null,null,null,null ,
	  @bitIsAlarm -- case when CHARINDEX('_R=1',@vcCustomProp1,0)>0 then 1 else 0 end
      )                                                  
 --End            
                      
 SELECT @uiMsgInID = uiMsgInID FROM @MsgInID     
--end 
/************* Reading XML File and Shift into Temp table******************************/
--DECLARE @TempdtSeconday TABLE ([Shift] VARCHAR(10),ShiftType varchar(10),NoofShift VARCHAR(10),StratTime VARCHAR(10),EndTime VARCHAR(10))
  --@dtSeconday ,
  --@dtPrimary  ,
  --@dtFiberCompactors  
 IF @dtSeconday IS NOT NULL                               
BEGIN    
print '@dtSeconday  '                                          
	EXEC sp_xml_preparedocument @docHandle OUTPUT, @dtSeconday                                                       
	INSERT INTO rvlfMsgInHst_Secondary (MessageInID,OriginDateTime,BoxID,CR3,CY3,CB3,PF3,PO3,WH3,CR3_R,CY3_R,CB3_R,CR4,CY4,CB4,PF4,PO4,WH4,CR4_R,CY4_R,CB4_R,CR5,CY5,CB5
,PF5,PO5,WH5,CR5_R,CY5_R,CB5_R,P5,P5_R)                                                                 
	SELECT @uiMsgInID,@dtOriginDateTime1,@intBoxID1,CR3 ,CY3,CB3,PF3,PO3,WH3,CR3_R,CY3_R,CB3_R,CR4,CY4,CB4,PF4,PO4,WH4,CR4_R,CY4_R,CB4_R,CR5,CY5,CB5,PF5,PO5,WH5,CR5_R,CY5_R,CB5_R,P5,P5_R  
	 FROM OPENXML(@docHandle, '/DocumentElement/dtSeconday')    	
	WITH                               
	( CR3 VARCHAR(10) 'CR3' ,CY3  varchar(10)  'CY3'	,CB3 varchar(10)  'CB3',PF3 Varchar(10) 'PF3',PO3 Varchar(10) 'PO3',WH3 Varchar(10) 'WH3',CR3_R Varchar(10) 'CR3_R',
	CY3_R Varchar(10) 'CY3_R',CB3_R Varchar(10) 'CB3_R',CR4 Varchar(10)  'CR4',CY4 Varchar(10) 'CY4',CB4 Varchar(10) 'CB4',PF4 Varchar(10) 'PF4',PO4 Varchar(10) 'PO4'
	,WH4 Varchar(10) 'WH4',CR4_R Varchar(10) 'CR4_R',CY4_R Varchar(10) 'CY4_R',CB4_R Varchar(10) 'CB4_R',CR5 Varchar(10) 'CR5',CY5 Varchar(10) 'CY5',CB5 Varchar(10) 'CB5'
	,PF5 Varchar(10) 'PF5',PO5 Varchar(10) 'PO5',WH5 Varchar(10) 'WH5',CR5_R Varchar(10) 'CR5_R',CY5_R Varchar(10) 'CY5_R',CB5_R Varchar(10) 'CB5_R',P5 Varchar(10) 'P5',P5_R Varchar(10) 'P5_R')                                    
END 
 IF @dtPrimary IS NOT NULL                               
BEGIN     
print '@dtPrimary  '                                         
	EXEC sp_xml_preparedocument @docHandle OUTPUT, @dtPrimary                                                       
	INSERT INTO rvlfMsgInHst_Primary 
	(MessageInID,OriginDateTime,BoxID,CR6,CY6,CB6,WH6,PF6,PO6,CR6_R,CY6_R,CB6_R,CR7,CY7,CB7,WH7,PF7,PO7,CR7_R,CY7_R,CB7_R,CR8,CY8,CB8,WH8,PF8,PO8,CR8_R,CY8_R,CB8_R,CR9,CY9,CB9,WH9,PF9,PO9,CR9_R,CY9_R
,CB9_R,CR10,CY10,CB10,WH10,PF10,PO10,CR10_R,CY10_R,CB10_R,CR11,CY11,CB11,WH11,PF11,PO11,CR11_R,CY11_R,CB11_R,P6,P6_R,P7,P7_R)  

	SELECT @uiMsgInID,@dtOriginDateTime1,@intBoxID1,CR6,CY6,CB6,WH6,PF6,PO6,CR6_R,CY6_R,CB6_R,CR7,CY7,CB7,WH7,PF7,PO7,CR7_R,CY7_R,CB7_R,CR8,CY8,CB8,WH8,PF8,PO8,CR8_R,CY8_R,CB8_R,CR9,CY9,CB9,WH9,PF9,PO9
	,CR9_R,CY9_R,CB9_R,CR10,CY10,CB10,WH10,PF10,PO10,CR10_R,CY10_R,CB10_R,CR11,CY11,CB11,WH11,PF11,PO11,CR11_R,CY11_R,CB11_R,P6,P6_R,P7,P7_R FROM OPENXML(@docHandle, '/DocumentElement/dtPrimary')    	
	WITH                               
	(CR6 varchar(10) 'CR6',CY6 varchar(10) 'CY6',CB6 varchar(10) 'CB6',PF6 varchar(10) 'PF6',PO6 varchar(10) 'PO6',WH6 varchar(10) 'WH6',CR6_R varchar(10) 'CR6_R',CY6_R varchar(10) 'CY6_R'
	,CB6_R varchar(10) 'CB6_R',CR7 varchar(10) 'CR7',CY7 varchar(10) 'CY7',CB7 varchar(10) 'CB7',PF7 varchar(10) 'PF7',PO7 varchar(10) 'PO7',WH7 varchar(10) 'WH7',CR7_R varchar(10) 'CR7_R'
	,CY7_R varchar(10) 'CY7_R',CB7_R varchar(10) 'CB7_R',CR8 varchar(10) 'CR8',CY8 varchar(10) 'CY8',CB8 varchar(10) 'CB8',PF8 varchar(10) 'PF8',PO8 varchar(10) 'PO8',WH8 varchar(10) 'WH8'
	,CR8_R varchar(10) 'CR8_R',CY8_R varchar(10) 'CY8_R',CB8_R varchar(10) 'CB8_R',CR9 varchar(10) 'CR9',CY9 varchar(10) 'CY9',CB9 varchar(10) 'CB9',PF9 varchar(10) 'PF9',PO9 varchar(10) 'PO9'
	,WH9 varchar(10) 'WH9',CR9_R varchar(10) 'CR9_R',CY9_R varchar(10) 'CY9_R',CB9_R varchar(10) 'CB9_R',CR10 varchar(10) 'CR10',CY10 varchar(10) 'CY10',CB10 varchar(10) 'CB10',PF10 varchar(10) 'PF10'
	,PO10 varchar(10) 'PO10',WH10 varchar(10) 'WH10',CR10_R varchar(10) 'CR10_R',CY10_R varchar(10) 'CY10_R',CB10_R varchar(10) 'CB10_R',CR11 varchar(10) 'CR11',CY11 varchar(10) 'CY11'
	,CB11 varchar(10) 'CB11',PF11 varchar(10) 'PF11',PO11 varchar(10) 'PO11',WH11 varchar(10) 'WH11',CR11_R varchar(10) 'CR11_R',CY11_R varchar(10) 'CY11_R',CB11_R varchar(10) 'CB11_R'
	,P6 varchar(10) 'P6',P7 varchar(10) 'P7',P6_R varchar(10) 'P6_R',P7_R varchar(10) 'P7_R')
END     
IF @dtFiberCompactors IS NOT NULL                               
BEGIN   
print '@dtPrimary  '                                           
	EXEC sp_xml_preparedocument @docHandle OUTPUT, @dtFiberCompactors                                                       
	INSERT INTO rvlfMsgInHst_FibreCompactor (
	MessageInID,OriginDateTime,BoxID,CR12,CY12,CB12,PF12,PO12,WH12,CR12_R,CY12_R,CB12_R,CR13,CY13,CB13,PF13,PO13,WH13,CR13_R,CY13_R,CB13_R,CR14,CY14,CB14,PF14,PO14,WH14,CR14_R,CY14_R,CB14_R,CR15,CY15
,CB15,PF15,PO15,WH15,CR15_R,CY15_R,CB15_R,CR16,CY16,CB16,PF16,PO16,WH16,CR16_R,CY16_R,CB16_R,CR17,CY17,CB17,PF17,PO17,WH17,CR17_R,CY17_R,CB17_R,CR18,CY18,CB18,PF18,PO18,WH18,CR18_R,CY18_R,CB18_R,CR19
,CY19,CB19,PF19,PO19,WH19,CR19_R,CY19_R,CB19_R,P8,P9,P10,P11,P8_R,P9_R,P10_R,P11_R	)  
	SELECT @uiMsgInID,@dtOriginDateTime1,@intBoxID1,CR12,CY12,CB12,PF12,PO12,WH12,CR12_R,CY12_R,CB12_R,CR13,CY13,CB13,PF13,PO13,WH13,CR13_R,CY13_R,CB13_R,CR14,CY14,CB14,PF14,PO14,WH14,CR14_R,CY14_R,CB14_R
,CR15,CY15,CB15,PF15,PO15,WH15,CR15_R,CY15_R,CB15_R,CR16,CY16,CB16,PF16,PO16,WH16,CR16_R,CY16_R,CB16_R,CR17,CY17,CB17,PF17,PO17,WH17,CR17_R,CY17_R,CB17_R,CR18
,CY18,CB18,PF18,PO18,WH18,CR18_R,CY18_R,CB18_R,CR19,CY19,CB19,PF19,PO19,WH19,CR19_R,CY19_R,CB19_R,P8,P9,P10,P11,P8_R,P9_R,P10_R,P11_R FROM OPENXML(@docHandle, '/DocumentElement/dtFiberCompactors')	
	WITH                               
	(CR12 varchar(10) 'CR12',CY12 varchar(10) 'CY12',CB12 varchar(10) 'CB12',PF12 varchar(10) 'PF12',PO12 varchar(10) 'PO12',WH12 varchar(10) 'WH12',CR12_R varchar(10) 'CR12_R',CY12_R varchar(10) 'CY12_R'
,CB12_R varchar(10) 'CB12_R',CR13 varchar(10) 'CR13',CY13 varchar(10) 'CY13',CB13 varchar(10) 'CB13',PF13 varchar(10) 'PF13',PO13 varchar(10) 'PO13',WH13 varchar(10) 'WH13',CR13_R varchar(10) 'CR13_R'
,CY13_R varchar(10) 'CY13_R',CB13_R varchar(10) 'CB13_R',CR14 varchar(10) 'CR14',CY14 varchar(10) 'CY14',CB14 varchar(10) 'CB14',PF14 varchar(10) 'PF14',PO14 varchar(10) 'PO14',WH14 varchar(10) 'WH14'
,CR14_R varchar(10) 'CR14_R',CY14_R varchar(10) 'CY14_R',CB14_R varchar(10) 'CB14_R',CR15 varchar(10) 'CR15',CY15 varchar(10) 'CY15',CB15 varchar(10) 'CB15',PF15 varchar(10) 'PF15',PO15 varchar(10) 'PO15'
,WH15 varchar(10) 'WH15',CR15_R varchar(10) 'CR15_R',CY15_R varchar(10) 'CY15_R',CB15_R varchar(10) 'CB15_R',CR16 varchar(10) 'CR16',CY16 varchar(10) 'CY16',CB16 varchar(10) 'CB16',PF16 varchar(10) 'PF16'
,PO16 varchar(10) 'PO16',WH16 varchar(10) 'WH16',CR16_R varchar(10) 'CR16_R',CY16_R varchar(10) 'CY16_R',CB16_R varchar(10) 'CB16_R',CR17 varchar(10) 'CR17',CY17 varchar(10) 'CY17',CB17 varchar(10) 'CB17'
,PF17 varchar(10) 'PF17',PO17 varchar(10) 'PO17',WH17 varchar(10) 'WH17',CR17_R varchar(10) 'CR17_R',CY17_R varchar(10) 'CY17_R',CB17_R varchar(10) 'CB17_R',CR18 varchar(10) 'CR18',CY18 varchar(10) 'CY18'
,CB18 varchar(10) 'CB18',PF18 varchar(10) 'PF18',PO18 varchar(10) 'PO18',WH18 varchar(10) 'WH18',CR18_R varchar(10) 'CR18_R',CY18_R varchar(10) 'CY18_R',CB18_R varchar(10) 'CB18_R',CR19 varchar(10) 'CR19'
,CY19 varchar(10) 'CY19',CB19 varchar(10) 'CB19',PF19 varchar(10) 'PF19',PO19 varchar(10) 'PO19',WH19 varchar(10) 'WH19',CR19_R varchar(10) 'CR19_R',CY19_R varchar(10) 'CY19_R',CB19_R varchar(10) 'CB19_R'
,P8 varchar(10) 'P8',P9 varchar(10) 'P9',P10 varchar(10) 'P10',P11 varchar(10) 'P11',P8_R varchar(10) 'P8_R',P9_R varchar(10) 'P9_R',P10_R varchar(10) 'P10_R',P11_R varchar(10) 'P11_R')
END 
              
	 IF @tiBoxMsgInTypeId1 IN (1)
		 BEGIN 
			exec rvlf_sp_GetEnergyConsumptionForShift @intBoxID,@dtOriginDateTime,@uiMsgInID
			 --update rvlfMsgInHst set odometer=dbo.rvlf_fn_GetEnergyConsumptionForShift(@intBoxID,@dtOriginDateTime,1) 
			 --,duration=dbo.rvlf_fn_GetEnergyConsumptionForShift(@intBoxID,@dtOriginDateTime,2) where MessageInID=@uiMsgInID
		 end
 
 PRINT 'BoxId Table'        
 /******************************************************************************/                                                   
     /****************************Box ID Table**************************************/                                
     -- Inserts into the rvlfBoxID if sensor mask is available in the information. 
     --IF @vcSensorMask IS NOT NULL AND LEN(@vcSensorMask) = 8 AND @tiBoxMsgInTypeId NOT IN (51,121) AND @tiValidGps <>2 
	  --IF @tiBoxMsgInTypeId1 IN (1)
   --   BEGIN
	  --UPDATE rvlfBoxId SET            
   --       LastLatitude = CASE WHEN @tiValidGps1 = 0 THEN @dLatitude1 ELSE LastLatitude END,                                                  
   --       LastLongitude = CASE WHEN @tiValidGps1 = 0 THEN @dLongitude1 ELSE LastLongitude END,      
   --       LastCommunicatedDateTime = @dtDateTimeReceived1
			--WHERE BoxId = @intBoxID1 
	  --End    
	  IF @tiBoxMsgInTypeId1 IN (1,8)
      BEGIN                                    
         if @tiBoxMsgInTypeId1 IN (1)                                           
		 begin
       DECLARE  @dtLastValidDateTime DateTime=(SELECT LastValidDateTime FROM rvlfBoxId WHERE BoxId = @intBoxID1)      
       -- Checks if the last information exists for the box, if so updates else inserts                                                         
             IF @dtOriginDateTime1 >= @dtLastValidDateTime                                             
		   BEGIN     
            UPDATE rvlfBoxId SET BoxArmed = @bitIsArmed,LastValidDateTime = CASE WHEN @tiValidGps1 = 2 THEN LastValidDateTime ELSE @dtOriginDateTime1 END,                        
             LastCommunicatedDateTime = @dtDateTimeReceived1,LastStatusDateTime = @dtOriginDateTime1, MessageInId = @uiMsgInID 		
		   	WHERE BoxId = @intBoxID1                                                                          
           END                                          
        END                                          
		Else if @tiBoxMsgInTypeId1 IN (8)   
		begin
			UPDATE rvlfBoxId SET LastCommunicatedDateTime = @dtOriginDateTime1 WHERE BoxId = @intBoxID1
		end
       ELSE IF(@dtLastValidDateTime IS NULL OR @dtLastValidDateTime='')                                                 
        BEGIN                                                  
         DELETE FROM rvlfBoxId WHERE BoxId=@intBoxID1       
         INSERT INTO rvlfBoxId                     
    (                                            
          BoxId, BoxArmed, LastValidDateTime, LastLatitude, LastLongitude,                                                   
          LastSpeed, LastCommunicatedDateTime, LastSensorMask,                    
          OrganizationId, LastStatusDateTime, Heading , LastStreetAddress ,                                                  
          NearestLandmark, MessageInId                                                  
         )                                      
         VALUES                                 
         (                                           
          @intBoxID1, @bitIsArmed, @dtLastValidGPSTime, @dLatitude1, @dLongitude1,                                                  
          @tiSpeed1, @dtDateTimeReceived1, @vcSensorMask,                                                   
          @bigOrganizationID, @dtOriginDateTime1, @siHeading,                                
          CASE WHEN @tiValidGps1 = 0 THEN NULL ELSE 'N/A' END,                                             
          CASE WHEN @tiValidGps1 = 0 THEN NULL ELSE 'N/A' END,                                                  
          @uiMsgInID                                                 
         )                                           
        END                   
      END 
          
	IF @tiBoxMsgInTypeId1 IN (8)
      BEGIN
	  declare @DIP varchar(15)=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'Input=',';')
	  update rvlfBoxId set LastSensorMask=@DIP where BoxId = @intBoxID1 
	  
	  end
		        PRINT 'Alarm Table.'                                   
     /******************************************************************************/ 
	 
	/***********For Alarm logging******************/
	
	if (@tiBoxMsgInTypeId1 =8 or @bitIsAlarm=1)--CHARINDEX('_R=1',@vcCustomProp1,0) <> 0)
     Begin	
		Declare @msgIDLastPacket uniqueidentifier 
		Select top 1 @msgIDLastPacket = messageinid from rvlfMsgInHst h where boxid= @intBoxID1 and BoxMsgInTypeId in (@tiBoxMsgInTypeId1) and h.MessageInID != @uiMsgInID 
		order by OriginDateTime desc 
		PRINT 'Alarm Table 1'
		 EXEC rvlf_sp_AlarmMessageReceived_vxl @vcCustomProp1,@tiBoxMsgInTypeId1,0,0,@intBoxID1,@dtOriginDateTime1,@uiMsgInID,@msgIDLastPacket 
     END
	 Else
	 Begin
		 IF(@tiBoxMsgInTypeId1 in(1))
		 BEGIN
			Declare @CurDateTimeForAlarm Datetime = GETUTCDATE()
			UPDATE [rvlfAlarm] SET [IsClosed]=1,[ClosedBy]=0,[DateTimeClosed] = @CurDateTimeForAlarm WHERE BoxID=@intBoxID1  
					AND ([IsClosed] IS NULL OR [IsClosed] = 0 OR [IsClosed]='') and AlarmType=@tiBoxMsgInTypeId1
					
			update rvlfBoxId set ControllerID= null where BoxId=@intBoxID1
			--EXEC rvlf_sp_LogNotificaitons_ForAlarms @CurDateTimeForAlarm,NULL,@tiBoxMsgInTypeId1
		 END
	 End

PRINT 'Alarm Table end'
	/*********************************************/  
-- if CHARINDEX('IsAlarm=1',@vcCustomProp1,0) <> 0 --and @tiBoxMsgInTypeID in (4,7,24)
  -- Begin
		--EXEC rvlf_sp_LogNotificaitons_ForAlarms @msgIDLastPacket,@uiMsgInID,@tiBoxMsgInTypeId1
  -- End
     /******************************************************************************/                                       
     /***************************Communication Processing***************************/   
        -- Inserts the communication information based on the communication information.             
    IF NOT EXISTS(SELECT commAddressValue FROM rvlfBoxCommInfo WHERE BoxId = @intBoxID1 AND CommAddressValue =@vcNewIP)      
      BEGIN                           
       DELETE FROM rvlfBoxCommInfo WHERE BoxId = @intBoxID1                              
       INSERT INTO rvlfBoxCommInfo(BoxID,CommAddressTypeId,CommAddressValue)                                                  
       SELECT @intBoxID1,CommAddressTypeID,@vcNewIP FROM rvlfCommModeAddressType                 
        WHERE CommModeId = @tiCommModeId   
       END                                                   
        /******************************************************************************/                              
                PRINT 'ACK / Response'                                   
     /*************************Message out Processing (ACK / Response)**************/                   
  IF (@dtSentDateTime1 IS NOT NULL or (@tiBoxMsgInTypeId=20 or @tiBoxMsgInTypeId=14))                        
  BEGIN         
 -- select * from rvlfBoxCmdOutType
    declare @mode char(2)= dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'RangeMode=',';')                               
	
	UPDATE TOP (1) rvlfMsgOutHst SET Acknowledged = dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'Status=',';'), MessageInID= @uiMsgInID WHERE BoxId = @intBoxID1 
	AND SentDateTime between DATEADD(SECOND,-10,@dtOriginDateTime1) and @dtOriginDateTime1 and 
	BoxCmdOutTypeId= case when @mode='F' then 1 when @mode='T' then 2 when @mode='E' then 14 when @mode='P' then 27 else 0 end and MessageInID is null

	declare @RCustomProp varchar(1000)
	select @RCustomProp=CustomProp from rvlfMsgOutHst WHERE BoxId = @intBoxID1 and MessageInID= @uiMsgInID
if(@mode='F') begin
--Update reporting interval and speed threshold to master table                   
UPDATE v SET v.RptInterval=@RCustomProp--dbo.rvlf_fn_GetParamValueWithIndex(REPLACE(@RCustomProp,@intBoxID1+'|',@intBoxID1+'|F'),'F','|')
 ,[Modified DateTime]=GETDATE()
 FROM rvlfVehicle v  
INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId                                              
INNER JOIN rvlfMsgOutHst H ON H.BoxId=va.BoxId                                           
WHERE H.BoxId = @intBoxID1 AND H.BoxCmdOutTypeId IN (1) 
end
	
else if exists (select * from rvlfParamRange where Boxid=@intBoxID1)
begin
if(@mode='T') begin  PRINT 'ACK T'
update rvlfParamRange set T1_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T1MIN','|'),T1_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T1MAX','|')
,T2_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T2MIN','|'),T2_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T2MAX','|')
,T3_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T3MIN','|'),T3_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T3MAX','|')
,T4_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T4MIN','|'),T4_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T4MAX','|')
,T5_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T5MIN','|'),T5_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T5MAX','|'),ModifyDate=GETutcDATE() where Boxid=@intBoxID1
end 
else if (@mode='P')
begin PRINT 'ACK P'
update rvlfParamRange set P3_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P3Mn','|'),P3_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P3Mx','|')
,P4_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P4Mn','|'),P4_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P4Mx','|')
,P5_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P5Mn','|'),P5_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P5Mx','|')
,P6_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P6Mn','|'),P6_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P6Mx','|')
,P7_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P7Mn','|'),P7_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P7Mx','|')
,P8_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P8Mn','|'),P8_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P8Mx','|')
,P9_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P9Mn','|'),P9_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P9Mx','|')
,P10_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P10Mn','|'),P10_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P10Mx','|')
,P11_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P11Mn','|'),P11_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P11Mx','|')
,DPs_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPsMIN','|'),DPs_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPsMAX','|')
,DPp_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPpMIN','|'),DPp_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPpMAX','|')
,DPp1_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPp1MIN','|'),DPp1_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPp1MAX','|'),ModifyDate=GETDATE() where Boxid=@intBoxID1
end
else if (@mode='E') begin PRINT 'ACK E'
update rvlfParamRange set V1_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'V1Mn','|'),V1_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'V1Mx','|')
,C1_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C1Mn','|'),C1_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C1Mx','|')
,C2_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C2Mn','|'),C2_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C2Mx','|')
,C3_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C3Mn','|'),C3_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C3Mx','|')
,C4_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C4Mn','|'),C4_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C4Mx','|')
,C5_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C5Mn','|'),C5_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C5Mx','|')
,C6_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C6Mn','|'),C6_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C6Mx','|')
,C7_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C7Mn','|'),C7_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C7Mx','|')
,C8_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C8Mn','|'),C8_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C8Mx','|')
,C9_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C9Mn','|'),C9_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C9Mx','|')
,C10_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C10Mn','|'),C10_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C10Mx','|')
,C11_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C11Mn','|'),C11_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C11Mx','|')
,C12_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C12Mn','|'),C12_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C12Mx','|')
,C13_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C13Mn','|'),C13_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C13Mx','|')
,C14_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C14Mn','|'),C14_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C14Mx','|')
,C15_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C15Mn','|'),C15_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C15Mx','|')
,C16_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C16Mn','|'),C16_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C16Mx','|')
,C17_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C17Mn','|'),C17_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C17Mx','|')
,C18_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C18Mn','|'),C18_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C18Mx','|')
,C19_Min=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C19Mn','|'),C19_Max=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C19Mx','|')
,RC1=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC1_','|'),[RC2]=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC2_','|')
,RC3=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC3_','|'),[RC4]=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC4_','|')
,RC5=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC5_','|'),RC6=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC6_','|')
,RC7=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC7_','|'),RC8=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC8_','|')
,RC9=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC9_','|'),RC10=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC10_','|')
,RC11=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC11_','|'),RC12=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC12_','|')
,RC13=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC13_','|'),RC14=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC14_','|')
,RC15=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC15_','|'),RC16=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC16_','|')
,RC17=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC17_','|'),RC18=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC18_','|')
,RC19=dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC19_','|'),ModifyDate=GETutcDATE() 
where Boxid=@intBoxID1
end
else if (@mode='A' or @mode='C') 
begin 
	declare @VehiclePlanId bigint,@ServiceDetailsID bigint,@planID bigint
	SELECT top 1 @VehiclePlanId=vm.VehiclePlanId,@ServiceDetailsID=vm.ServiceDetailsId,@planID=vp.PlanId
	FROM rvlfVehicleMaintenanceService vm
	INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId
	INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId
	INNER JOIN rvlfVehicle v ON v.VehicleId = vp.VehicleId
	inner join rvlfMAKDevices D on  D.VehicleId=v.VehicleId where isnull(vm.RunningSerial,0)=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'Sno=',';') and D.BoxId=@intBoxID1 order by vm.ServiceDetailsId desc
	UPDATE TOP (1) rvlfMsgOutHst SET Acknowledged = case when @mode='C' then '2' else dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'Status=',';') end, MessageInID= @uiMsgInID,isCommentSentStatus=4,isCommentSentUpdateDate=GETDATE() WHERE BoxId = @intBoxID1 and SequenceNum=@VehiclePlanId 
	and SentDateTime=(select top 1 SentDateTime from rvlfMsgOutHst where BoxId = @intBoxID1 and SequenceNum=@VehiclePlanId order by SentDateTime desc)
	
	

	if(@mode='C')
		begin
			--if(dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'user=',';')<>'')
			--	begin
			--		if(exists(Select UserId from rvlfUser where UserName=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'user=',';')))
			--			begin
			--				Select @CloseUserID=UserId from rvlfUser where UserName=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'user=',';')
			--			end
			--		else
			--			begin
			--				Select @CloseUserID=UserId from rvlfUser where UserName=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'user=',';')
			--			end
			--	end

			declare @Readingvalues bigint=0,@closeName varchar(200) ='Closed by: ' +  dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp1,'user=',';')

			Select @Readingvalues=CurrentOdometerReading from rvlfVehicleCurrentReadings where VehicleId in (Select VehicleId from rvlfVehicleAssignment where BoxId=@intBoxID1)
			declare @p6 xml
			set @p6=convert(xml,N'<DocumentElement/>')
			declare @exeDate datetime=cast(getdate() as date)
			declare @exeScheduleOnDate datetime=getdate()
			exec rvlf_sp_UpdateMaintenanceServiceDetails @bigQueryingUser=N'1',@bigServiceDetailsId=@ServiceDetailsID,@tiStatus=N'1',@bigCurrentReading=@Readingvalues,@dtExecutionOnDate=@exeDate,@tblMaintenanceServiceDetails=@p6,@IsDueOn=N'1',@dtScheduleOnDate=@exeScheduleOnDate,@vcComments=@closeName,@ModifiedBy=N'1',@ModifiedDateTime=@exeScheduleOnDate


			INSERT INTO rvlfMaintenanceServiceDetails(ServiceDetailsId, ServiceId, ServicedOn, ServiceCost, ServicedBy)
			SELECT @ServiceDetailsID, ms.ServiceId, getdate(), ps.PlannedCost,'1' FROM rvlfMaintenanceService ms
			INNER JOIN rvlfMaintenancePlanServices ps ON ps.ServiceId = ms.ServiceId
			LEFT OUTER JOIN rvlfMaintenanceServiceDetails sd ON sd.ServiceId = ms.ServiceId AND sd.ServiceDetailsId = @ServiceDetailsID
			WHERE ps.PlanId = @planID 
	end

end

end
else
begin PRINT 'ACK '
insert into rvlfParamRange (boxid,T1_Min,T1_Max,T2_Min,T2_Max,T3_Min,T3_Max,T4_Min,T4_Max,P1_Min,P1_Max,P2_Min,P2_Max,P3_Min,P3_Max,P4_Min,P4_Max,P5_Min,P5_Max,V1_Min,V1_Max,C1_Min,C1_Max,C2_Min,C2_Max
,DPs_Min,DPs_Max,DPp_Min,DPp_Max,DPp1_Min,DPp1_Max,RC1,[RC2],IsActive,CreatedDate,CreatedBy) 
values (@intBoxID1,
dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T1MIN','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T1MAX','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T2MIN','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T2MAX','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T3MIN','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T3MAX','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T4MIN','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'T4MAX','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P1Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P1Mx','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P2Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P2Mx','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P3Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P3Mx','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P4Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P4Mx','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P5Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'P5Mx','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'V1Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'V1Mx','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C1Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C1Mx','|')  
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C2Mn','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'C2Mx','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPsMIN','|'),dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPsMAX','|')
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPpMIN','|'),dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPpMAX','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPp1MIN','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'DPp1MAX','|') 
,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC1_','|') ,dbo.rvlf_fn_GetParamValueWithIndex(@RCustomProp,'RC2_','|'),1,getutcdate(),1)
end

END                                        
                                 
        --PRINT 'Welcome 4'                                          
IF @trancount = 0           
            COMMIT;                            
    -- COMMIT TRAN                          
    END TRY                           
    BEGIN CATCH         
        DECLARE @error int, @message varchar(4000), @xstate int;                          
        SELECT @error = ERROR_NUMBER(),                           
             @message = ERROR_MESSAGE(),                        
               @xstate = XACT_STATE();                              
                           
        if @xstate = -1                        
            ROLLBACK TRAN;                                          
        if @xstate = 1 and @trancount = 0                                          
         ROLLBACK TRAN;                                          
        if @xstate = 1 and @trancount > 0                                          
            ROLLBACK TRANSACTION MessageTransaction;                                              
                                           
      --ROLLBACK TRAN                                          
      SET @ErrorMessage = 'An Error occured during insert of the packet message : ' + @message                                          
      RAISERROR( @ErrorMessage,16,1)                                                  
    END CATCH                                                   
    END--CONDITION 02 END              
  END             
 END --CONDITION 01 END                 
/******************************************************************************/                                                                
  
                                     
 --CHECK THE SCHEDULED OTA COMMAND RETRY**************************************************************                                                 
 --DECLARE @bigRetryScheduleId bigint=null,@tintAck tinyint=null,@dtOtaTime datetime=null 
 --SELECT TOP 1 @tintAck=Acknowledged,@dtOtaTime=H.SentDateTime FROM rvlfMsgOutHst H         
 -- WHERE H.BoxCmdOutTypeId =22 AND H.BoxId =@intBoxID1 AND H.Acknowledged BETWEEN 0 AND 10 ORDER BY H.SentDateTime DESC                                                   
 --IF (@tintAck NOT IN(2,6) AND @tintAck IS NOT NULL)                                                  
 -- BEGIN                                                  
 --  IF EXISTS(SELECT ScheduleId FROM rvlfScheduleOfCommandsMaster WHERE Boxid=@intBoxID1 AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND BoxCmdOutTypeId =22)                                                  
 --   BEGIN                                                  
 --    SELECT @bigRetryScheduleId =a.ScheduleId  FROM rvlfScheduleOfCommandsMaster a inner join rvlfSchedulingOfCommandsLog b
	--on a.ScheduleId=b.ScheduleId              
 --     WHERE Boxid=@intBoxID1 and ResponseMsg != 'Success' AND BoxCmdOutTypeId =22 AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND GETUTCDATE() BETWEEN EffectiveFrom AND EffectiveTo                                                   
 --    IF @bigRetryScheduleId IS NOT NULL                         
 --BEGIN                          
 --      UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=NULL WHERE ScheduleId =@bigRetryScheduleId AND BoxCmdOutTypeId=22                                                  
 --      IF EXISTS(SELECT ScheduleLogId FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId)      
 --       BEGIN                                         
 --        UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=NULL,ActualExecutionDate=CASE WHEN @dtOtaTime>CreatedDate AND @dtOtaTime <=EffectiveTo THEN @dtOtaTime ELSE NULL END WHERE ScheduleId =@bigRetryScheduleId AND BoxCmdOutTypeId  =22 
 --        DELETE rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId AND ResponseId IN (1,2,3,4,6,7,8,9,10) --RESPONSEMSG!='Aborted'              
 --       END             
 --     END                                    
 -- END              
 -- END        
 --ELSE IF(@tintAck IS NULL)      
 -- BEGIN              
 --  SELECT @bigRetryScheduleId =ScheduleId  FROM rvlfScheduleOfCommandsMaster    
 --   WHERE Boxid=@intBoxID1 AND BoxCmdOutTypeId =22 AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND GETUTCDATE() BETWEEN EffectiveFrom AND EffectiveTo             
 --  IF(@bigRetryScheduleId IS NOT NULL OR @bigRetryScheduleId!='')              
 --   BEGIN                                                       
 --    IF NOT EXISTS(SELECT ScheduleLogId FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId)      
 --     BEGIN                                                  
 --      INSERT INTO rvlfSchedulingOfCommandsLog (ScheduleId,ExecutionOn,IsCommandSend,[No.ofTries],ResponseMsg,ResponseId)      
 --      SELECT @bigRetryScheduleId,@dtOtaTime,1,1,'Command sent successfully.',3                                                  
 --     END     
 --   END         
 -- END         

                       
 ----------------------------------                      
 /**************************************************************************************************/      
 --SCHEDULE THE COMMANDS****************************************************************************/                                                
 --IF (((SELECT TOP 1 BoxId  FROM rvlfBoxId WHERE BoxId=@intBoxID1 AND CONVERT(DATE,LastCommunicatedDateTime)=CONVERT(DATE,GETUTCDATE()))=@intBoxID1) OR (@tiBoxMsgInTypeId1=52))                                                    
 -- BEGIN         
 -- --PRINT 'Welcome 5'                                          
 --  --CHECK IF THE BOXID HAVE ANY SCHEDULES FOR GIVE COMMANDS                      
 --  IF EXISTS(SELECT ScheduleId  FROM rvlfScheduleOfCommandsMaster SM                                                   
 --   WHERE ScheduleId NOT IN(SELECT ScheduleId  FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE()))   
 --    AND SM.BoxId =@intBoxID1  and SM.Isdelete is null                                  
 --    AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))                          
 --   --AND (GETUTCDATE()>= EffectiveFrom                                                  
 --    --AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END)) and BoxCmdOutTypeId<>94                  
 -- AND (GETUTCDATE()>= (case when BoxCmdOutTypeId=94 then DATEADD(MINUTE,-30,EffectiveFrom) else EffectiveFrom end)   
 --    AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END))                  
 --    AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE())))                                   
 --   BEGIN                                            
 --  --PRINT 'Welcome 6'                                          
 --    DECLARE @TBLSCHEDULES TABLE(ScheduleId bigint,inc bit)                                                  
 --    INSERT INTO @TBLSCHEDULES(ScheduleId,inc)                                                 
 --     SELECT DISTINCT SM.ScheduleId,0 FROM rvlfScheduleOfCommandsMaster SM                                                  
 --      WHERE ScheduleId NOT IN(SELECT ScheduleId  FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE()))                                                   
 --    AND SM.BoxId =@intBoxID1  and SM.Isdelete is null
 --       AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))                                                  
 --    --    AND (GETUTCDATE()>= EffectiveFrom         
 --    --AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END)) and BoxCmdOutTypeId<>94           
 --       AND (GETUTCDATE()>= (case when BoxCmdOutTypeId=94 then DATEADD(MINUTE,-30,EffectiveFrom) else EffectiveFrom end)       
 --     AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE  EffectiveTo END))         
         
 --       AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE()))        
 --    WHILE EXISTS(SELECT ScheduleId FROM @TBLSCHEDULES WHERE inc =0)                                           
 --     BEGIN                        
 --     --PRINT 'Welcome 7'                                          
 --      DECLARE @vcType varchar(50)=null,@bigScheduleId bigint=null                                                
 --      SELECT @bigScheduleId=ScheduleId FROM @TBLSCHEDULES WHERE inc=0                                                  
   
 --    --UPDATE THE LATEST IP AND PORT                          
 --      UPDATE rvlfScheduleOfCommandsMaster                                  
 --       SET PacketInfo = REPLACE(PacketInfo,SUBSTRING(PacketInfo,CHARINDEX('IP=',PacketInfo,1)+3,(CHARINDEX(';',PacketInfo,CHARINDEX('Port=',PacketInfo,1))-4)),@vcCommInfo1+';Port='+CAST(@siCommInfo2 AS VARCHAR))     
 --      WHERE ScheduleId=@bigScheduleId  
                                                       
 --      SELECT TOP 1 @vcType=ExecutionOn,@bigScheduleId=ScheduleId FROM rvlfScheduleOfCommandsMaster                                                   
 --       WHERE ScheduleId=@bigScheduleId                                                   
                                                       
 --      --IF THE COMMANDS EXECUTION TYPE IS Ignition On                                                 
 --        IF (@vcType ='Ignition On' AND @tiBoxMsgInTypeId1=2)           
 --       BEGIN                    
 --        INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)                           
 --        VALUES(@bigScheduleId,GETUTCDATE(),0)                                        
 --       END                              
 --      ELSE IF(@vcType ='Any message in' AND @tiBoxMsgInTypeId1 NOT IN(12))                      
 --BEGIN                                                
 --        INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)                           
 --         VALUES(@bigScheduleId,GETUTCDATE(),0) 
 --       END      
 --      UPDATE TOP(1) @TBLSCHEDULES SET inc=1 WHERE ScheduleId=@bigScheduleId     
 --     END                               
 --   END                  
 --END                                    

SET NOCOUNT OFF     
end
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateMessageReceived1]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 create Procedure [dbo].[rvlf_sp_UpdateMessageReceived1]      
@intboxid bigint=null,      
@dtOriginDateTime datetime,      
@dtDateTimeReceived datetime,      
@vcCommMode varchar(100),      
@tiBoxMsgInTypeId TINYINT = null,      
@vcBoxProtocolTypeName varchar(50) = null,      
@vcCommInfo1 varchar(15),      
@siCommInfo2 int ,      
@tiValidGps smallint = 2,      
@dLatitude decimal(10,6) = 0,      
@dLongitude decimal(10,6) = 0,      
@tiSpeed smallint = 0,      
@siHeading smallint = 0,      
@vcSensorMask varchar(8) = null,      
@vcCustomProp varchar(max)= null,      
@bigSequenceNum bigint = null,      
@bitIsArmed bit = null,      
@tiPriority tinyint = null,      
@bitIsAlarm bit =0,      
@dtSentDateTime datetime = null,      
@bitIgnitionStatus bit = null,      
@bigOdoMeterReading bigint = null,      
@bitIsTrinetraApp bit = 0,      
@ModelNo VARCHAR(256) = null,      
@odoValue_app varchar(6) = null,      
@AlarmDesc_app varchar(256) = null,      
@IsPrefAck bit = 0,
@dtSeconday XML = NULL,
@dtPrimary XML = NULL,
@dtFiberCompactors XML = NULL     
AS      
/*********************************************************************************************************************************/      
-- Name : [rvlf_sp_UpdateMessageReceived]      
-- Description : To insert the messages that is sent to the device      
-- Author : V.Narayanasamy      
-- Company : Angler Technologies      
-- History : <<Date(dd-MON-yyyy)>> Initial Reason      
-- : 11-Oct-2011 VN Created Intial Version      
-- : 22-Nov-2011 Ranjith Add Geozone issue (Geozone id assigned instead of Geozone no for VehicleGeozone table)      
-- : 27-Jan-2012 Sakthi Casting for add geozone and Geozone id instead of Geozone no for deleting geozone      
-- : 11-May-2012 Sakthi Update the odometer and duration column with values      
-- : 11-Oct-2012 Sakthi Update reporting interval and speed threshold to master vehicle table      
-- : 17-Oct-2012 Set speed is 0 by default for extreme and harsh braking / acceleration      
-- : 23-Oct-2013 Sakthi Log the geozone based Trip details      
-- : 16-Nov-2013 Sakthi Track the trip details by vehicle wise to other clients      
-- : 29-Oct-2018 Asanraj Incluede OrganizationId for 412      
/*********************************************************************************************************************************/      
 BEGIN      
  SET NOCOUNT ON    
  DECLARE @startdate datetime,@enddate datetime,@Msgin varchar(50)  
  SET @startdate=getdate()  
  --For input Parameters verification from SLS service.      
  --if(@tiBoxMsgInTypeId in (20,22,114) and @dtSentDateTime IS not null)      
  --begin      
  --insert into SLSParam values(getdate(),isnull(cast(@intBoxID as varchar),',zz') + ' $ ' + isnull(cast(@dtOriginDateTime as varchar),',ZZ') + ' $ ' +      
  --isnull(cast(@dtDateTimeReceived as varchar),',zz') + ' $ ' + isnull( @vcCommMode,',zz') + ' $ ' + isnull( cast(@tiBoxMsgInTypeId as varchar),',zz') + ' $ ' +      
  --isnull(@vcBoxProtocolTypeName,',zz') + ' $ ' + isnull(@vcCommInfo1,',zz') + ' $ ' + isnull(cast(@siCommInfo2 as varchar),',zz') + ' $ ' +      
  --isnull(cast(@tiValidGps as varchar),',zz') + ' $ ' + isnull(cast(@dLatitude as varchar),',zz') + '$' + isnull(cast(@dLongitude as varchar),',zz') + ' $ ' +      
  --isnull(cast(@tiSpeed as varchar),',zz') + ' $ ' + isnull(cast(@siHeading as varchar),',zz') + ' $ ' + isnull(@vcSensorMask,',zz') + ' $ ' +      
  --isnull(@vcCustomProp,',zz') + ' $ ' + isnull( cast(@bigSequenceNum as varchar),',zz') + ' $ ' + isnull( cast(@bitIsArmed as varchar),',zz') + ' $ ' +      
  --isnull(cast(@tiPriority as varchar),',zz') + ' $ ' + isnull( cast(@bitIsAlarm as varchar),',zz') + ' $ ' + isnull(cast(@dtSentDateTime as varchar),',zz') + ' $ ' +      
  --isnull(cast(@bitIgnitionStatus as varchar),',zz') + ' $ ' + isnull(cast(@bigOdoMeterReading as varchar),',zz'))      
  --end      
  if(@intboxid = 0 and @tiBoxMsgInTypeId = 20)  
  Begin  
 Set @intboxid = (select Top 1 BoxId from rvlfMsgOutHst where CommInfo1 = @vcCommInfo1 and CommInfo2 = @siCommInfo2 and SUBSTRING(CustomProp, 10, 7) =  SUBSTRING(@vcCustomProp, 11, 7) order by SentDateTime desc )   
 Set @dtSentDateTime = (select Top 1 SentDateTime from rvlfMsgOutHst where CommInfo1 = @vcCommInfo1 and CommInfo2 = @siCommInfo2 and SUBSTRING(CustomProp, 10, 7) =  SUBSTRING(@vcCustomProp, 11, 7) order by SentDateTime desc)   
  End  
  
  DECLARE @bigOrganizationID bigint=(SELECT OrganizationID FROM rvlfBoxId with(nolock) WHERE BoxId = @intBoxID)      
  declare @OrganizationPackage table (packageid bigint,Moduleid bigint,operationid bigint,OperationTypeName varchar(500),operationdesc varchar(500))      
 
 if(@tiBoxMsgInTypeId in (121,158,188,113,96)) --22-07-2020 to avoid unwanted msg in msginhst table and track any repeated msg due to device issue 
 begin
 INSERT INTO rvlfmsginhst_resetmsg      
          (      
          BoxID , OriginDateTime , DateTimeReceived , ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,      
          CommInfo2 , ValidGps , Latitude ,Longitude , Speed , Heading , SensorMask , CustomProp , SequenceNum ,      
          IsArmed , Priority , StreetAddress, NearestLandmark , IsNotificationSent,odometer,IsProcessed,IsArchived      
          )               
          VALUES      
          (      
          @intBoxID , @dtOriginDateTime , @dtDateTimeReceived , 4 ,@tiBoxMsgInTypeId, 1 , @vcCommInfo1 ,      
          @siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed ,-1 , @vcSensorMask , @vcCustomProp , @bigSequenceNum ,      
          @bitIsArmed , @tiPriority ,CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,NULL,0,CAST(@odoValue_app as bigint),      
          CASE WHEN @tiValidGps = 0 THEN 1 ELSE NULL END,0      
          ) 
 end 
  --IF @intBoxID NOT IN (481,482,6846,358480082009731, 358480082009657, 358480082009491) and @tiBoxMsgInTypeId not in(188,113,121,158) --  
  else --IF @intBoxID NOT IN (8717,8768) and @tiBoxMsgInTypeId not in(96,188,113,158) -- ,121 commented 22-07-2020
   BEGIN      
    Declare @SMSbasedQueryError int = 0      
    IF @tiBoxMsgInTypeId = 114 and (@vcCustomProp like '%SendSMSQuery:1%')      
     Begin      
      select @intBoxID = va.BoxId from rvlfVehicleAssignment va with(nolock) inner join rvlfVehicle v on v.VehicleId =va.VehicleId      
      where v.VehicleDescription =      
      SUBSTRING(@vcCustomProp, CHARINDEX('VehicleName:',@vcCustomProp,0)+12,(CHARINDEX(';',@vcCustomProp,CHARINDEX('VehicleName:',@vcCustomProp,1))) -(CHARINDEX('VehicleName:',@vcCustomProp,1)+12))      
      DECLARE @CommandId Bigint      
      DECLARE @MobileNo varchar(20),@VCSmsMsg varchar(max),@VCSmsMsgUserRights varchar(max)      
      Declare @SMSAlertMsgs varchar(max)      
      Declare @Userid varchar(50),      
      @OrganizationID varchar(50),      
      @UserName varchar(50),      
      @Email varchar(50),      
      @FleetId varchar(50),      
      @FleetName varchar(500)      
      Declare @VehicleID varchar(50),@VehicleDescription varchar(50),@VehicleName varchar(50),@LicensePlate varchar(50)      
      SELECT @MobileNo = CAST(REPLACE(SUBSTRING(@vcCustomProp, CHARINDEX('MobileNo:',@vcCustomProp,0)+9,(CHARINDEX(';',@vcCustomProp,CHARINDEX('MobileNo:',@vcCustomProp,1))) -(CHARINDEX('MobileNo:',@vcCustomProp,1)+9)),'+','') AS bigint),      
      @CommandId = SUBSTRING(@vcCustomProp, CHARINDEX('Command:',@vcCustomProp,0)+8,LEN(@vcCustomProp))      
      Select @OrganizationID=OrganizationId,@UserName=UserName,@Email=Email,@Userid=UserId from rvlfuser where MobileNo = @MobileNo --set @MobileNo = 9585846164      
      set @VCSmsMsgUserRights = dbo.rvlf_fn_GetSMSCommandUserRights(@MobileNo,@intBoxID)      
      if @VCSmsMsgUserRights <> '' and @VCSmsMsgUserRights is not null --and @intBoxID <> ''      
       Begin      
        Set @VCSmsMsg = @VCSmsMsgUserRights      
       end      
      Else    
       Begin      
        Set @VCSmsMsg = dbo.rvlf_fn_GetSMSCommand(@CommandId,@vcCustomProp)      
       End      
      if @intBoxID = '' or @VCSmsMsgUserRights <> ''      
       Begin      
        If @VCSmsMsgUserRights <> '' and @VCSmsMsgUserRights is not null --and @intBoxID <> ''      
        Set @SMSAlertMsgs = @VCSmsMsg      
        Else IF @CommandId = 255 --and @VCSmsMsgUserRights ='' and @VCSmsMsgUserRights is null      
        Set @SMSAlertMsgs = 'Invalid command. Send Tri HELP to know the available commands and inputs.'      
        Else IF @CommandId = 254 --and @VCSmsMsgUserRights ='' and @VCSmsMsgUserRights is null      
        Set @SMSAlertMsgs = @VCSmsMsg      
        Else --if @VCSmsMsgUserRights ='' and @VCSmsMsgUserRights is null      
        Set @SMSAlertMsgs = 'Please check the vehicle name and resend the command.'      
        --_SendSMSTest      
        insert into rvlfNotificationLog(MessageInID,OriginDateTime,DateTimeReceived,CanSendSMS,IsSMSSent,Userid,OrganizationID,      
        UserName,Email,MobileNo,StreetAddress,Speed,Boxid,BoxMsgInTypeName,VehicleID,VehicleDescription,      
        VehicleName,Fleetid,Fleetname,LicensePlate,Subjectsufix,MessageDetails,CanSendEmail,SMSScheduleID)      
        values      
        (null,@dtOriginDateTime,@dtOriginDateTime,1,0,@Userid,@OrganizationID,@UserName,@Email,@MobileNo,      
        'N/A',0,000,@tiBoxMsgInTypeId,null,null,null,null,null,null,'Notify',@SMSAlertMsgs,0,0)      
        set @SMSbasedQueryError = 1      
       End      
     End      
    if @intBoxID <> 000 -- Validating Boxid for SMS based Query      
     Begin      
      IF @bitIsTrinetraApp = 1 AND @ModelNo IS NOT NULL      
       BEGIN      
        --For mobile application      
        DECLARE @MsgInID_App TABLE (uiMsgInID uniqueidentifier)      
        DECLARE @uiMsgInID_App uniqueidentifier      
        DECLARE @orgId int      
        DECLARE @dtLastValidGPSTime_app datetime      
        SELECT @intBoxID = mb.BoxID,@orgId=b.OrganizationId FROM rvlfModelBoxSettings_App mb      
        INNER JOIN rvlfModel_App ap ON ap.ModelId=mb.ModelId      
        INNER JOIN rvlfBoxId b ON b.BoxId=mb.BoxId WHERE ap.ModelCode=@ModelNo      
        IF @intBoxID IS NULL      
         BEGIN      
          RAISERROR('Given asset details not mapped in the software side', 16,1)      
         END      
        ELSE      
         BEGIN      
          --Last valid location update      
          IF @tiValidGps =3 BEGIN SELECT @tiValidGps =0,@tiBoxMsgInTypeId=8 END      
          --Preference settings ack received      
          IF @IsPrefAck = 1 BEGIN UPDATE dbo.rvlfModel_App SET IsChanged= 0 WHERE ModelCode=@ModelNo END      
          --If message is alarm, set type      
          IF @bitIsAlarm =1 AND @vcCustomProp NOT LIKE '%Param=Preference Changed%' AND @tiValidGps <> 3 BEGIN SET @tiBoxMsgInTypeId = 4 END      
          --If datetime received is lesser than origin datetime      
          IF @dtDateTimeReceived < @dtOriginDateTime BEGIN SET @dtDateTimeReceived = DATEADD(SECOND,3,@dtOriginDateTime) END      
          -- Log mobile messages into server      
          INSERT INTO rvlfMsgInHSt      
          (      
          BoxID , OriginDateTime , DateTimeReceived , ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,      
          CommInfo2 , ValidGps , Latitude ,Longitude , Speed , Heading , SensorMask , CustomProp , SequenceNum ,      
          IsArmed , Priority , StreetAddress, NearestLandmark , IsNotificationSent,odometer,IsProcessed,IsArchived      
          )      
          OUTPUT INSERTED.MessageInID into @MsgInID_App      
          VALUES      
          (      
          @intBoxID , @dtOriginDateTime , @dtDateTimeReceived , 4 ,@tiBoxMsgInTypeId, 1 , @vcCommInfo1 ,      
          @siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed ,-1 , @vcSensorMask , @vcCustomProp , @bigSequenceNum ,      
          @bitIsArmed , @tiPriority ,CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,NULL,0,CAST(@odoValue_app as bigint),      
          CASE WHEN @tiValidGps = 0 THEN 1 ELSE NULL END,0      
          )      
          SELECT @uiMsgInID_App = uiMsgInID FROM @MsgInID_App      
          --For display the current location of mobile devices      
          IF @tiValidGps <> 0      
           BEGIN      
            SELECT @dtLastValidGPSTime_app = ISNULL(max(OriginDateTime), @dtOriginDateTime) FROM rvlfMsgInHst WHERE BoxId = @intBoxID and ValidGps = 0 --and SensorMask IS NOT NULL      
           END      
          DECLARE @dtLastValidDateTime_app DateTime=(SELECT LastValidDateTime FROM rvlfBoxId WHERE BoxId = @intBoxID)      
          -- Checks if the last information exists for the box, if so updates else inserts      
          IF @dtOriginDateTime >= @dtLastValidDateTime_app AND @tiBoxMsgInTypeId NOT IN (121,188)      
           BEGIN      
            UPDATE rvlfBoxId SET BoxArmed = 1,LastValidDateTime = CASE WHEN @tiValidGps = 0 THEN @dtOriginDateTime ELSE LastValidDateTime END,      
            LastLatitude = @dLatitude,LastLongitude = @dLongitude,LastSpeed = @tiSpeed,      
            LastCommunicatedDateTime = @dtDateTimeReceived,LastSensorMask = @vcSensorMask,OrganizationId = @orgId,      
            LastStatusDateTime = @dtOriginDateTime,LastStreetAddress = CASE WHEN @tiValidGps = 0 THEN NULL ELSE LastStreetAddress END,      
            NearestLandmark = CASE WHEN @tiValidGps = 0 THEN NULL ELSE NearestLandmark END,Heading = @siHeading,MessageInId = @uiMsgInID_App      
            WHERE BoxId = @intBoxID      
           END      
          --If message is alarm      
          IF @bitIsAlarm =1      
           BEGIN      
            INSERT INTO rvlfAlarm(AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,DriverId)      
             VALUES(3,@dtOriginDateTime,@intBoxID,91,@dLatitude,@dLongitude,@AlarmDesc_app,(CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END), NULL)       
           END      
          --Get the preference settings      
          SELECT a.ModelId,a.ModelCode,CASE WHEN ISNULL(a.IsChanged,0)=0 THEN '0' ELSE '1' END AS IsChanged FROM dbo.rvlfModel_App a      
          INNER JOIN rvlfModelBoxSettings_App bx ON bx.ModelId=a.ModelId WHERE ModelCode=@ModelNo      
          --SELECT ModelId,ModelCode,ISNULL(IsChanged,0) AS IsChanged FROM dbo.rvlfModel_App WHERE ModelCode=@ModelNo      
         END      
       END      
      ELSE      
       BEGIN      
        IF (@tiBoxMsgInTypeId <> 52)      
         BEGIN--CONDITION 01 START      
          DECLARE @tintSensor tinyint=CASE WHEN @vcCustomProp LIKE '%SENSOR_NUM=%' THEN      
          CAST(dbo.rvlf_fn_getparamvaluewithindex(@vccustomprop,'SENSOR_NUM=',';')AS TINYINT) ELSE 0 END      
          --SUBSTRING(@vcCustomProp,CHARINDEX('%SENSOR_NUM=%',@vcCustomProp,0)+12,(CHARINDEX(';',@vcCustomProp,(CHARINDEX('%SENSOR_NUM=%',@vcCustomProp,0)))-(CHARINDEX('%SENSOR_NUM=%',@vcCustomProp,0)+12)))      
          DECLARE @tintBoxgnore tinyint=(SELECT COUNT(igid) FROM rvlfboxignoremsgs WHERE BOXID =@intBoxID AND      
          BOXMSGINTYPEID=@tiBoxMsgInTypeId AND SENSORNO=@tintSensor)      
          IF(@tintBoxgnore=0)      
          DECLARE @tintOrgIgnore tinyint=(SELECT count(igid) FROM rvlforgignoremsgs WHERE ORGID =@bigOrganizationID      
          AND BOXMSGINTYPEID=@tiBoxMsgInTypeId AND SENSORNO=@tintSensor)      
          --CHECK THE IGNORE MESSAGES BASED ON THE RVLFBOXIGNOREMSGS TABLE      
          IF(@tintBoxgnore=0)      
          IF(@tintOrgIgnore=0)      
           BEGIN      
            IF Exists (SELECT MessageInID FROM rvlfMsgInHst with(nolock) WHERE BoxId = @intBoxID AND BoxMsgInTypeId = @tiBoxMsgInTypeId      
            AND OriginDateTime = @dtOriginDateTime and CustomProp=@vcCustomProp)      
             BEGIN      
              RAISERROR('Data Integrity Violation1', 16,1)      
             END      
            ELSE      
             BEGIN--CONDITION 02 START      
              -- Local variables to hold the intermediate results      
              IF @intBoxID = 999986      
               BEGIN      
                SET @dLatitude = '12.920182'      
                SET @dLongitude = '77.679921'      
                SET @tiValidGps = 0      
               END      
              DECLARE @ErrorMessage varchar(3000)      
              DECLARE @intBoxProtocolTypeId int      
              DECLARE @tiServiceID tinyint      
              DECLARE @tiCommModeId tinyint      
              DECLARE @MsgInID TABLE ( uiMsgInID uniqueidentifier)      
              DECLARE @uiMsgInID1 uniqueidentifier      
              DECLARE @uiMsgInID uniqueidentifier      
              DECLARE @vcNewIP varchar(25)      
              SET @vcNewIP = @vcCommInfo1 + ':'+ CAST(@siCommInfo2 AS varchar(5))      
              DECLARE @dtLastValidGPSTime datetime      
              DECLARE @bitCreateAlarm bit      
              DECLARE @tiAlarmLevelID tinyint      
              DECLARE @bigGeoZoneID bigint      
              DECLARE @vcAlarmLevelName varchar(30)      
              /********** demo*************/      
              DECLARE @DemoMsgInID TABLE ( uiDemoMsgInID uniqueidentifier)      
              DECLARE @uiDemoMsgInID uniqueidentifier      
              DECLARE @vcOldIP varchar(25)      
              SET @vcNewIP = @vcCommInfo1 + ':'+ CAST(@siCommInfo2 AS varchar(5))      
              --DECLARE @bitCanNotify bit      
              SET @dtLastValidGPSTime = @dtOriginDateTime      
              DECLARE @IsAddressAlreadyAvailable bit = 0      
              DECLARE @vcStreetAddress varchar(250)      
   DECLARE @vcNearestLandmark varchar(300)      
              /*********end *****************/      
              SET @dtLastValidGPSTime = @dtOriginDateTime      
              --update the origindatetime if origindatetime is greater then current date time      
              IF(@dtOriginDateTime>CONVERT(datetime,CONVERT(varchar(19),SYSUTCDATETIME())))      
               BEGIN      
                SET @dtOriginDateTime=CONVERT(datetime,CONVERT(varchar(19),SYSUTCDATETIME()))      
               END      
              --update the datetimerecived if datetimerecived is greater then origindatetime      
              IF(@dtOriginDateTime>=@dtDateTimeReceived)      
               BEGIN      
                SET @dtDateTimeReceived=DATEADD(S,2,@dtOriginDateTime)      
               END      
              IF(@tiBoxMsgInTypeId=100 AND CHARINDEX('RF_ID=',@vcCustomProp,0) > 1)      
               BEGIN --RFID Automate Schedule START      
                SET @vcSensorMask='00000000'      
                DECLARE @rfDRIVERID BIGINT=NULL      
          SELECT @rfDRIVERID=DriverId FROM rvlfIButtonMapping      
                WHERE IButtonKey=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RF_ID=',';') AND OrganizationId=@bigOrganizationID      
                -- updated BoxID aganist Driver based on Ibutton punch      
                DECLARE @rfResult varchar(5)      
                DECLARE @dtRFPunchIn DATETIME=NULL,@AssignmentId INT = NULL      
                SET @rfResult = dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'Punch:',';')      
                IF @rfDRIVERID IS NOT NULL      
                 BEGIN      
                  IF(@rfResult='OUT')      
                   BEGIN      
                    SELECT TOP 1 @AssignmentId=AssignmentId,@dtRFPunchIn=PunchIn FROM rvlfDriverAssignment      
                    WHERE BoxID=@intBoxID AND DriverId=@rfDRIVERID AND PunchOut IS NULL ORDER BY PunchIn DESC      
                    IF(@dtRFPunchIn IS NOT NULL)      
                     BEGIN      
                      UPDATE rvlfDriverAssignment SET PunchIn =@dtRFPunchIn,PunchOut=@dtOriginDateTime WHERE BOXID=@intBoxID AND DriverId=@rfDRIVERID AND AssignmentId=@AssignmentId AND PunchIn=@dtRFPunchIn      
                     END      
                   END      
                  ELSE      
                   BEGIN      
                    IF EXISTS (SELECT 1 FROM rvlfDriverAssignment WHERE BoxId=@intBoxID AND PunchIn IS NOT NULL AND PunchOut IS NULL AND DriverId=@rfDRIVERID)      
                     BEGIN      
                     UPDATE rvlfDriverAssignment SET PunchOut=DATEADD(SECOND,-30,@dtOriginDateTime) WHERE BoxId=@intBoxID AND PunchIn IS NOT NULL AND PunchOut IS NULL AND DriverId=@rfDRIVERID      
                     END      
                    INSERT INTO rvlfDriverAssignment(DriverId,PunchIn,PunchOut,BOXID,AssignmentDate,IsAmtIssued,AssignedDate)      
                    VALUES(@rfDRIVERID,@dtOriginDateTime,NULL,@intBoxID,CONVERT(DATE,GETDATE()),0,GETDATE())      
                   END      
                 END      
               END--RFID Automate Schedules END      
              --update driver key messages      
              IF(@tiBoxMsgInTypeId=76)      
               BEGIN --CONDITION 03 START      
                SET @vcCustomProp=@vcCustomProp+'ignition='+CAST(@bitIgnitionStatus as varchar)+';'      
                SET @vcSensorMask='00000000'      
                DECLARE @DRIVERID BIGINT=NULL      
                SELECT @DRIVERID=DriverId FROM rvlfIButtonMapping      
                WHERE IButtonKey=CASE WHEN @vcCustomProp LIKE '%Driver ID=%'      
                THEN CAST(SUBSTRING (@vcCustomProp,CHARINDEX('Driver ID=',@vcCustomProp,1)+10,      
                CHARINDEX(';',@vcCustomProp,CHARINDEX('Driver ID=',@vcCustomProp,1)) -      
                (CHARINDEX('Driver ID=',@vcCustomProp,1)+10)) as varchar) ELSE '0' END AND OrganizationId=@bigOrganizationID      
                -- updated BoxID aganist Driver based on Ibutton punch      
                DECLARE @result varchar(5)      
                SET @result = CASE WHEN @vcCustomProp LIKE '%Driver Status=%'      
                THEN CAST(SUBSTRING (@vcCustomProp,CHARINDEX('Driver Status=',@vcCustomProp,1)+14,      
                CHARINDEX(';',@vcCustomProp,CHARINDEX('Driver Status=',@vcCustomProp,1)) - (CHARINDEX('Driver Status=',@vcCustomProp,1)+14)) as varchar) ELSE 'OUT' END      
                IF(@result='OUT')      
                 BEGIN      
                  DECLARE @dtPunchin DATETIME=NULL      
                  SELECT @dtPunchin=PUNCHINTIME FROM rvlfIButtonMapping WHERE BoxID=@intBoxID AND DriverId=@DRIVERID      
                  IF(@dtPunchin IS NOT NULL)      
                   BEGIN      
                    IF EXISTS(SELECT AssignmentId FROM rvlfDriverAssignment WHERE BOXID=@intBoxID AND DriverId=@DRIVERID AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime)     
     AND CONVERT(DATE,ToTime)) AND (@dtPunchin <=ToTime) AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime) AND PunchIn IS NULL AND PunchOut IS NULL)      
             BEGIN      
                      UPDATE rvlfDriverAssignment SET PunchIn =@dtPunchin,PunchOut=@dtOriginDateTime      
                      WHERE BOXID=@intBoxID AND DriverId=@DRIVERID      
                      AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime)      
                      AND CONVERT(DATE,ToTime)) AND (@dtPunchin <=ToTime)      
                      AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime)      
                      AND PunchIn IS NULL AND PunchOut IS NULL      
                     END      
                    ELSE IF EXISTS(SELECT AssignmentId FROM rvlfDriverAssignment WHERE BOXID=@intBoxID AND DriverId=@DRIVERID AND (CONVERT(DATE,@dtOriginDateTime)     
     BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime)) AND (@dtPunchin <=ToTime) AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime) AND     
     PunchIn IS NOT NULL AND PunchOut IS NOT NULL)      
                     BEGIN      
                      INSERT INTO rvlfDriverAssignment(DriverId,FromTime,ToTime,PunchIn,PunchOut,BOXID,AssignmentDate,IsAmtIssued,AssignedDate)      
                      SELECT TOP 1 @DRIVERID,FromTime,ToTime,@dtPunchin,@dtOriginDateTime,@intBoxID,CONVERT(DATE,GETDATE()),0,GETDATE()      
                      FROM rvlfDriverAssignment      
                      WHERE BOXID=@intBoxID AND DriverId=@DRIVERID      
                      AND (CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime))      
                      AND (@dtPunchin <=ToTime)      
                      AND ((@dtOriginDateTime<=ToTime AND @dtOriginDateTime>FromTime) OR @dtOriginDateTime>ToTime)      
                      AND PunchIn IS NOT NULL AND PunchOut IS NOT NULL      
                     END      
                    ELSE      
                     BEGIN      
                      INSERT INTO rvlfDriverAssignment(DriverId,PunchIn,PunchOut,BOXID,AssignmentDate,IsAmtIssued,AssignedDate)      
                      VALUES(@DRIVERID,@dtPunchin,@dtOriginDateTime,@intBoxID,CONVERT(DATE,GETDATE()),0,GETDATE())      
                     END      
                   END      
                 END      
                UPDATE RVLFIButtonMapping SET Boxid = CASE WHEN @result = 'IN' THEN @intBoxID ELSE 0 END,      
                PunchInTime=CASE WHEN @result = 'IN' THEN @dtOriginDateTime ELSE NULL END WHERE DriverId = @DRIVERID      
                IF(@DRIVERID IS NOT NULL)      
                 BEGIN      
                  SET @vcCustomProp=@vcCustomProp+'MAPID='+CAST(@DRIVERID as varchar)      
                 END      
                ELSE      
                 BEGIN      
                  SET @vcCustomProp=@vcCustomProp+'MAPID=0'      
                 END      
               END--CONDITION 03 END    
              --GET THE PROTOCOLID BASED ON THE PROTOCOL NAME      
              SELECT @intBoxProtocolTypeId = BoxProtocolTypeId FROM rvlfBoxProtocolType WHERE BoxProtocolTypeName = @vcBoxProtocolTypeName      
              --GET THE COMMAND MODE ID BASED ON THE COMMANDMODE NAME      
              SELECT @tiCommModeId = CommModeId FROM rvlfCommMode WHERE CommModeName = @vcCommMode      
              --GET THE PROTOCOLID BASED ON THE PROTOCOL NAME      
              SELECT @tiServiceID = ServiceID FROM rvlfServices WHERE CommModeId = @tiCommModeId      
              /***************************Severity Settings**********************************/      
              -- Checks if the message has the severity settings such that an alarm has to be created.      
              IF EXISTS (SELECT BoxId FROM rvlfBoxMsgSeverity WHERE BoxId=@intBoxID AND BoxMsgInTypeId = @tiBoxMsgInTypeID)      
               BEGIN      
                DECLARE @intDuration int = 1      
                IF @tiBoxMsgInTypeId = 9      
                 BEGIN      
                  SET @intDuration = CAST (SUBSTRING (@vcCustomProp, CHARINDEX(':',@vcCustomProp,1)+1, CHARINDEX(';',@vcCustomProp)-1 -CHARINDEX(':',@vcCustomProp,1)) as Int)      
 END      
                IF @intDuration > 0      
                 BEGIN      
                  SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.AlarmLevelID, @vcAlarmLevelName = s.AlarmLevelName FROM rvlfBoxMsgSeverity bs INNER JOIN rvlfSeverity s On bs.AlarmLevelID = s.AlarmLevelId WHERE bs.BoxId = @intBoxID   
      AND bs.BoxMsgInTypeId = @tiBoxMsgInTypeID      
                 END      
               END      
              ELSE      
               BEGIN      
                SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.DefaultAlarmLevel,@vcAlarmLevelName = s.AlarmLevelName FROM rvlfBoxProtocolMsgInType bs INNER JOIN rvlfSeverity s On bs.DefaultAlarmLevel = s.AlarmLevelId WHERE bs.BoxMsgInTypeId



   
    
= @tiBoxMsgInTypeID      
               END      
              IF @tiBoxMsgInTypeId =5 OR @tiBoxMsgInTypeId =6      
               BEGIN
				set @bigGeoZoneID=cast(dbo.rvlf_fn_getparamvaluewithindex(@vccustomprop,'GeozoneID=',';') as bigint)
                --SET @bigGeoZoneID =CAST(SUBSTRING(@vcCustomProp,CHARINDEX('=',@vcCustomProp,1)+1, (CHARINDEX(';',@vcCustomProp,1)- CHARINDEX('=',@vcCustomProp,1))-1) as bigint)      
                SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = s.AlarmLevelId, @vcAlarmLevelName = s.AlarmLevelName FROM rvlfOrganizationGeozone g INNER JOIN rvlfSeverity s ON g.SeverityId = s.AlarmLevelId   
    WHERE g.OrganizationId = @bigOrganizationID AND g.GeozoneId = @bigGeoZoneID
				
				--Update rvlfBoxId set LastGeoZoneStatus= case when @tiBoxMsgInTypeId=5 then 1 else case when @tiBoxMsgInTypeId=6 then 0 end end,LastGeozoneID=@bigGeoZoneID,LastGeozoneINOUTdt=@dtOriginDateTime where BoxId=@intboxid
               END      
              IF @tiBoxMsgInTypeId = 11      
               BEGIN      
                DECLARE @tiSensorID tinyint,@intSensorStateStart int,@intSensorStateEnd int, @vcSensorStatus varchar(10),@bitIsOn bit      
                SET @tiSensorID = CAST(SUBSTRING(@vcCustomProp,CHARINDEX('=',@vcCustomProp)+1,1) As tinyint)      
                SET @intSensorStateStart = CHARINDEX('=',@vcCustomProp,LEN('SENSOR_NUM=')+1)      
                SET @intSensorStateEnd = CHARINDEX(';',@vcCustomProp,15)      
                SET @vcSensorStatus =      
                CASE WHEN @vcCustomProp LIKE '%SENSOR_STATUS=%' THEN dbo.rvlf_fn_getparamvaluewithindex(@vccustomprop,'SENSOR_STATUS=',';')      
                -- SUBSTRING(@vcCustomProp,CHARINDEX('SENSOR_STATUS=',@vcCustomProp,0)+14,      
                -- (CHARINDEX(';',@vcCustomProp,(CHARINDEX('SENSOR_STATUS=',@vcCustomProp,0)))-(CHARINDEX('SENSOR_STATUS=',@vcCustomProp,0)+14)))      
                ELSE SUBSTRING(@vcCustomProp,@intSensorStateStart+1, @intSensorStateEnd - @intSensorStateStart-1)END      
                SET @bitIsOn = CASE WHEN @vcSensorStatus = 'OPEN' OR @vcSensorStatus = 'ON'      
                OR @vcSensorStatus = 'NORMAL' OR @vcSensorStatus = 'OK' THEN 1      
                WHEN @vcSensorStatus = 'CLOSE' OR @vcSensorStatus = 'OFF' OR @vcSensorStatus = 'LOW' THEN 0      
                END      
             IF EXISTS (SELECT BoxId FROM rvlfBoxSensorsCfg WHERE BoxId = @intBoxID AND SensorId = @tiSensorID)      
                 BEGIN      
                  SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = s.AlarmLevelId, @vcAlarmLevelName = s.AlarmLevelName FROM rvlfBoxSensorsCfg bs INNER JOIN rvlfSeverity s ON s.AlarmLevelId = (CASE WHEN @bitIsOn=1 THEN bs.AlarmLevelOn   
      ELSE AlarmLevelOff END) WHERE bs.BoxId = @intBoxID AND bs.SensorId = @tiSensorID      
                 END      
                ELSE      
                 BEGIN      
                  SELECT @bitCreateAlarm = s.CreateAlarm,@tiAlarmLevelID = bs.DefaultAlarmLevel, @vcAlarmLevelName = s.AlarmLevelName FROM rvlfBoxProtocolMsgInType bs INNER JOIN rvlfSeverity s On bs.DefaultAlarmLevel = s.AlarmLevelId   
      WHERE bs.BoxMsgInTypeId = @tiBoxMsgInTypeID      
                 END      
               END      
              IF @tiBoxMsgInTypeId = 27      
               BEGIN      
                SET @bitCreateAlarm = 1      
               END      
              IF @tiBoxMsgInTypeId IN (14,15,16,17)      
               BEGIN      
                SET @tiSpeed = 0      
               END      
              DECLARE @trancount int;      
              SET @trancount = @@trancount;      
              --PRINT CAST(@trancount as varchar)      
               BEGIN TRY      
                IF @trancount = 0      
                BEGIN TRANSACTION;      
            ELSE      
                SAVE TRANSACTION MessageTransaction;      
                /***********************Message In History*************************************/      
                --BEGIN TRAN MessageTransaction      
                --BEGIN TRY      
                --PRINT 'Welcome 1'      
				
				 IF EXISTS(select * from rvlfRouteVehicleAssignment rva inner join rvlfRouteVehicleAssignmentDetails RVAD on RVA.AssignmentId=RVAD.AssignmentId inner join rvlfVehicleAssignment va on rva.VehicleId = va.VehicleId where BoxId =@intboxid and rva.TripStatus=2 and CONVERT(date,RVAD.AssignmentDate) = CONVERT(Date,GETDATE()))
					BEGIN
						--Karthick
						
						declare @landmarkID bigint=0
						declare @NearLandmarkList table(ID int identity(1,1),LandmarkID Bigint)

						SET @landmarkID = null        

						declare @tblRouteLandmark table(id int identity(1,1),AssignmentID bigint,RouteID bigint,TripStatus int,LandmarkID bigint)
						insert into @tblRouteLandmark(AssignmentID,RouteID,TripStatus,LandmarkID)
						select RVA.AssignmentId,RVA.RouteId,RVAD.TripStatus,RD.LndID from rvlfRouteVehicleAssignment RVA 
								inner join rvlfRouteVehicleAssignmentDetails RVAD on RVA.AssignmentId=RVAD.AssignmentId
								inner join rvlfRouteMaster RM on RVA.RouteId=RM.RouteID 
								inner join rvlfRouteDetails RD on RD.RouteID=RM.RouteID 
								inner join rvlfVehicleAssignment VA on RVA.VehicleId=VA.VehicleId
								where isnull(RVA.Isdelete,0)=0 and va.BoxId=@intboxid and RVAD.TripStatus=2 and CONVERT(date,RVAD.AssignmentDate) = CONVERT(Date,GETDATE())

						SELECT top 1 @landmarkID = A.LandmarkID FROM                 
						(select distinct L.LandMarkId,
									  ROUND((MIN(DEGREES(ACOS(
									  (                
							  SIN(RADIANS(L.Latitude)) *                                            
							  SIN(RADIANS(@dLatitude)) +                                            
							  COS(RADIANS(L.Latitude)) *                                            
							  COS(RADIANS(@dlatitude)) *                                            
							  COS(RADIANS(L.Longitude - @dLongitude))                
										  ) 
									  ))) * 69.09 * 1.609344),3) as Distance,CAST(CAST(L.Radius AS DECIMAL(8,4))/1000 as decimal(10,6)) as Radius                                              
						From rvlfLandMarK L WHERE --L.Latitude = @dlatitude and L.Longitude = @dlongitude AND 
						L.OrganizationId = @bigOrganizationID and L.LandmarkID in (Select RL.LandmarkID from @tblRouteLandmark RL)                
						group by L.LandMarkId,L.LandMarkName,L.Latitude,L.Longitude,L.Radius                
						) A WHERE A.Distance <= Radius                
						order by Distance asc   
						
						if(@landmarkID is not null)
							begin
								declare @ReturnCustomProp nvarchar(MAX)=null
								declare @routeID bigint=0
								select top 1 @routeID=RD.RouteId from @tblRouteLandmark RD where RD.LandmarkID=@landmarkID
								
								Exec rvlf_sp_GetNextStopID @intBoxID,@vcCustomProp,@landmarkID,@dtOriginDateTime,@routeID,@ReturnCustomProp output
								if(@ReturnCustomProp is not null)
									begin
										set @vcCustomProp=@ReturnCustomProp
									end
							end

						
					end

					


                IF @vcCustomProp not like '%ImgData:1%' -- CHARINDEX('ImgData:', @vcCustomProp) = 0      
                 begin      
                  PRINT 'Message Table'      
                  -- To insert the information in the message in history table      
                  INSERT INTO rvlfMsgInHSt      
                  (      
                  BoxID , OriginDateTime , DateTimeReceived ,      
                  ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,      
                  CommInfo2 , ValidGps , Latitude ,Longitude , Speed ,      
                  Heading , SensorMask , CustomProp , SequenceNum ,      
                  IsArmed , Priority , StreetAddress,IsNotificationSent,IsProcessed,IsArchived      
                  )      
                  OUTPUT INSERTED.MessageInID into @MsgInID      
                  VALUES      
                  (      
                  @intBoxID , @dtOriginDateTime , @dtDateTimeReceived ,      
                  @tiServiceID ,@tiBoxMsgInTypeId, @intBoxProtocolTypeId , @vcCommInfo1 ,      
                  @siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed ,      
                  @siHeading , @vcSensorMask , @vcCustomProp , @bigSequenceNum ,      
                  @bitIsArmed , @tiPriority ,      
                  CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,0,CASE WHEN @tiValidGps = 0 THEN 1 ELSE NULL END,0      
                  )      
                 End      
                IF @tiBoxMsgInTypeId = 114 and @vcCustomProp like '%ImgData:1%'      
                 BEGIN      
                  DECLARE @ImageID int      
                  DECLARE @CurrentPacket tinyint      
                  SELECT @ImageID = SUBSTRING(@vcCustomProp, CHARINDEX('Image ID:',@vcCustomProp,0)+9,      
                  (CHARINDEX(';',@vcCustomProp,CHARINDEX('Image ID:',@vcCustomProp,1))) -(CHARINDEX('Image ID:',@vcCustomProp,1)+9)),      
                  @CurrentPacket=SUBSTRING(@vcCustomProp, CHARINDEX('Current Packet:',@vcCustomProp,0)+15,      
                  (CHARINDEX(';',@vcCustomProp,CHARINDEX('Current Packet:',@vcCustomProp,1))) -(CHARINDEX('Current Packet:',@vcCustomProp,1)+15))      
                  IF NOT EXISTS (SELECT 1 FROM rvlfCameraImages WHERE BoxId=@intBoxID AND ImageID=@ImageID AND CurrentPacket=@CurrentPacket and CONVERT(date,ReceivedDate) = CONVERT(date,GETUTCDATE()))      
                   BEGIN      
                    INSERT INTO rvlfCameraImages      
                    (ReceivedDate,ImageID,BoxID,ImageData,ImageLength,CurrentPacket,TotalPackets)      
                    VALUES      
                    ( @dtOriginDateTime, @ImageID,@intBoxID,      
                    --SUBSTRING(@vcCustomProp, CHARINDEX('Image ID:', @vcCustomProp)+9,1),      
                    SUBSTRING(@vcCustomProp, CHARINDEX('Image Data:', @vcCustomProp)+11,LEN(@vcCustomProp)),      
                    SUBSTRING(@vcCustomProp, CHARINDEX('Image Length:',@vcCustomProp,0)+13,      
                    (CHARINDEX(';',@vcCustomProp,CHARINDEX('Image Length:',@vcCustomProp,1))) -(CHARINDEX('Image Length:',@vcCustomProp,1)+13)),      
                    @CurrentPacket,SUBSTRING(@vcCustomProp, CHARINDEX('Total Packets:',@vcCustomProp,0)+14,      
                    (CHARINDEX(';',@vcCustomProp,CHARINDEX('Total Packets:',@vcCustomProp,1))) -(CHARINDEX('Total Packets:',@vcCustomProp,1)+14))      
                    --SUBSTRING(@vcCustomProp, CHARINDEX('Current Packet:', @vcCustomProp)+15,1),      
                    --SUBSTRING(@vcCustomProp, CHARINDEX('Total Packets:', @vcCustomProp)+14,1)      
                    )      
                   END      
                 END      
                IF @tiBoxMsgInTypeId = 114 and (@vcCustomProp like '%SendSMSQuery:1%') and @SMSbasedQueryError = 0      
                 Begin      
                  Declare @VCCusProp varchar(max),@intBoxmsgintypeid int,@unMsginID varchar(max),@dtOrgDatetime datetime,@intSpeed bigint,      
                  @varStreetAddress varchar(max),@varBoxmsginTypeName varchar(max),      
                  @VarSensorStatus varchar(10), @VCCommandParam varchar(max), @VCCommand varchar(max),@intScheduleid int,      
                  @dtCmdCreateddate datetime,@dtcmdEnddate datetime      
                  set @VCSmsMsgUserRights = dbo.rvlf_fn_GetSMSCommandUserRights(@MobileNo,@intBoxID)      
                  select @intScheduleid = IDENT_CURRENT('rvlfScheduleOfCommandsMaster') + 1      
                  if @VCSmsMsgUserRights <> '' and @VCSmsMsgUserRights is not null      
                   Begin      
                    Set @VCSmsMsg = @VCSmsMsgUserRights      
                    set @intScheduleid = null      
                   end      
                  if @CommandId not in (254,255)      
                   Begin      
                    select @VehicleID =v.VehicleId,@VehicleDescription=v.VehicleDescription,@VehicleName=v.VehicleDescription,@LicensePlate=v.LicensePlate, @OrganizationID=v.OrganizationId,@FleetId=fv.FleetId,@FleetName=f.fleetname from rvlfVehicle v     

 
                    inner join rvlfvehicleassignment va with(nolock) on va.VehicleId=v.VehicleId      
                    inner join rvlfFleetVehicles fv on fv.VehicleId = v.VehicleId      
                    inner join rvlffleet f on f.fleetid = fv.fleetid      
                    where va.boxid = @intBoxID      
                   End      
                  SELECT @uiMsgInID1 = uiMsgInID FROM @MsgInID      
                  Set @dtCmdCreateddate =getutcdate()      
                  Set @dtcmdEnddate = dateadd(dd,1,getutcdate())      
                  Set @VCCommandParam = dbo.rvlf_fn_GetSMSCommandFrame(@intBoxID,@vcCustomProp)      
                  if @CommandId = 1      
                   Begin Set @VCCommand = '?' End      
                  else if @CommandId =2      
                   Begin Set @VCCommand = 'R' End      
                  else if @CommandId =3      
                   Begin Set @VCCommand = 'S' End      
                  --insert into rvlfSMSInHst(BoxId,Customprop,MessageInId,MobileNo,OriginDateTime,s) values(@intBoxID,@vcCustomProp,@unMsginID,@MobileNo,@dtOriginDateTime)      
                  if @CommandId not in (254,255) and @SMSbasedQueryError = 0      
                   Begin      
                    Exec [rvlf_sp_SaveAndUpdateAndDeleteSchedulingOfCommands] 0,0,@VCCommand,@VCCommandParam,@dtCmdCreateddate,@dtcmdEnddate,0,3,@Userid,@OrganizationID,@VehicleID,'any message in',@FleetId,@intBoxID      
                   end      
                  else if @VCSmsMsg like '%Invalid%' and @SMSbasedQueryError = 0      
                   Begin      
                    set @intScheduleid = null      
                   End      
                  --_SendSMSTest      
                  insert into rvlfNotificationLog(MessageInID,OriginDateTime,DateTimeReceived,CanSendSMS,IsSMSSent,Userid,OrganizationID,      
                  UserName,Email,MobileNo,StreetAddress,Speed,Boxid,BoxMsgInTypeName,VehicleID,VehicleDescription,      
                  VehicleName,Fleetid,Fleetname,LicensePlate,Subjectsufix,MessageDetails,CanSendEmail,SMSScheduleID)      
                  values      
                  (@uiMsgInID1,@dtOriginDateTime,@dtOriginDateTime,1,0,@Userid,@bigOrganizationID,@UserName,@Email,@MobileNo,      
                  null,0,@intBoxID,@tiBoxMsgInTypeId,@VehicleID,@VehicleDescription,@VehicleName,@FleetId,@FleetName,@LicensePlate,'Notify',      
                  @VCSmsMsg,0,@intScheduleid)      
                 End      
                SELECT @uiMsgInID = uiMsgInID,@Msgin=uiMsgInID FROM @MsgInID    
				 Declare @RouteAlertMsg varchar(3)=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'AlertMsg=',';'))      
							--Route ETA
					Declare @Route varchar(3)=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RouteID=',';'))                        

					if(@RouteAlertMsg='001')                          
						Begin                           
							--declare @msgid uniqueidentifier = (select MessageInID from rvlfMsgInHst where BoxId=@intBoxID and BoxMsgInTypeId=@tiBoxMsgInTypeId and MessageInID=@uiMsgInID order by OriginDateTime desc)
							update rvlfRouteETA set RouteStatus=2 where BoxID=@intBoxID and RouteStatus=0--2 incomplete route
							insert into rvlfRouteETA (BoxID,StartLocationDateTime,CustomProp,MessageInId,RouteStatus,StopStatus) values (@intBoxID,@dtOriginDateTime,@vcCustomProp,@uiMsgInID,0,@RouteAlertMsg)
						end
					if(@RouteAlertMsg='010' or @RouteAlertMsg='011')
						begin
							update rvlfRouteETA set CustomProp=@vcCustomProp,MessageInId=@uiMsgInID,StopStatus=@RouteAlertMsg where AutoNoETA in 
							(select top 1 AutoNoETA from rvlfRouteETA where BoxID=@intBoxID  and RouteStatus=0 and RouteID=@Route order by AutoNoETA desc)
						end
					if(@RouteAlertMsg='100')
						begin
							update rvlfRouteETA set CustomProp=@vcCustomProp,MessageInId=@uiMsgInID,RouteStatus=1,StopStatus=@RouteAlertMsg where AutoNoETA in 
							(select top 1 AutoNoETA from rvlfRouteETA where BoxID=@intBoxID  and RouteStatus=0 and RouteID=@Route order by AutoNoETA desc)
						end
                ----Data Movement for Global Scan Technologies---      
                --IF EXISTS(SELECT TOP 1 BoxId FROM rvlfBoxID WHERE BoxId=@intBoxID AND OrganizationId=242) AND      
                --@tiBoxMsgInTypeId IN (1,2,3,4,9,24,41,12,14,15,16,17)      
                --BEGIN TRY      
                -- INSERT INTO dbo.GlobalScan1(Unit_Id,Latitude,Latitude_Dir,Longitude,Longitude_Dir,UTC_Time,Speed,COG,Vt_date,      
                -- Vech_dist,Panic_Info,DubaiDateTime,currentdatetime,MessageId,IsProcessed)      
                -- VALUES(@intBoxID,CAST(@dLatitude AS FLOAT),(CASE WHEN SUBSTRING(CAST(@dLatitude AS VARCHAR),1,1)='-'THEN 'SOUTH' ELSE 'NORTH' END),      
                -- CAST(@dLongitude AS FLOAT),(CASE WHEN SUBSTRING(CAST(@dLongitude AS VARCHAR),1,1)='-'THEN 'WEST' ELSE 'EAST' END),GETUTCDATE(),@tiSpeed,      
                -- @siHeading,@dtOriginDateTime,      
                -- (CASE WHEN @vcCustomProp LIKE '%Odometer=%' THEN      
                -- CAST(SUBSTRING (@vcCustomProp,CHARINDEX('Odometer=',@vcCustomProp,1)+9,      
                -- CHARINDEX(';',@vcCustomProp,CHARINDEX('Odometer=',@vcCustomProp,1)) -      
                -- (CHARINDEX('Odometer=',@vcCustomProp,1)+9)) as bigint) ELSE 0 END),      
                -- dbo.[rvlf_fn_GetAlarmDetails_New](@vcCustomProp,@tiBoxMsgInTypeId,@intBoxID,NULL,NULL,NULL),DATEADD(HOUR,4,@dtOriginDateTime),      
                -- @dtDateTimeReceived,@uiMsgInID,1)      
                --END TRY      
                --BEGIN CATCH      
                -- PRINT 'END Global Scan'      
                --END CATCH      
                -----End--------------------------------------      
                ---------To update the duration from the custome prop to the Duration column------      
                UPDATE rvlfMsgInHst SET duration = (      
                CASE WHEN BoxMsgInTypeId = 3 AND customprop LIKE'%SENSOR_STATUS=OFF%' THEN SUBSTRING(SUBSTRING(customprop,CHARINDEX('SENSOR_DURATION=',customprop)+16,5),0,CHARINDEX(';',SUBSTRING(customprop,CHARINDEX('SENSOR_DURATION=',customprop)+16,5))) 

  
    
     
                WHEN BoxMsgInTypeId = 9 THEN SUBSTRING(customprop,8,CHARINDEX(';',customprop)-8)      
                ELSE NULL END), odometer = 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      
                WHERE MessageInID = @uiMsgInID      
                --PRINT 'Welcome 2'      
                --------------------------------------------------------------------------------------      
                /****************demo *****************/      
                -- Demo Entry Insertion      
                /*IF(@intDemoBoxID IS NOT NULL)      
                BEGIN      
                INSERT INTO rvlfMsgInHSt      
                (      
                BoxID , OriginDateTime , DateTimeReceived ,      
                ServiceID ,BoxMsgInTypeId ,BoxProtocolTypeId , CommInfo1 ,      
                CommInfo2 , ValidGps , Latitude ,Longitude , Speed ,      
                Heading , SensorMask , CustomProp , SequenceNum ,      
                IsArmed , Priority , StreetAddress, NearestLandmark , IsNotificationSent      
                )      
                OUTPUT INSERTED.MessageInID into @demoMsgInID      
                VALUES      
                (      
                @intDemoBoxID , @dtOriginDateTime , @dtDateTimeReceived ,      
                @tiServiceID ,@tiBoxMsgInTypeId, @intBoxProtocolTypeId , @vcCommInfo1 ,      
                @siCommInfo2 , @tiValidGps , @dLatitude , @dLongitude , @tiSpeed ,      
                @siHeading , @vcSensorMask , @vcCustomProp , @bigSequenceNum ,      
                @bitIsArmed , @tiPriority ,      
                CASE WHEN @tiValidGps = 0 THEN      
                CASE WHEN @IsAddressAlreadyAvailable = 1 AND @vcStreetAddress!='N/A' THEN @vcStreetAddress ELSE NULL END      
                ELSE 'N/A' END,      
                CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,0      
                --CASE WHEN @tiValidGps > 0 THEN 0 ELSE 0 END      
                )      
                SELECT @uiDemoMsgInID = uidemoMsgInID FROM @demoMsgInID      
                END*/      
                /*************end ***************************/      
                PRINT 'BoxId Table'      
                /******************************************************************************/      
                /****************************Box ID Table**************************************/      
                -- Inserts into the rvlfBoxID if sensor mask is available in the information.      
                IF @vcSensorMask IS NOT NULL AND LEN(@vcSensorMask) = 8 AND @tiBoxMsgInTypeId NOT IN (51,121,188) AND @tiValidGps <>2      
                 BEGIN      
                  IF @tiValidGps <> 0      
                   BEGIN      
                    SELECT @dtLastValidGPSTime = ISNULL(max(OriginDateTime), @dtOriginDateTime)      
                    FROM rvlfMsgInHst WHERE BoxId = @intBoxID and ValidGps = 0 --and SensorMask IS NOT NULL      
                   END      
                  DECLARE @dtLastValidDateTime DateTime=(SELECT LastValidDateTime FROM rvlfBoxId with(nolock) WHERE BoxId = @intBoxID)      
                  -- Checks if the last information exists for the box, if so updates else inserts      
                  IF @dtOriginDateTime >= @dtLastValidDateTime      
                   BEGIN      
                    UPDATE rvlfBoxId SET BoxArmed = @bitIsArmed,LastValidDateTime = CASE WHEN @tiValidGps = 0 THEN @dtOriginDateTime ELSE LastValidDateTime END,      
                    LastLatitude = CASE WHEN @tiValidGps = 0 THEN @dLatitude ELSE LastLatitude END,      
                    LastLongitude = CASE WHEN @tiValidGps = 0 THEN @dLongitude ELSE LastLongitude END,LastSpeed = @tiSpeed,      
                    LastCommunicatedDateTime = @dtDateTimeReceived,LastSensorMask = @vcSensorMask,OrganizationId = @bigOrganizationID,      
                    LastStatusDateTime = @dtOriginDateTime,LastStreetAddress = CASE WHEN @tiValidGps = 0 THEN NULL ELSE LastStreetAddress END,      
                    NearestLandmark = CASE WHEN @tiValidGps = 0 THEN NULL ELSE NearestLandmark END,Heading = @siHeading,MessageInId = @uiMsgInID      
                    WHERE BoxId = @intBoxID      
                   END      
                  ELSE IF(@dtLastValidDateTime IS NULL OR @dtLastValidDateTime='')      
                   BEGIN      
                 DELETE FROM rvlfBoxId WHERE BoxId=@intBoxID      
                    INSERT INTO rvlfBoxId      
                    (      
                    BoxId, BoxArmed, LastValidDateTime, LastLatitude, LastLongitude,      
                    LastSpeed, LastCommunicatedDateTime, LastSensorMask,      
                    OrganizationId, LastStatusDateTime, Heading , LastStreetAddress ,      
                    NearestLandmark, MessageInId      
                    )      
                    VALUES      
                    (      
                    @intBoxID, @bitIsArmed, @dtLastValidGPSTime, @dLatitude, @dLongitude,      
                    @tiSpeed, @dtDateTimeReceived, @vcSensorMask,      
                    @bigOrganizationID, @dtOriginDateTime, @siHeading,      
                    CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,      
                    CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,      
                    @uiMsgInID      
                    )      
                    /*********** demo **************/      
                    --Demo Acoount Mapping      
                    /*IF(@intDemoBoxID IS NOT NULL)      
                    BEGIN      
                    INSERT INTO rvlfBoxId      
                    (      
                    BoxId, BoxArmed, LastValidDateTime, LastLatitude, LastLongitude,      
                    LastSpeed, LastCommunicatedDateTime, LastSensorMask,      
                    OrganizationId, LastStatusDateTime, Heading , LastStreetAddress ,      
                    NearestLandmark, MessageInId      
                    )      
                    VALUES      
                    (      
                    @intDemoBoxID, @bitIsArmed, @dtLastValidGPSTime, @dLatitude, @dLongitude,      
                    @tiSpeed, @dtDateTimeReceived, @vcSensorMask,      
                    55, @dtOriginDateTime, @siHeading,      
                    CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,      
                    CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END,      
                    @uiDemoMsgInID )      
                    END */      
                    /*********end ************/      
                   END      
                 END      
                PRINT 'Alarm Table'      
                if (@tiBoxMsgInTypeId =187) --demo changes for accenture tilt sensor      
                 begin      
                  if(dbo.rvlf_fn_getparamvaluewithindex(@vcCustomProp,'Alertid=',';') in (1,2,3,5))      
                  set @bitIsAlarm = 1      
                  set @tiAlarmLevelID = 3      
                 end      
                /******************************************************************************/      
                /*************************Alarm Processing*************************************/      
                -- Inserts to Alarm table, if it is an alarm.      
                IF @bitIsAlarm = 1 Or @bitCreateAlarm = 1      
                 BEGIN      
                  DECLARE @siAlarmLevelID smallint,@bigDriverID bigint = NULL      
                  DECLARE @bigAlarmID bigint      
                  SELECT @bigDriverID = DriverId FROM RVLFIButtonMapping WHERE BoxID = @intBoxID      
                  IF(@bigDriverID IS NULL OR @bigDriverID='')      
                   BEGIN      
                    SELECT @bigDriverID = DriverId FROM rvlfDriverAssignment WHERE BoxID = @intBoxID      
                    AND @dtOriginDateTime BETWEEN FromTime AND ToTime      
                    AND CONVERT(DATE,@dtOriginDateTime) BETWEEN CONVERT(DATE,FromTime) AND CONVERT(DATE,ToTime)      
                    if(@bigDriverID IS NULL OR @bigDriverID='') --Included for rfid based driver 21-apr-2016 gopal for cotton blossom      
                     begin      
                      select top 1 @bigDriverID=DriverId FROM rvlfDriverAssignment WHERE BoxID = @intBoxID order by assignmentid desc      
                     end      
                   END      
                  --PRINT 'Welcome 3'      
                  IF(@tiAlarmLevelID is null OR @tiAlarmLevelID='')      
                   BEGIN      
                    SET @tiAlarmLevelID = 4 -- hardcoded to avoid AlarmLeveleID issue      
                   END      
                  PRINT 'Alarm 1 Table'      
                  INSERT INTO rvlfAlarm(AlarmLevelId,DateTimeCreated,BoxId,AlarmType,Lat,Long,[Description],StreetAddress,DriverId,CustomProp)      
                  VALUES(@tiAlarmLevelID,@dtOriginDateTime,@intBoxID,@tiBoxMsgInTypeId,@dLatitude,@dLongitude,      
                  CASE WHEN @tiBoxMsgInTypeId IN (5 , 6) THEN CAST(@bigGeoZoneID AS varchar(600))      
                  WHEN @tiBoxMsgInTypeId = 4 THEN CAST (@tiSpeed As Varchar(600))      
                  ELSE dbo.rvlf_fn_GetAlarmDetails_Optimzd(@vcCustomProp , @tiBoxMsgInTypeId, @intBoxID,@uiMsgInID, @dtOriginDateTime,'LanguageEn') END,      
                  CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END, @bigDriverID,@vcCustomProp)      
                  PRINT 'Alarm 1 END'      
                  --Student sms Trigger for alarm for unassigned geozone/vehicle 12-feb-2015 commented for LKD org temporarily      
                  IF(@tiBoxMsgInTypeId=100 and charindex('Punch:101',@vcCustomProp,1)>0 or charindex('Punch:110',@vcCustomProp,1)>0)      
                   Begin      
                    print 'Student alarm'      
                    Declare @punch varchar(30)= dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'Punch:',';')      
                    Insert into rvlfRFIDSchoolSMSNotification(StudentID,VehicleID,BoxID,GeozoneID,OrganizationId ,EntryExitTime ,RFID ,StudentName,ContactNo , MessageTemplate,MsgType, IsSMSSent)      
                    select S.StudentMasterID,va.VehicleID,@intBoxID,S.GeozoneId,S.OrganizationID,@dtOriginDateTime,S.RFID,S.StudentFirstName + +      
                    S.StudentLastName,S.ContactNo ,      
          CASE WHEN @punch ='101' THEN ('Name : '+ S.StudentFirstName + + S.StudentLastName + '\n Info: Boarded / Get down incorrect Location at : '+ CAST((dbo.rvlf_fn_DayLightSavings_Date(@dtOriginDateTime,O.OrganizationID,TZ.HoursToBeAdded, TZ    
.MinToBeAdded,@dtOriginDateTime)) as varchar(20))) +'-Trinetra'      
                    WHEN @punch ='110' THEN ('Name : '+ S.StudentFirstName + + S.StudentLastName + '\n Info: Boarded / Get down from incorrect vehicle at : '+      
                    CAST((dbo.rvlf_fn_DayLightSavings_Date(@dtOriginDateTime,O.OrganizationID,TZ.HoursToBeAdded,TZ.MinToBeAdded,@dtOriginDateTime))      
                    as varchar(20)))+'-Trinetra' end as MessageType,4,0      
                    from rvlfStudentMaster S  with(nolock)    
                    inner join rvlfVehicle v on s.OrganizationId=v.OrganizationId      
                    inner join rvlfVehicleAssignment va with(nolock) on v.VehicleId=va.VehicleId      
                    inner join rvlfOrganization O on O.OrganizationId = S.OrganizationID      
                    inner join rvlfTimeZones TZ on TZ.TimeZoneID = O.CountryId      
                    where s.RFID= dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RF_ID=',';') and va.BoxId=@intBoxID      
                   End      
                  ---------------- ---------------- ----------------      
                  /*********** demo ********************/      
                  -- Demo Account Mapping      
                  /*IF(@intDemoBoxID IS NOT NULL)      
                  BEGIN      
                  SELECT @bigAlarmID = ISNULL(Max(AlarmID),0)+1 FROM rvlfAlarm      
                  INSERT INTO rvlfAlarm      
                  ( AlarmId,AlarmLevelId, DateTimeCreated , BoxId , AlarmType ,Lat , Long , [Description],StreetAddress )      
                  VALUES ( @bigAlarmID , @tiAlarmLevelID, @dtOriginDateTime , @intDemoBoxID , @tiBoxMsgInTypeId, @dLatitude , @dLongitude ,      
                  CASE WHEN @tiBoxMsgInTypeId IN (5 , 6) THEN CAST(@bigGeoZoneID AS varchar(600))      
                  WHEN @tiBoxMsgInTypeId = 4 THEN CAST (@tiSpeed As Varchar(600))      
                  ELSE dbo.rvlf_fn_GetAlarmDetails(@vcCustomProp , @tiBoxMsgInTypeId, @intDemoBoxID,@uiDemoMsgInID, @dtOriginDateTime) END,      
                  CASE WHEN @tiValidGps = 0 THEN NULL ELSE 'N/A' END      
)      
                  END */      
                  /*************end **********************/      
                 END      
                /******************************************************************************/      
                /***************************Communication Processing***************************/      
                -- Inserts the communication information based on the communication information.      
                IF NOT EXISTS(SELECT commAddressValue FROM rvlfBoxCommInfo WHERE BoxId = @intBoxID AND CommAddressValue =@vcNewIP)      
                 BEGIN      
                  DELETE FROM rvlfBoxCommInfo WHERE BoxId = @intBoxID      
                  INSERT INTO rvlfBoxCommInfo(BoxID,CommAddressTypeId,CommAddressValue)      
                  SELECT @intBoxID,CommAddressTypeID,@vcNewIP FROM rvlfCommModeAddressType      
                  WHERE CommModeId = @tiCommModeId      
                 END      
                /******************************************************************************/      
                PRINT 'Trip Table'      
                /**************************Trip Processing*************************************/      
                DECLARE @tripTobeProcessed bigint      
                DECLARE @bigTripID bigint      
                DECLARE @bigPreviousTripID bigint      
                -- Checks the Geozone status and update starts or ends the trip against boxid.      
                IF EXISTS (SELECT 1 FROM dbo.rvlfBoxId WHERE BoxID=@intBoxID AND OrganizationID=201) --Afcons Clients      
                 BEGIN      
                  select '201'      
                  -- SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetails_AFC WHERE BoxID = @intBoxID AND IsTripClosed = 0      
                  -- IF(@bigOdoMeterReading IS NULL AND @tiBoxMsgInTypeId=114 AND CHARINDEX(';Odometer:',@vcCustomProp,0) <> 0)      
                  -- BEGIN      
                  --SELECT @bigOdoMeterReading=SUBSTRING(@vcCustomProp,CHARINDEX(';Odometer:',@vcCustomProp,0)+10,      
                  --(LEN(@vcCustomProp)-(CHARINDEX(';Odometer:',@vcCustomProp,0)+9)))      
                  -- END      
                  -- ELSE IF (@bigOdoMeterReading IS NULL AND @tiBoxMsgInTypeId=6)      
                  -- BEGIN      
                  -- SELECT @bigOdoMeterReading=SUBSTRING(@vcCustomProp,CHARINDEX(';Odometer=',@vcCustomProp,0)+10,      
                  --((CHARINDEX(';Battery',@vcCustomProp,0))-(CHARINDEX(';Odometer=',@vcCustomProp,0)+10)))      
                  -- END      
                  -- UPDATE dbo.rvlfTripDetails_AFC SET EndDate=@dtOriginDateTime , OdometerEnd = CASE WHEN @bigOdoMeterReading IS NULL      
                  -- THEN OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID ,      
                  -- IsTripClosed = CASE WHEN @tiBoxMsgInTypeId = 5 THEN 1 ELSE 0 END,      
                  --IdlingDuration = IdlingDuration + (CASE WHEN @tiBoxMsgInTypeId <> 9 THEN 0 ELSE      
                  -- CAST(dbo.rvlf_fn_GetDuration(@vcCustomProp, @tiBoxMsgInTypeID, @intBoxID,0) as int) END)      
                  -- WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID AND IsTripClosed = 0      
                  -- IF @tiBoxMsgInTypeId IN (5,6,114)      
                  -- BEGIN      
                  -- IF (@tiBoxMsgInTypeId = 6 OR (@tiBoxMsgInTypeId = 114 AND CHARINDEX('GeozoneInOutWithDuration:',@vcCustomProp,0) <> 0))      
                  -- AND @tripTobeProcessed = 0      
                  -- BEGIN      
                  -- SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM dbo.rvlfTripDetails_AFC WHERE BoxId = @intBoxID      
 -- SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM dbo.rvlfTripDetails_AFC      
                  -- INSERT INTO dbo.rvlfTripDetails_AFC(TripId, BoxId, StartDate, EndDate, OdometerStart, OdometerEnd,      
        -- StartMessageInID , EndMessageInID, IsTripClosed) VALUES      
                  -- (@bigTripID,@intBoxID, @dtOriginDateTime, @dtOriginDateTime, @bigOdoMeterReading ,      
                  -- @bigOdoMeterReading , @uiMsgInID , @uiMsgInID, 0)      
                  -- INSERT INTO dbo.rvlfTripFareDetails(TripId) VALUES(@bigTripID) --Trip Fare Details      
                  -- UPDATE dbo.rvlfTripDetails_AFC SET StopTime = DATEDIFF(ss, EndDate, @dtOriginDateTime)      
                  -- WHERE BoxId = @intBoxID AND TripID = @bigPreviousTripID      
                  -- END      
                  -- ELSE IF @tiBoxMsgInTypeId = 5 AND @tripTobeProcessed = 0      
                  -- BEGIN      
                  -- SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetails_AFC WHERE BoxID = @intBoxID AND IsTripClosed = 1      
                  -- UPDATE dbo.rvlfTripDetails_AFC SET EndDate=@dtOriginDateTime , OdometerEnd = CASE WHEN @bigOdoMeterReading IS NULL      
                  -- THEN OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID ,IsTripClosed = 1      
                  -- WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID      
                  -- END      
                  --END      
                 END      
                ELSE      
                 BEGIN --Other Clients      
                  -- Checks the ignition status and starts or ends the trip.      
                  SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetails WHERE BoxID = @intBoxID      
                  AND IsTripClosed = 0      
                  UPDATE dbo.rvlfTripDetails SET EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL THEN OdometerEnd ELSE @bigOdoMeterReading END,EndMessageInID = @uiMsgInID , IsTripClosed = CASE WHEN @bitIgnitionStatus = 0 THEN 1 ELSE      
      0 END,      
                  IdlingDuration = IdlingDuration + (CASE WHEN @tiBoxMsgInTypeId <> 9 THEN 0 ELSE      
                  CAST(dbo.rvlf_fn_GetDuration(@vcCustomProp, @tiBoxMsgInTypeID, @intBoxID,0) as int) END)      
                  WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID AND IsTripClosed = 0      
                  IF @tiBoxMsgInTypeId <> 13      
                   BEGIN      
                    IF @bitIgnitionStatus = 1 AND @tripTobeProcessed = 0 and (@tiBoxMsgInTypeId = 2 AND CHARINDEX('SENSOR_NUM=3;',@vcCustomProp,0) <> 0)      
                     BEGIN      
                      SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM dbo.rvlfTripDetails WHERE BoxId = @intBoxID      
                      SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM dbo.rvlfTripDetails  with(nolock)     
                      INSERT INTO dbo.rvlfTripDetails      
                      (TripId, BoxId, StartDate, EndDate, OdometerStart, OdometerEnd,StartMessageInID , EndMessageInID, IsTripClosed)      
                      VALUES (@bigTripID, @intBoxID, @dtOriginDateTime, @dtOriginDateTime, @bigOdoMeterReading ,      
                      @bigOdoMeterReading , @uiMsgInID , @uiMsgInID, 0)      
                      UPDATE dbo.rvlfTripDetails SET StopTime = DATEDIFF(ss, EndDate, @dtOriginDateTime)      
                      WHERE BoxId = @intBoxID AND TripID = @bigPreviousTripID      
                     END      
                    ELSE IF @bitIgnitionStatus = 0 AND @tripTobeProcessed = 0 AND (@tiBoxMsgInTypeId = 3 AND      
                    CHARINDEX('SENSOR_NUM=3;',@vcCustomProp,0) <> 0)      
                     BEGIN      
                      SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetails  with(nolock)    
                      WHERE BoxID = @intBoxID AND IsTripClosed = 1      
                      UPDATE dbo.rvlfTripDetails SET EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL THEN OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID , IsTripClosed = 1      
                      WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID      
                     END      
                   END --      
                  Declare @Sensor int --Get sensor      
                  -- if CHARINDEX('SENSOR_NUM=',@vcCustomProp,0) <> 0      
                  --begin      
                  -- set @sensor=dbo.rvlf_fn_getparamvaluewithindex(@vcCustomProp,'SENSOR_NUM=',';')      
                  --end      
                  -- -- Checks the ignition status and starts or ends the trip.      
                  -- SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetailssensorbsd WHERE BoxID = @intBoxID      
                  --AND IsTripClosed = 0      
                  --AND (CHARINDEX('SENSOR_NUM=',@vcCustomProp,0) = 0 or SensorNo=@Sensor) --#      
                  -- UPDATE dbo.rvlfTripDetailssensorbsd SET EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL THEN OdometerEnd ELSE      
                  -- @bigOdoMeterReading END,EndMessageInID = @uiMsgInID , --IsTripClosed = CASE WHEN @bitIgnitionStatus = 0 THEN 1 ELSE 0 END, #      
                  -- IdlingDuration = IdlingDuration + (CASE WHEN @tiBoxMsgInTypeId <> 9 THEN 0 ELSE      
                  -- CAST(dbo.rvlf_fn_GetDuration(@vcCustomProp, @tiBoxMsgInTypeID, @intBoxID,0) as int) END)      
                  -- WHERE BoxId = @intBoxID AND IsTripClosed = 0 -- AND TripID = @tripTobeProcessed #      
                  -- IF @tiBoxMsgInTypeId <> 13      
                  -- BEGIN --@bitIgnitionStatus = 1 AND      
                  -- IF @tripTobeProcessed = 0 and (@tiBoxMsgInTypeId = 2 AND CHARINDEX('SENSOR_NUM=',@vcCustomProp,0) <> 0)      
                  -- BEGIN      
                  -- SELECT @bigPreviousTripID = ISNULL(MAX(TRIPID), 0) FROM dbo.rvlfTripDetailssensorbsd WHERE BoxId = @intBoxID and SensorNo=@sensor --#      
                  -- SELECT @bigTripID = ISNULL(MAX(TRIPID), 0)+1 FROM dbo.rvlfTripDetailssensorbsd      
               --INSERT INTO dbo.rvlfTripDetailssensorbsd      
                  -- (TripId, BoxId, StartDate, EndDate, OdometerStart, OdometerEnd,StartMessageInID , EndMessageInID, IsTripClosed,SensorNo) --#      
                  -- VALUES (@bigTripID, @intBoxID, @dtOriginDateTime, @dtOriginDateTime, @bigOdoMeterReading , @bigOdoMeterReading , @uiMsgInID , @uiMsgInID, 0,@Sensor)      
                  -- UPDATE dbo.rvlfTripDetailssensorbsd SET StopTime = DATEDIFF(ss, EndDate, @dtOriginDateTime)      
                  --WHERE BoxId = @intBoxID AND TripID = @bigPreviousTripID      
                  -- END      
                  -- ELSE IF (@tiBoxMsgInTypeId = 3 AND CHARINDEX('SENSOR_NUM=',@vcCustomProp,0) <> 0) -- #@bitIgnitionStatus = 0 AND AND @tripTobeProcessed = 0      
                  -- BEGIN      
                  -- SELECT @tripTobeProcessed = ISNULL(MAX(TripID),0) FROM dbo.rvlfTripDetailssensorbsd      
                  -- WHERE BoxID = @intBoxID and SensorNo=@sensor--AND IsTripClosed = 1 #      
                  -- UPDATE dbo.rvlfTripDetailssensorbsd SET EndDate=@dtOriginDateTime , OdometerEnd = case WHEN @bigOdoMeterReading IS NULL      
                  -- THEN OdometerEnd ELSE @bigOdoMeterReading END, EndMessageInID = @uiMsgInID , IsTripClosed = 1      
                  -- WHERE TripID = @tripTobeProcessed AND BoxId = @intBoxID and SensorNo=@sensor --#      
                  -- END      
                  -- END      
                 END      
                /******************************************************************************/      
                PRINT 'Schedule Table'      
                /*************************Message out Processing (ACK / Response)**************/      
                IF @dtSentDateTime IS NOT NULL      
                 BEGIN      
    UPDATE rvlfMsgOutHst SET Acknowledged = 1, MessageInID= @uiMsgInID      
                  WHERE BoxId = @intBoxID AND SentDateTime = @dtSentDateTime      
                  --Update reporting interval and speed threshold to master table      
                  --UPDATE v SET v.RptInterval=--(CASE WHEN H.BoxCmdOutTypeId=1 THEN dbo.rvlf_fn_GetTimeFromSeconds(H.CustomProp) ELSE v.RptInterval END),      
                  --(CASE WHEN H.BoxCmdOutTypeId=1 and CHARINDEX(',1',H.CustomProp,1)=0 THEN dbo.rvlf_fn_GetTimeFromSeconds(H.CustomProp)      
                  --WHEN H.BoxCmdOutTypeId=1 and CHARINDEX(',1',H.CustomProp,1)>0 THEN REPLACE(H.CustomProp,',1','') ELSE v.RptInterval END),      
                  --v.SpdThreshold = (CASE WHEN H.BoxCmdOutTypeId=2 THEN CAST(H.CustomProp AS TINYINT) ELSE v.SpdThreshold END) FROM rvlfVehicle v      
                  --INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId      
                  --INNER JOIN rvlfMsgOutHst H ON H.BoxId=va.BoxId      
                  --WHERE H.BoxId = @intBoxID AND H.SentDateTime = CAST(@dtSentDateTime AS DATETIME) AND H.BoxCmdOutTypeId IN (1,2)    
       if LEN(@intBoxID) > 10   
      Begin  

	 -- declare @tmpcusprop varchar(max) = @vcCustomProp
	 -- if SUBSTRING(@tmpcusprop, len(@tmpcusprop) , 1) <> ';'
	 -- Begin
		--set @tmpcusprop = @tmpcusprop + ';'
	 -- End
	  --select SUBSTRING(@tmpcusprop, CHARINDEX(':', @tmpcusprop) + 1, (CHARINDEX(';', @tmpcusprop)) - (CHARINDEX(':', @tmpcusprop) + 1)) 
	  
     UPDATE v SET v.RptInterval=  
     SUBSTRING(H.CustomProp, CHARINDEX(':', H.CustomProp) + 1, len(H.CustomProp) - CHARINDEX(':', H.CustomProp) + 1)   
     FROM rvlfVehicle v      
     INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId      
     INNER JOIN rvlfMsgOutHst H ON H.BoxId=va.BoxId      
     WHERE H.BoxId = @intBoxID AND H.SentDateTime = CAST(@dtSentDateTime AS DATETIME) AND H.BoxCmdOutTypeId IN (1,2)     
	 --UPDATE v SET v.RptInterval=  
  --   SUBSTRING(@tmpcusprop, CHARINDEX(':', @tmpcusprop) + 1, (CHARINDEX(';', @tmpcusprop)) - (CHARINDEX(':', @tmpcusprop) + 1)) 
  --   FROM rvlfVehicle v      
  --   INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId      
  --   INNER JOIN rvlfMsgOutHst H ON H.BoxId=va.BoxId      
  --   WHERE H.BoxId = @intBoxID AND H.SentDateTime = CAST(@dtSentDateTime AS DATETIME) AND H.BoxCmdOutTypeId IN (1,2)         
      End  
      Else  
      Begin  
     UPDATE v SET v.RptInterval=--(CASE WHEN H.BoxCmdOutTypeId=1 THEN dbo.rvlf_fn_GetTimeFromSeconds(H.CustomProp) ELSE v.RptInterval END),      
     (CASE WHEN H.BoxCmdOutTypeId=1 and CHARINDEX(',1',H.CustomProp,1)=0 THEN dbo.rvlf_fn_GetTimeFromSeconds(H.CustomProp)      
     WHEN H.BoxCmdOutTypeId=1 and CHARINDEX(',1',H.CustomProp,1)>0 THEN REPLACE(H.CustomProp,',1','') ELSE v.RptInterval END),      
     v.SpdThreshold = (CASE WHEN H.BoxCmdOutTypeId=2 THEN CAST(H.CustomProp AS TINYINT) ELSE v.SpdThreshold END) FROM rvlfVehicle v      
     INNER JOIN rvlfVehicleAssignment va ON va.VehicleId=v.VehicleId      
     INNER JOIN rvlfMsgOutHst H ON H.BoxId=va.BoxId      
     WHERE H.BoxId = @intBoxID AND H.SentDateTime = CAST(@dtSentDateTime AS DATETIME) AND H.BoxCmdOutTypeId IN (1,2)            
      End  
          
                  /*********** demo *****************/      
                  -- Demo Account Mapping      
                  /*IF(@intDemoBoxID IS NOT NULL)      
                  BEGIN      
                  UPDATE rvlfMsgOutHst SET Acknowledged = 1, MessageInID= @uiDemoMsgInID WHERE      
                  BoxId = @intDemoBoxID AND SentDateTime = @dtSentDateTime      
                  END */      
                  /*********end **************/      
                  DECLARE @tiCmdTypeID tinyint=(SELECT BoxCmdOutTypeId FROM rvlfMsgOutHst WHERE BoxId = @intBoxID AND SentDateTime = @dtSentDateTime)      
                  IF(@tiCmdTypeID IN(11,12))      
                  BEGIN      
     DECLARE @bigUserID bigint,@bigVehicleID bigint,@bigGeozoneNo bigint,@bigPassOrganizationID bigint      
                  SELECT @bigVehicleID = VehicleId FROM rvlfVehicleAssignment      
                  WHERE BoxId=@intBoxID AND IsDeleted <> 1      
                  DECLARE @tiSeverity bigint      
                  IF @tiCmdTypeID = 11      
                   BEGIN      
                    --SELECT @bigUserID= MO.UserId, @bigGeozoneNo=CAST(MO.CustomProp AS bigint),@bigPassOrganizationID=OG.OrganizationId      
                    --FROM rvlfMsgOutHst MO INNER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId=CAST(MO.CustomProp AS bigint)      
                    --WHERE MO.BoxId = @intBoxID AND MO.SentDateTime = @dtSentDateTime AND OG.OrganizationId=@bigOrganizationID    
     if LEN(@intBoxID) > 10   
       Begin        
      declare @tmpsetparam varchar(max), @tmpsel varchar(10), @tmptelgeo int    
      set @tmpsetparam = (select Top 1 CustomProp from rvlfMsgOutHst WHERE BoxId = @intBoxID AND SentDateTime = CAST(@dtSentDateTime AS DATETIME) order by SentDateTime desc)        
      set @tmpsel = SUBSTRING(@tmpsetparam, 10, 5)  

        set @tmptelgeo = ISNULL((select GeozoneNo from rvlftkGeozoneParamID where ParamID = @tmpsel), 0)

 --     set @tmptelgeo = (select case @tmpsel   
 --     when 20100 then 1 when 20120 then 2 when 20140 then 3 when 20160 then 4 when 20180 then 5 when 20200 then 6 when 20220 then 7 when 20240 then 8 when 20260 then 9 when 20280 then 10 when 20300 then 11 when 20320 then 12 when 20340 then 13 when 20360
 --then 14 when 20380 then 15 when 20400 then 16 when 20420 then 17 when 20440 then 18 when 20460 then 19 when 20480 then 20 when 20500 then 21 when 20520 then 22 when 20540 then 23 when 20560 then 24 when 20580 then 25 when 20600 then 26 when 20620 then 27
 --when 20640 then 28 when 20660 then 29 when 20680 then 30 when 20700 then 31 when 20720 then 32 when 20740 then 33 when 20760 then 34 when 20780 then 35 when 20800 then 36 when 20820 then 37 when 20840 then 38 when 20860 then 39 when 20880 then 40 when 20900 then 41 when 20920 then 42 when 20940 then 43 when 20960 then 44 when 20980 then 45 when 21000 then 46 when 21020 then 47 when 21040 then 48 when 21060 then 49 when 21080 then 50 else 0 end )  
        
      SELECT @bigUserID= MO.UserId   
      FROM rvlfMsgOutHst MO WHERE MO.BoxId = @intBoxID AND MO.SentDateTime = @dtSentDateTime   
      SELECT  @bigGeozoneNo= b.GeozoneID, @bigPassOrganizationID= a.OrganizationId FROM rvlfOrganizationGeozone a inner join rvlfOrganizationGeozonetkRel b on a.GeozoneNo = b.GeozoneNo and a.OrganizationId = b.OrganizationID where b.BoxID = @intboxid and 

b.TKGeozoneID = @tmptelgeo         
       End  
       else  
       Begin  
     SELECT @bigUserID= MO.UserId, @bigGeozoneNo=CAST(MO.CustomProp AS bigint),@bigPassOrganizationID=OG.OrganizationId      
                    FROM rvlfMsgOutHst MO INNER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId=CAST(MO.CustomProp AS bigint)      
                    WHERE MO.BoxId = @intBoxID AND MO.SentDateTime = @dtSentDateTime AND OG.OrganizationId=@bigOrganizationID      
       End    
                    SELECT @tiSeverity = SeverityId FROM rvlfOrganizationGeozone WHERE GeozoneId = @bigGeozoneNo and OrganizationId = @bigPassOrganizationID      
                    IF(@tiSeverity IS NOT NULL)      
                     BEGIN IF NOT EXISTS(SELECT GeozoneNo FROM rvlfVehicleGeozone WHERE VehicleId = @bigVehicleID AND GeozoneNo = @bigGeozoneNo)      
                     BEGIN      
                      DECLARE @IsUnAuthorizedGeo AS BIT = 0      
                      SELECT @IsUnAuthorizedGeo = DN.IsUnAuthorisedGeoZone      
                      FROM rvlfdelaynotify DN      
                      INNER JOIN rvlfVehicleAssignment VA ON VA.BoxId = DN.BoxId      
                      INNER JOIN rvlfOrganizationGeozone OG ON OG.GeozoneId = DN.GeozoneId      
                  WHERE VA.VehicleId = @bigVehicleID AND OG.GeozoneId = @bigGeozoneNo      
                      INSERT INTO rvlfVehicleGeozone(VehicleId,SeverityId,GeozoneNo,AssingedBy,AssingedDate,IsUnAuthorizedGeozone)      
                      VALUES(@bigVehicleID, @tiSeverity, @bigGeozoneNo, @bigUserID, @dtSentDateTime,@IsUnAuthorizedGeo)      
                     END      
                    END      
                   END      
                  IF @tiCmdTypeID = 12      
                   BEGIN      
                    DECLARE @vcGeozoneIDs varchar(150)=(SELECT CustomProp FROM rvlfMsgOutHst WHERE BoxId = @intBoxID AND SentDateTime = @dtSentDateTime)      
                    IF @vcGeozoneIDs ='65535'      
                     BEGIN      
                      DELETE FROM rvlfVehicleGeozone WHERE VehicleId= @bigVehicleID      
                     END      
                    ELSE      
                     BEGIN      
                      DELETE rvlfVehicleGeozone WHERE VehicleId= @bigVehicleID      
                      AND GeozoneNo IN (SELECT GeozoneId FROM rvlfOrganizationGeozone      
                      WHERE OrganizationId = @bigOrganizationID AND GeozoneId IN      
                      (SELECT * from dbo.rvlf_fn_ConvertArrayToTable(@vcGeozoneIDs,',')))      
                     END      
                   END      
                  END      
                 END      
                IF (@intBoxID = 2)      
                 BEGIN      
                  exec rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId       
                 END      
                -- Disable SMS for Dhana college when Fuel Drain with Ignition ON      
                IF (@bigOrganizationID = 47 and @tiBoxMsgInTypeId = 90 and @bitIgnitionStatus = 1)      
                 BEGIN      
                  UPDATE rvlfMsgInHst set IsNotificationSent = 1 where MessageInID = @uiMsgInID      
                 END      
                --Log notifications for geozone messages.      
                --IF(@tiBoxMsgInTypeId IN(5,6))      
                --BEGIN      
                --EXEC rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId      
                --END      
                PRINT 'Log Notification Table'      
                --UPDATE THE LOG NOTIFICATION FOR INVALID GPS      
                -- ELSE IF @tiValidGps >= 0 AND @tiBoxMsgInTypeId=100      
                -- BEGIN      
                --EXEC rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId      
                -- END      
                IF @tiValidGps > 0 AND @tiBoxMsgInTypeId NOT IN (100,21) and @vcCustomProp not like '%IButtonCommand:1%' and @vcCustomProp not like '%CameraSettings:1%' and @vcCustomProp not like '%Img%' and @vcCustomProp not like '%SendSMSQuery:1%'
  
    
      
                 BEGIN      
                  EXEC rvlf_sp_LogNotificaitons @uiMsgInID, @tiBoxMsgInTypeId      
                 END      
                --PRINT 'Welcome 4'      
                IF @trancount = 0      
        COMMIT;      
                -- COMMIT TRAN      
               END TRY      
              BEGIN CATCH      
              DECLARE @error int, @message varchar(4000), @xstate int;      
              SELECT @error = ERROR_NUMBER(),      
              @message = ERROR_MESSAGE(),      
              @xstate = XACT_STATE();      
              if @xstate = -1      
              ROLLBACK TRAN;      
              if @xstate = 1 and @trancount = 0      
              ROLLBACK TRAN;      
              if @xstate = 1 and @trancount > 0      
              ROLLBACK TRANSACTION MessageTransaction;      
              --ROLLBACK TRAN      
              SET @ErrorMessage = 'An Error occured during insert of the packet message : ' + @message      
              RAISERROR( @ErrorMessage,16,1)      
              END CATCH      
             END--CONDITION 02 END      
           END      
         END --CONDITION 01 END      
        /******************************************************************************/      
        --SELECT @bigOrganizationID = OrganizationID FROM rvlfBoxId WHERE BoxId = @intBoxID      
        if(@tiBoxMsgInTypeId in (2,3,5,6,114,100))      
         begin      
          insert into @OrganizationPackage      
          select op.packageid ,po.Moduleid ,po.operationid ,operationtypename ,operationdesc from rvlfOrganizationPackage op      
          INNER JOIN rvlfPackageOperations po on op.PackageId=po.PackageId      
          INNER JOIN rvlfOperationType ot on po.OperationID=ot.OperationTypeId      
          inner join rvlforganization o on op.organizationid=o.organizationid      
          WHERE op.OrganizationID=@bigOrganizationID and op.IsActive=1 and o.ExpiresOn>=getdate()      
         end      
        --Student Punch Geozone In/Out      
        IF(@tiBoxMsgInTypeId IN(5,6,114) and CHARINDEX('GeozoneID=',@vcCustomProp,0)>0)      
         BEGIN      
          --School Geozone Entry/Exit      
          If exists (select * from rvlfSchoolMaster A inner join rvlfBoxId B on a.OrganizationID=B.OrganizationId      
          where B.BoxId=@intBoxID and GeozoneId=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'GeozoneID=',';')      
          and A.OrganizationId not in (select OrgId from rvlfGitscoSchoolMgmt)) --Disabled for GITSCO on 30-Oct-2017 --A.OrganizationId not in (6,352,412))      
           begin      
             Begin try      
              Exec rvlf_sp_GetandUpdateRFIDStudentSMSTrigger @intBoxID      
              print 'Student log RFID Updated'      
             end try      
            BEGIN CATCH      
            --ROLLBACK TRAN      
            SET @ErrorMessage = 'An Error occured during insert of RFID Student entry to school : ' + ERROR_MESSAGE()      
            RAISERROR( @ErrorMessage,16,1)      
            END CATCH      
           end      
  -- As per the client request, We have command the school Entry / Exit notification by karthikeyan.R on 2019-Nov-01.  
          --If exists (select * from rvlfSchoolMaster A inner join rvlfBoxId B on a.OrganizationID = B.OrganizationId      
          --where B.BoxId = @intBoxID and GeozoneId = dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'GeozoneID=',';')      
          --and A.OrganizationId in (select OrgId from rvlfGitscoSchoolMgmt)) --Disabled for GITSCO on 30-Oct-2017      
          -- begin      
          --   Begin try      
          --    Exec rvlf_sp_GetandUpdateRFIDStudentSMSTrigger_TripWise @intBoxID,@dtOriginDateTime,@vcCustomProp,@uiMsgInID,@tiBoxMsgInTypeId      
          --    print 'School geozone reached/started based on trips has been Updated'      
          --   end try      
          --  BEGIN CATCH      
          --  --ROLLBACK TRAN      
          --  SET @ErrorMessage = 'An Error occured during insert of School geozone reached/started based on trips : ' + ERROR_MESSAGE()      
          --  RAISERROR( @ErrorMessage,16,1)      
          --  END CATCH      
          -- end      
          --Student Pickup/Drop Geozone Entry      
          --If exists(select * from rvlfBoxId b      
          --inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId      
          --inner join rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1      
          --inner join rvlfPackageOperations po on op.PackageId=po.PackageId      
          --inner join rvlfOperationType ot on po.OperationID=ot.OperationTypeId      
          --Where b.BoxId=@intBoxID and @tiBoxMsgInTypeId = 5 and b.OrganizationId in (6)      
          --and charindex('Notification for Student Pickup point Entry',ot.OperationTypeName,1)>0)      
          If exists(select * from @OrganizationPackage b Where @tiBoxMsgInTypeId = 5 -- and @bigOrganizationID in (6)      
          and charindex('Notification for Student Pickup point Entry',b.OperationTypeName,1)>0)      
           BEGIN      
             BEGIN TRY      
              Exec rvlf_sp_TriggerSMSforStudentGeozoneEntry @intBoxID,@dtOriginDateTime,@vcCustomProp,@uiMsgInID      
              print 'Student Pickup point Entry Notification log Updated'      
             END TRY      
            BEGIN CATCH      
            --ROLLBACK TRAN      
            SET @ErrorMessage = 'An Error occured during insert of Student Pickup point Entry Notification : ' + ERROR_MESSAGE()      
            RAISERROR( @ErrorMessage,16,1)      
            END CATCH      
           END      
         END      
        --Student RFID Swipes Notifications by Anbarasu.E on 12-Aug-2015      
        IF(@tiBoxMsgInTypeId IN(100) and CHARINDEX('RF_ID=',@vcCustomProp,0)>0)      
         BEGIN      
          If exists (select * from rvlfStudentMaster where OrganizationID=@bigOrganizationID and RFID=dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'RF_ID=',';'))      
           begin      
             Begin try      
              -- if exists(select * from rvlfBoxId b inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId      
              --inner join rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1      
              --inner join rvlfPackageOperations po on op.PackageId=po.PackageId      
              --inner join rvlfOperationType ot on po.OperationID=ot.OperationTypeId      
              --where b.BoxId=@intBoxID and charindex('Notification for Each',ot.OperationTypeName,1)>0)      
              if exists(select * from @OrganizationPackage b where charindex('Notification for Each',b.OperationTypeName,1)>0)      
               Begin      
                Exec rvlf_sp_TriggerSMSforStudentRFIDSwipes @intBoxID,@dtOriginDateTime,@vcCustomProp,@uiMsgInID      
                print 'Student RFID swipes log Updated'      
               End      
             end try      
            BEGIN CATCH      
            --ROLLBACK TRAN      
            SET @ErrorMessage = 'An Error occured during insert of RFID Student swipe : ' + ERROR_MESSAGE()      
            RAISERROR( @ErrorMessage,16,1)      
            END CATCH      
           end      
         END      
        --Student SMS before stops reached      
        IF(@tiBoxMsgInTypeId=114 and charindex('34;Routeid',@vcCustomProp,1)>0)      
         BEGIN      
          Declare @AlertMsg varchar(3)=(select dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'AlertMsg=',';'))      
          if(@AlertMsg='011' or @AlertMsg='001')      
           Begin      
            --if exists(select b.boxid from rvlfBoxId b inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId      
            --inner join rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1      
            --inner join rvlfPackageOperations po on op.PackageId=po.PackageId      
            --inner join rvlfOperationType ot on po.OperationID=ot.OperationTypeId      
            --where b.BoxId=@intBoxID and charindex('Notification before',ot.OperationTypeName,1)>0)      
            if exists(select * from @OrganizationPackage b where charindex('Notification before',b.OperationTypeName,1)>0)      
             begiN      
              exec rvlf_sp_TriggerSMSBfrStops @intBoxID,@dtOriginDateTime,@vcCustomProp      
             enD      
           End      
         END      
        IF(dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'SENSOR_NUM=',';') = '1' or dbo.rvlf_fn_GetParamValueWithIndex(@vcCustomProp,'SENSOR_NUM=',';') = '2')      
         BEGIN      
          --IF EXISTS(select * from rvlfBoxId b inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId      
          --INNER JOIN rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1      
          --INNER JOIN rvlfPackageOperations po on op.PackageId=po.PackageId      
          --INNER JOIN rvlfOperationType ot on po.OperationID=ot.OperationTypeId      
          --WHERE b.BoxId=@intBoxID and charindex('Trip switch Notifications to Reporting Person',ot.OperationTypeName,1)>0)      
          if exists(select * from @OrganizationPackage b where charindex('Trip switch Notifications to Reporting Person',b.OperationTypeName,1)>0) and @tiBoxMsgInTypeId = 2      
           BEGIN      
            EXEC rvlf_sp_TriggerTripStartNotification @dtOriginDateTime,@vcCustomProp,@tiBoxMsgInTypeId,@intBoxID      
            EXEC rvlf_sp_TripDetails_GIT @intBoxID,@dtOriginDateTime,@uiMsgInID,1      
            print 'Trip switch ON Notifications log Updated'      
           END      
          --IF EXISTS(select b.boxid from rvlfBoxId b inner join rvlfOrganization o on b.OrganizationId=o.OrganizationId      
          --INNER JOIN rvlfOrganizationPackage op on o.OrganizationId=op.OrganizationID and op.IsActive=1      
          --INNER JOIN rvlfPackageOperations po on op.PackageId=po.PackageId      
          --INNER JOIN rvlfOperationType ot on po.OperationID=ot.OperationTypeId      
          --WHERE b.BoxId=@intBoxID and charindex('Trip switch based Headcount Notification to Reporting Person',ot.OperationTypeName,1)>0) and @tiBoxMsgInTypeId = 3      
          if exists(select * from @OrganizationPackage b where charindex('Trip switch based Headcount Notification to Reporting Person',b.OperationTypeName,1)>0) and @tiBoxMsgInTypeId = 3      
           BEGIN      
             BEGIN TRY      
              exec rvlf_sp_TriggerTripEndNotification @dtOriginDateTime,@vcCustomProp,2,@intBoxID,@uiMsgInID,@tiValidGps,@dLatitude,@dLongitude      
              EXEC rvlf_sp_TripDetails_GIT @intBoxID,@dtOriginDateTime,@uiMsgInID,0      
              print 'Trip switch OFF with Student Headcount Notifications log Updated'      
             END TRY      
            BEGIN CATCH      
            --ROLLBACK TRAN      
            SET @ErrorMessage = 'An Error occured during Gitsco Head count Notification : ' + ERROR_MESSAGE()      
            RAISERROR( @ErrorMessage,16,1)      
            END CATCH      
           END      
         END      
        --CHECK THE SCHEDULED OTA COMMAND RETRY**************************************************************      
        DECLARE @bigRetryScheduleId bigint=null,@tintAck tinyint=null,@dtOtaTime datetime=null      
        SELECT TOP 1 @tintAck=Acknowledged,@dtOtaTime=H.SentDateTime FROM rvlfMsgOutHst H      
        WHERE H.BoxCmdOutTypeId =22 AND H.BoxId =@intBoxID AND H.Acknowledged BETWEEN 0 AND 10 ORDER BY H.SentDateTime DESC      
        IF (@tintAck NOT IN(2,6) AND @tintAck IS NOT NULL)      
         BEGIN      
          IF EXISTS(SELECT ScheduleId FROM rvlfScheduleOfCommandsMaster WHERE Boxid=@intBoxID AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND BoxCmdOutTypeId =22)      
           BEGIN      
            SELECT @bigRetryScheduleId =a.ScheduleId FROM rvlfScheduleOfCommandsMaster a inner join rvlfSchedulingOfCommandsLog b      
            on a.ScheduleId=b.ScheduleId      
            WHERE Boxid=@intBoxID and ResponseMsg != 'Success' AND BoxCmdOutTypeId =22 AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND GETUTCDATE() BETWEEN EffectiveFrom AND EffectiveTo      
            IF @bigRetryScheduleId IS NOT NULL      
             BEGIN      
              UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=NULL WHERE ScheduleId =@bigRetryScheduleId AND BoxCmdOutTypeId=22      
              IF EXISTS(SELECT ScheduleLogId FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId)      
               BEGIN      
                UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=NULL,ActualExecutionDate=CASE WHEN @dtOtaTime>CreatedDate AND @dtOtaTime <=EffectiveTo THEN @dtOtaTime ELSE NULL END WHERE ScheduleId =@bigRetryScheduleId AND BoxCmdOutTypeId =22    



  
                DELETE rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId AND ResponseId IN (1,2,3,4,6,7,8,9,10) --RESPONSEMSG!='Aborted'      
               END      
             END      
           END      
         END      
        ELSE IF(@tintAck IS NULL)      
         BEGIN      
          SELECT @bigRetryScheduleId =ScheduleId FROM rvlfScheduleOfCommandsMaster      
          WHERE Boxid=@intBoxID AND BoxCmdOutTypeId =22 AND @dtOtaTime BETWEEN EffectiveFrom AND EffectiveTo AND GETUTCDATE() BETWEEN EffectiveFrom AND EffectiveTo      
          IF(@bigRetryScheduleId IS NOT NULL OR @bigRetryScheduleId!='')      
           BEGIN      
            IF NOT EXISTS(SELECT ScheduleLogId FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigRetryScheduleId)      
             BEGIN      
              INSERT INTO rvlfSchedulingOfCommandsLog (ScheduleId,ExecutionOn,IsCommandSend,[No.ofTries],ResponseMsg,ResponseId)      
              SELECT @bigRetryScheduleId,@dtOtaTime,1,1,'Command sent successfully.',3      
             END      
           END      
         END      
        --------------Get next route to assign ---------------------------------------      
        IF(@tiBoxMsgInTypeId=114 and charindex('AlertMsg=001',@vcCustomProp,1)>0)      
         Begin      
          DECLARE @vcType1 varchar(50)=null,@bigScheduleId1 bigint=null      
          SELECT top 1 @vcType1=ExecutionOn,@bigScheduleId1= ScheduleId FROM rvlfScheduleOfCommandsMaster SM      
          WHERE ScheduleId NOT IN(SELECT ScheduleId FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE())) AND SM.BoxId =@intBoxID and SM.Isdelete is null      
          AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))      
          AND (GETUTCDATE()<= EffectiveFrom      
          AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END))      
          AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE()))      
          order by EffectiveFrom asc      
          --UPDATE THE LATEST IP AND PORT      
          UPDATE rvlfScheduleOfCommandsMaster      
          SET PacketInfo = REPLACE(PacketInfo,SUBSTRING(PacketInfo,CHARINDEX('IP=',PacketInfo,1)+3,(CHARINDEX(';',PacketInfo,CHARINDEX('Port=',PacketInfo,1))-4)),@vcCommInfo1+';Port='+CAST(@siCommInfo2 AS VARCHAR))      
          WHERE ScheduleId=@bigScheduleId1      
          --IF THE COMMANDS EXECUTION TYPE IS Ignition On      
          IF (@vcType1 ='Ignition On' AND @tiBoxMsgInTypeId=2)      
           BEGIN      
            --INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn)      
            -- VALUES(@bigScheduleId1,GETUTCDATE())      
            INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)      
            VALUES(@bigScheduleId1,GETUTCDATE(),0)      
           END      
          ELSE IF(@vcType1 ='Any message in' AND @tiBoxMsgInTypeId =114)      
           BEGIN      
            INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId) VALUES(@bigScheduleId1,GETUTCDATE(),0)      
           END      
         End      
        ----------------------------------      
        /**************************************************************************************************/      
        --SCHEDULE THE COMMANDS****************************************************************************/      
        IF (((SELECT TOP 1 BoxId FROM rvlfBoxId WHERE BoxId=@intBoxID AND CONVERT(DATE,LastCommunicatedDateTime)=CONVERT(DATE,GETUTCDATE()))=@intBoxID) OR (@tiBoxMsgInTypeId=52))      
         BEGIN      
          --PRINT 'Welcome 5'      
          --CHECK IF THE BOXID HAVE ANY SCHEDULES FOR GIVE COMMANDS      
          IF EXISTS(SELECT ScheduleId FROM rvlfScheduleOfCommandsMaster SM      
     WHERE ScheduleId NOT IN(SELECT ScheduleId FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE()))      
          AND SM.BoxId =@intBoxID and SM.Isdelete is null      
          AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))      
          --AND (GETUTCDATE()>= EffectiveFrom      
          --AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END)) and BoxCmdOutTypeId<>94      
          AND (GETUTCDATE()>= (case when BoxCmdOutTypeId=94 then DATEADD(MINUTE,-30,EffectiveFrom) else EffectiveFrom end)      
          AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END))      
          AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE())))      
           BEGIN      
            --PRINT 'Welcome 6'      
            DECLARE @TBLSCHEDULES TABLE(ScheduleId bigint,inc bit)      
            INSERT INTO @TBLSCHEDULES(ScheduleId,inc)      
            SELECT DISTINCT SM.ScheduleId,0 FROM rvlfScheduleOfCommandsMaster SM      
            WHERE ScheduleId NOT IN(SELECT ScheduleId FROM rvlfSchedulingOfCommandsLog WHERE CONVERT(DATE,ExecutionOn)=CONVERT(DATE,GETUTCDATE()))      
            AND SM.BoxId =@intBoxID and SM.Isdelete is null      
            AND (EffectiveTo IS NULL OR CONVERT(DATE,EffectiveTo)>=CONVERT(DATE,GETUTCDATE()))      
            -- AND (GETUTCDATE()>= EffectiveFrom      
            --AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END)) and BoxCmdOutTypeId<>94      
            AND (GETUTCDATE()>= (case when BoxCmdOutTypeId=94 then DATEADD(MINUTE,-30,EffectiveFrom) else EffectiveFrom end)      
            AND GETUTCDATE()<=(CASE WHEN EffectiveTo IS NULL THEN GETUTCDATE() ELSE EffectiveTo END))      
            AND (SM.NextExecutionOn IS NULL OR CONVERT(DATE,SM.NextExecutionOn)=CONVERT(DATE,GETUTCDATE()))      
            WHILE EXISTS(SELECT ScheduleId FROM @TBLSCHEDULES WHERE inc =0)      
             BEGIN      
              --PRINT 'Welcome 7'      
              DECLARE @vcType varchar(50)=null,@bigScheduleId bigint=null      
              SELECT @bigScheduleId=ScheduleId FROM @TBLSCHEDULES WHERE inc=0      
              --UPDATE THE LATEST IP AND PORT      
              UPDATE rvlfScheduleOfCommandsMaster      
              SET PacketInfo = REPLACE(PacketInfo,SUBSTRING(PacketInfo,CHARINDEX('IP=',PacketInfo,1)+3,(CHARINDEX(';',PacketInfo,CHARINDEX('Port=',PacketInfo,1))-4)),@vcCommInfo1+';Port='+CAST(@siCommInfo2 AS VARCHAR))      
              WHERE ScheduleId=@bigScheduleId      
              SELECT TOP 1 @vcType=ExecutionOn,@bigScheduleId=ScheduleId FROM rvlfScheduleOfCommandsMaster      
              WHERE ScheduleId=@bigScheduleId      
              --IF THE COMMANDS EXECUTION TYPE IS Ignition On      
              IF (@vcType ='Ignition On' AND @tiBoxMsgInTypeId=2)      
               BEGIN      
                INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)      
                VALUES(@bigScheduleId,GETUTCDATE(),0)      
               END      
              ELSE IF(@vcType ='Any message in' AND @tiBoxMsgInTypeId NOT IN(12))      
               BEGIN      
                INSERT INTO rvlfSchedulingOfCommandsLog(ScheduleId,ExecutionOn,ResponseId)      
                VALUES(@bigScheduleId,GETUTCDATE(),0)      
               END      
              UPDATE TOP(1) @TBLSCHEDULES SET inc=1 WHERE ScheduleId=@bigScheduleId      
             END      
           END      
         END 
--		 IF EXISTS(select * from rvlfRouteVehicleAssignment rva inner join rvlfVehicleAssignment va on rva.VehicleId = va.VehicleId
--where BoxId =@intboxid and rva.TripStatus=2 and CONVERT(date,FromDateTime) = CONVERT(Date,GETDATE()))
--		 BEGIN		  
--		  	exec rvlf_sp_Getinoutlandmark_Route @uiMsgInid,@bigOrganizationID,@dlatitude, @dlongitude,@intboxid,@vcStreetAddress, @vcNearestLandmark;						
--		 END     
       END      
     END      
   END     
    
  SET NOCOUNT OFF      
 end
GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateNotificationNews]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    
CREATE Procedure [dbo].[rvlf_sp_UpdateNotificationNews]    
 @NewsId bigint = Null,
 @IsNotificationSent bit = Null
AS    
/****************************************************************************************/    
-- Name    : rvlf_sp_UpdateNotificationNews    
-- Description   : To get the news details    
-- Author    : ranjith N 
-- Created Date  : 16-Apr-2014    
/***************************************************************************************/    
BEGIN    
 SET NOCOUNT ON          
  Update rvlfNews set IsNotificationSent = @IsNotificationSent where NewsId =  @NewsId              
   
 SET NOCOUNT OFF    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateNotificationReadStatus]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_UpdateNotificationReadStatus]
@vcMsgInIds VARCHAR(MAX),
@UserID BIGINT
AS
/***********************************************************************************************
Procedure Name		: rvlf_sp_UpdateNotificationReadStatus
Details				: To Update the read status for viewed notifications
Created By			: Sakthi Gopinath S
Created Date		: 30-Jun-2015
History				: Initial Version Created by SS
***********************************************************************************************/
BEGIN
SET NOCOUNT ON
	
	INSERT INTO rvlfNotificationRead(MessageInId,UserId,ReadDate)
	SELECT	ab.FieldValue,@UserID,GETUTCDATE() 
	FROM	dbo.rvlf_fn_ConvertArrayToTable(@vcMsgInIds,',') ab
	LEFT	OUTER JOIN dbo.rvlfNotificationLog nl ON nl.MessageInId = ab.FieldValue and nl.UserId = @UserID 
	WHERE	nl.UserId = @UserID and nl.MessageInId NOT IN (SELECT MessageInId From rvlfNotificationRead Where UserID = @UserID)

	--SELECT	ab.FieldValue,@UserID,GETUTCDATE() 
	--FROM	dbo.rvlf_fn_ConvertArrayToTable(@vcMsgInIds,', ') ab
	--LEFT	OUTER JOIN dbo.rvlfNotificationRead nr ON nr.MessageInId=ab.FieldValue
	--WHERE	nr.UserId = @UserID

SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateNotifications]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_UpdateNotifications]
	@uiMessageInID uniqueidentifier,
	@bigUserID bigint,
	@bitIsEmail bit,
	@bitIsSuccess bit,
	@vcErrorMessage varchar(600) = null,
	@dtProcessedDateTime DateTime
AS
/******************************************************************************/
--	Name		:	rvlf_sp_UpdateNotifications
--	Description	:	To update related to the notifications sent
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	14-Nov-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Declares the required variables to hold the intermediate results.
	DECLARE @ErrorMessage varchar(200)
	
	IF EXISTS ( SELECT MessageInID FROM rvlfNotificationLog WHERE MessageInID = @uiMessageInID)
	BEGIN
		BEGIN TRAN Update_Notifications
		BEGIN TRY
			UPDATE rvlfNotificationLog SET 
				IsMailSent = CASE WHEN @bitIsEmail = 1 THEN @bitIsSuccess ELSE IsMailSent END,
				IsEmailError = CASE WHEN @bitIsEmail = 1 and @bitIsSuccess = 0 THEN 1 ELSE 0 END,
				NoOfEmailTries = CASE WHEN @bitIsEmail = 1 and @bitIsSuccess = 0 THEN 
					ISNULL(NoOfEmailTries,0)+1 ELSE NoOfEmailTries END,
				EmailErrorMessage = CASE WHEN @bitIsEmail = 1 and @bitIsSuccess = 0 THEN 
					@vcErrorMessage ELSE EmailErrorMessage END,
				EmailProcessedDate = CASE WHEN @bitIsEmail = 1 THEN @dtProcessedDateTime 
					ELSE EmailProcessedDate END,
				
				IsSMSSent = CASE WHEN @bitIsEmail  = 0 THEN @bitIsSuccess ELSE IsSMSSent END,
				IsSMSError = CASE WHEN @bitIsEmail = 0 and @bitIsSuccess = 0 THEN 1 ELSE 0 END,
				NoOfSMSTries = CASE WHEN @bitIsEmail = 0 and @bitIsSuccess = 0 THEN 
					ISNULL(NoOfSMSTries,0)+1 ELSE NoOfSMSTries END,
				SMSError = CASE WHEN @bitIsEmail = 0 and @bitIsSuccess = 0 THEN 
					@vcErrorMessage ELSE SMSError END,
				SMSProcessedDate = CASE WHEN @bitIsEmail = 0 THEN @dtProcessedDateTime 
					ELSE SMSProcessedDate END
			WHERE MessageInID = @uiMessageInID and UserID=@bigUserID
			COMMIT TRAN
		END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during updating notifiations : ' + ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
	END

	ELSE
	BEGIN
		SET @ErrorMessage = 'No such message exists : ' + CAST(@uiMessageInID as varchar(36))
		RAISERROR( @ErrorMessage,16,1)
	END

SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateNotifications_SMSbasedQuery]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateNotifications_SMSbasedQuery]    
 @SMSbasedQueryID bigint,    
 @bitIsEmail bit,    
 @bitIsSuccess bit,    
 @vcErrorMessage varchar(600) = null,    
 @dtProcessedDateTime DateTime    
AS    
/******************************************************************************/    
-- Name  : rvlf_sp_UpdateNotifications_SMSbasedQuery    
-- Description : To update related to the notifications sent    
-- Author  : N.Ranjith  
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 03-Apr-2014 Ranjith Created Intial Version     
/******************************************************************************/    
BEGIN    
SET NOCOUNT ON     
 -- Declares the required variables to hold the intermediate results.    
 DECLARE @ErrorMessage varchar(200)    
--_SendSMSTest     
 IF EXISTS ( SELECT MessageInID FROM rvlfNotificationLog WHERE SMSbasedQueryID = @SMSbasedQueryID)    
 BEGIN    
  BEGIN TRAN Update_Notifications    
  BEGIN TRY    
   UPDATE rvlfNotificationLog SET     
    IsMailSent = CASE WHEN @bitIsEmail = 1 THEN @bitIsSuccess ELSE IsMailSent END,    
    IsEmailError = CASE WHEN @bitIsEmail = 1 and @bitIsSuccess = 0 THEN 1 ELSE 0 END,    
    NoOfEmailTries = CASE WHEN @bitIsEmail = 1 and @bitIsSuccess = 0 THEN     
     ISNULL(NoOfEmailTries,0)+1 ELSE NoOfEmailTries END,    
    EmailErrorMessage = CASE WHEN @bitIsEmail = 1 and @bitIsSuccess = 0 THEN     
     @vcErrorMessage ELSE EmailErrorMessage END,    
    EmailProcessedDate = CASE WHEN @bitIsEmail = 1 THEN @dtProcessedDateTime     
     ELSE EmailProcessedDate END,    
        
    IsSMSSent = CASE WHEN @bitIsEmail  = 0 THEN @bitIsSuccess ELSE IsSMSSent END,    
    IsSMSError = CASE WHEN @bitIsEmail = 0 and @bitIsSuccess = 0 THEN 1 ELSE 0 END,    
    NoOfSMSTries = CASE WHEN @bitIsEmail = 0 and @bitIsSuccess = 0 THEN     
     ISNULL(NoOfSMSTries,0)+1 ELSE NoOfSMSTries END,    
    SMSError = CASE WHEN @bitIsEmail = 0 and @bitIsSuccess = 0 THEN     
     @vcErrorMessage ELSE SMSError END,    
    SMSProcessedDate = CASE WHEN @bitIsEmail = 0 THEN @dtProcessedDateTime     
     ELSE SMSProcessedDate END    
   WHERE SMSBasedQueryID = @SMSbasedQueryID 
   COMMIT TRAN    
  END TRY    
 BEGIN CATCH    
  ROLLBACK TRAN     
  SET @ErrorMessage = 'An Error occured during updating notifiations : ' + ERROR_MESSAGE()    
  RAISERROR( @ErrorMessage,16,1)    
 END CATCH    
 END    
    
 ELSE    
 BEGIN    
  SET @ErrorMessage = 'No such message exists for SMS based Query '    
  RAISERROR( @ErrorMessage,16,1)    
 END    
    
SET NOCOUNT OFF    
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateParentNotificationStatus]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
      
CREATE PROCEDURE [dbo].[rvlf_sp_UpdateParentNotificationStatus]
	@NotificationId			bigint	= Null,  
	@IsNotificationSent		bit		= Null  
AS      
/****************************************************************************************/      
-- Name    : rvlf_sp_UpdateParentNotificationStatus
-- Description   : To update the notification Status and Sent date after sending Notifications.
-- Author    : Anbarasu.E
-- Created Date  : 29-06-2015
/***************************************************************************************/      
BEGIN
	SET NOCOUNT ON;
 
	UPDATE	rvlfNotificationToParents 
	SET		IsNotificationSent = @IsNotificationSent, PublishedDate = GETDATE()
	WHERE	NotificationId = @NotificationId
     
	SET NOCOUNT OFF;
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdatePassword]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_UpdatePassword]     
/******************************************************    
Stored Procedure Name : rvlf_sp_UpdatePassword    
Purpose     : Update password   
Created by    : Uma    
Created date   : 21-Jul-09    
Updated by    :     
Updated date   :     
*******************************************************/    
    
@UserID bigint   = Null,    
@Pwd		varchar(100)	= null,
@Type varchar(2) = Null,
@bigUserId bigint=null
AS    
    
BEGIN     
    
 IF (@UserID > 0)    
 BEGIN    
    IF (@Type = 'CP') -- Change Password on First Login
	BEGIN
    
	  UPDATE rvlfUser SET Password = @Pwd, IsPwdChanged = 1,ModifiedBy=@bigUserId,ModifiedDateTime=GETUTCDATE() WHERE UserId = @UserID 
	  
	END
	ELSE -- Reset Password
    BEGIN
    
	  UPDATE rvlfUser SET Password = @Pwd, IsLocked = 0,ModifiedBy=@bigUserId,ModifiedDateTime=GETUTCDATE() WHERE UserId = @UserID 
	  
	END
	
 END    
    
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdatePendingScheduleofCommands]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

  
CREATE Procedure [dbo].[rvlf_sp_UpdatePendingScheduleofCommands]    
 @dtExecutionOn datetime=null,    
 @bitIsCommandSend bit=null,    
 @vcErrorMsg varchar(500)=null,    
 @bigScheduleLogId bigint=null,    
 @bigScheduleId BIGINT=NULL,    
 @bitIsServiceCall bit=null,    
 @intBoxid int =null     
AS    
/******************************************************************************/    
-- Name  : [rvlf_sp_UpdatePendingScheduleofCommands]    
-- Description : To update the pending of schedule commands     
-- Author  : V.Narayanasamy    
-- Company  : Angler Technologies    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
--    : 15-Dec-2010 VN Created Intial Version     
/******************************************************************************/    
BEGIN    
     
 --update the logged commands from scheduling windows service    
 IF(@bitIsServiceCall =1)    
  BEGIN    
   DECLARE @dtCmdSentTime datetime =(SELECT TOP 1 SentDateTime  FROM rvlfMsgOutHst WHERE BoxId = @intBoxid AND Acknowledged IS NULL ORDER BY SentDateTime DESC)    
   IF(@dtCmdSentTime IS NULL OR @dtCmdSentTime ='' )    
    SET @dtCmdSentTime= (SELECT GETUTCDATE())    
   UPDATE rvlfSchedulingOfCommandsLog SET ExecutionOn=@dtCmdSentTime,IsCommandSend=0,ResponseMsg='In-Progress',ResponseId=2 WHERE ScheduleId=@bigScheduleId AND ScheduleLogId =@bigScheduleLogId      
  END    
 ELSE    
  BEGIN      
 -- GET THE EXECUTION TIME      
 SELECT @intBoxid =Boxid  FROM rvlfScheduleOfCommandsMaster WHERE ScheduleId=@bigScheduleId     
 Declare @dtActualEcecution datetime=null    
 IF(@bitIsCommandSend =1)    
  BEGIN    
   SELECT  @dtActualEcecution=OriginDateTime FROM rvlfMsgInHst     
   WHERE MessageInID =((SELECT MessageInID FROM rvlfMsgOutHst     
    WHERE BoxID = @intBoxid     
     AND SentDateTime = (SELECT MAX(SentDateTime)FROM rvlfMsgOutHst WHERE BoxID = @intBoxid)     
     AND Acknowledged = 1))    
  END    
 ELSE     
  BEGIN          
   SELECT @dtActualEcecution=SentDateTime FROM rvlfMsgOutHst     
    WHERE BoxID = @intBoxid    
     AND SentDateTime = (SELECT MAX(SentDateTime)FROM rvlfMsgOutHst WHERE BoxID =@intBoxid)     
  END    
      
 IF(@dtActualEcecution IS NULL OR @dtActualEcecution='')    
  BEGIN    
   SET @dtActualEcecution=GETUTCDATE()    
  END        
 --UPDATE THE COMMAND DETAILS    
 UPDATE rvlfSchedulingOfCommandsLog SET ExecutionOn=@dtActualEcecution,IsCommandSend=@bitIsCommandSend,    
  RESPONSEMSG=@vcErrorMsg,    
  ResponseId = CASE WHEN @vcErrorMsg ='The command sent successfully.' THEN 3    
        WHEN @vcErrorMsg ='The command has failed.' THEN 4 ELSE 0 END,    
  [No.oftries]=ISNULL([No.oftries],0)+1    
  WHERE ScheduleLogId=@bigScheduleLogId     
    
  ---- delete assinged route schedule    
 IF exists(select * from rvlfScheduleOfCommandsMaster where ScheduleId=@bigScheduleId and BoxCmdOutTypeId=94    
 and dbo.rvlf_fn_GetParamValueWithIndex(PacketInfo,'Param=',';')='42,3' and CHARINDEX('success',@vcErrorMsg,0)>0)        
 begin       
 --UPDATE rvlfSchedulingOfCommandsLog SET RESPONSEMSG= case when @vcErrorMsg like '%success%' then ResponseMsg + '1' else ResponseMsg end     -- WHERE ScheduleLogId=@bigScheduleLogId         
 UPDATE b set B.Isdelete=1  from rvlfScheduleOfCommandsMaster b     
 left join rvlfSchedulingOfCommandsLog c on b.ScheduleId=c.ScheduleId        
 inner join rvlfRouteVehicleAssignment d on b.ScheduleId=d.ScheduleId      
 inner join rvlfVehicleAssignment v on d.VehicleId=v.VehicleId      
 where b.Isdelete is null and b.BoxCmdOutTypeId=94 and c.ScheduleLogId is not null and        
 ToDateTime > GETUTCDATE() and v.BoxId=@intBoxid    
 UPDATE d set d.Isdelete=1  from rvlfScheduleOfCommandsMaster b     
 left join rvlfSchedulingOfCommandsLog c on b.ScheduleId=c.ScheduleId        
 inner join rvlfRouteVehicleAssignment d on b.ScheduleId=d.ScheduleId      
 inner join rvlfVehicleAssignment v on d.VehicleId=v.VehicleId      
 where b.Isdelete is null and b.BoxCmdOutTypeId=94 and c.ScheduleLogId is not null and        
 ToDateTime > GETUTCDATE() and v.BoxId=@intBoxid    
 end           
 ----------    
      
 --UPDATE THE NEXT EXECUTION DATE AND TIME IF THE COMMAND SEND IS SUCCESS    
 IF((@bitIsCommandSend=1) OR((SELECT COUNT(ScheduleLogId) FROM rvlfSchedulingOfCommandsLog SL     
  INNER JOIN rvlfScheduleOfCommandsMaster SM ON SM.ScheduleId=SL.ScheduleId     
  WHERE SL.[NO.OFTRIES]>=SM.[No.ofRetries] AND SL.ScheduleLogId=@bigScheduleLogId)>=1))    
  BEGIN     
   --GET THE FREQUENCY TYPE     
   DECLARE @tintType tinyint=(SELECT Frequency FROM rvlfScheduleOfCommandsMaster     
    WHERE ScheduleId=@bigScheduleId)    
       
   --IF THE FREQUENCY IS DAY LEVEL    
   IF (@tintType=1)    
    BEGIN    
     UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=DATEADD(D,1,@dtExecutionOn)     
      WHERE ScheduleId=@bigScheduleId    
       AND(EffectiveTo IS NULL OR CONVERT(DATE,DATEADD(D,1,@dtExecutionOn))<=CONVERT(DATE,EffectiveTo))     
    END    
       
   --IF THE FREQUENCY IS 3DAY LEVEL    
   ELSE IF (@tintType=2)    
    BEGIN    
     UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=DATEADD(D,3,@dtExecutionOn)     
      WHERE ScheduleId=@bigScheduleId    
       AND(EffectiveTo IS NULL OR CONVERT(DATE,DATEADD(D,3,@dtExecutionOn))<=CONVERT(DATE,EffectiveTo))     
    END    
        
   --IF THE FREQUENCY IS 1WEEK LEVEL    
   ELSE IF (@tintType=3)    
    BEGIN    
     UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn=DATEADD(D,7,@dtExecutionOn)     
      WHERE ScheduleId=@bigScheduleId    
       AND(EffectiveTo IS NULL OR CONVERT(DATE,DATEADD(D,7,@dtExecutionOn))<=CONVERT(DATE,EffectiveTo))     
    END      
   ELSE IF (@tintType=0)    
    BEGIN        
     IF(@bitIsCommandSend=1)    
      BEGIN    
       UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn= DATEADD(D,1,EffectiveTo)    
        WHERE ScheduleId=@bigScheduleId             
      END    
     --ELSE    
     -- BEGIN    
     --  UPDATE rvlfScheduleOfCommandsMaster SET NextExecutionOn= GETUTCDATE()     
     --   WHERE ScheduleId=@bigScheduleId    
     --    --AND(EffectiveTo IS NULL OR CONVERT(DATE,GETUTCDATE())<=CONVERT(DATE,EffectiveTo))     
     -- END    
    END        
   END     
  --DELETE THE LOG IF THE COMMAND IS NOT EXECUTED AFTER RETRIES    
  IF(@bitIsCommandSend=0)    
   BEGIN    
    IF EXISTS(SELECT SM.ScheduleId  FROM rvlfScheduleOfCommandsMaster SM    
     INNER JOIN rvlfSchedulingOfCommandsLog SL ON SL.ScheduleId =SM.ScheduleId     
     WHERE(CAST(SL.[No.ofTries] AS INT)-1)=SM.[No.ofRetries] AND SM.ScheduleId=@bigScheduleId AND CONVERT(DATE,SM.EffectiveTo) >=CONVERT(DATE,GETUTCDATE()))    
     BEGIN    
      --UPDATE rvlfScheduleOfCommandsMaster SET ActualExecutionDate=CASE WHEN @dtActualEcecution < CreatedDate THEN CreatedDate ELSE @dtActualEcecution END    
      UPDATE rvlfScheduleOfCommandsMaster SET ActualExecutionDate=@dtActualEcecution     
       WHERE ScheduleId=@bigScheduleId-- AND @dtActualEcecution BETWEEN EffectiveFrom AND EffectiveTo     
      DELETE FROM rvlfSchedulingOfCommandsLog WHERE ScheduleId =@bigScheduleId    
          
     END    
    ELSE IF EXISTS(SELECT SM.ScheduleId  FROM rvlfScheduleOfCommandsMaster SM    
     INNER JOIN rvlfSchedulingOfCommandsLog SL ON SL.ScheduleId =SM.ScheduleId     
     WHERE(CAST(SL.[No.ofTries] AS INT)-1)=SM.[No.ofRetries] AND SM.ScheduleId=@bigScheduleId AND CONVERT(DATE,SM.EffectiveTo)<CONVERT(DATE,GETUTCDATE()))         
     BEGIN    
      UPDATE rvlfScheduleOfCommandsMaster SET ActualExecutionDate=NULL WHERE ScheduleId=@bigScheduleId     
     END    
   END    
      
 END       
        
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateRFIDStudentSMSDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
        
CREATE Procedure [dbo].[rvlf_sp_UpdateRFIDStudentSMSDetails]         
 @vcVehId varchar(max)=null,        
 @bitType bit=null        
AS        
/******************************************************************************/        
-- Name  : [rvlf_sp_UpdateRFIDStudentSMSDetails] 20,null       
-- Description : To update the vehicle expire details.        
-- Author  : K.Kapilraj        
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
--    : 01-Oct-2014 VN Created initial version        
/******************************************************************************/        
BEGIN       
        
   UPDATE rvlfRFIDSchoolSMSNotification SET ISSMSSENT=1, SMSProcessedDateTime = GETUTCDATE()   WHERE Sno =CAST(@vcVehId AS bigint)    
      
END        
      
      
      
--select * from rvlfRFIDSchoolSMSNotification 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateScheduledReports]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateScheduledReports]
	@bigScheduledID bigint = null,
	@dtNextGenerationDate DateTime = null,
	@dtNextStartDate DateTime = null,
	@dtNextEndDate DateTime = null,
	@bitCanGenerate bit = 0,
	@dtLastGeneratedDateTime DateTime = null
AS
/*******************************************************************************************/
--	Name		:	rvlf_sp_UpdateScheduledReports 1
--	Description	:	To update the scheduled reports
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	02-Mar-2010	MJJC	Created Intial Version 
--              :   11-Mar-2010 MJJC	Included the start and end date update
/******************************************************************************************/
BEGIN
	SET NOCOUNT ON 
		 
		DECLARE @vcErrorMessage varchar(150)
		
		BEGIN TRANSACTION UpdateScheduledReports
			BEGIN TRY
				IF EXISTS (SELECT * FROM rvlfSchedulingReport WHERE ReportScheduleId = @bigScheduledID)
					BEGIN
						UPDATE rvlfSchedulingReport SET 
						NextGenerationDateTime = @dtNextGenerationDate /*CASE @bitCanGenerate WHEN 0 THEN NULL ELSE  @dtNextGenerationDate END */,
						ReportStartDate= @dtNextStartDate, --CASE @bitCanGenerate WHEN 0 THEN NULL ELSE   @dtNextStartDate END,
						ReportEndDate = @dtNextEndDate,  --CASE @bitCanGenerate WHEN 0 THEN NULL ELSE  @dtNextEndDate END ,
						IsLocked=0, LockedDateTime= NULL, CanGenerate = @bitCanGenerate,
						lastGeneratedDateTime = @dtLastGeneratedDateTime,
						ModifiedDateTime=GETUTCDATE()
						WHERE ReportScheduleId = @bigScheduledID
					END
						
				ELSE
					BEGIN
						SET @vcErrorMessage = 'No such report scheduled !'
						raiserror(@vcErrorMessage, 16 ,1 )
					END		
				COMMIT
			END TRY
			BEGIN CATCH
				ROLLBACK
			END CATCH
	SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateServiceNotificationStatus]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[rvlf_sp_UpdateServiceNotificationStatus]
AS
/*********************************************************************************************/
--	Name		:	[rvlf_sp_UpdateServiceNotificationStatus]
--	Description	:	To update the notification status where notifications sent or not 
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	23-Jun-2010	LK	Created Intial Version 
/*********************************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
		 
	BEGIN TRY
		
		CREATE TABLE #Nearing (ServiceDetailsId BIGINT, OverdueReminder TINYINT, NotificationType TINYINT)

		INSERT INTO #Nearing (ServiceDetailsId, OverdueReminder, NotificationType)
			SELECT ServiceDetailsId, ISNULL(mp.OverdueReminder, 0) AS OverdueReminder,
			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 AS NotificationType
			FROM rvlfVehicleMaintenanceService vm
			INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId
			INNER JOIN rvlfMaintenancePlanDetails pd ON pd.PlanDetailsId = vm.PlanDetailsId
			INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId
			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
			
	    UPDATE ms SET IsNotification1Sent = (CASE WHEN n.NotificationType = 0 THEN 1 ELSE IsNotification1Sent END),
			IsNotification2Sent = (CASE WHEN n.NotificationType = 1 THEN 1 ELSE IsNotification2Sent END),
			IsNotification3Sent = (CASE WHEN n.NotificationType = 2 THEN 1 ELSE IsNotification3Sent END),
			NotificationDate = (CASE WHEN n.NotificationType = 3 THEN DATEADD(D, n.OverdueReminder, (CASE WHEN NotificationDate IS NULL THEN GETUTCDATE() ELSE NotificationDate END)) ELSE NotificationDate END)
	    FROM rvlfVehicleMaintenanceService ms
	    INNER JOIN #Nearing n ON n.ServiceDetailsId = ms.ServiceDetailsId
	    
	    DROP TABLE #Nearing
		
	END TRY
	BEGIN CATCH
		SET @ErrorMessage = 'An Error occured during updation of maintenance service notification status : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END



GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateTracking]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[rvlf_sp_UpdateTracking]
	@dtRequisitionDate datetime=null,
	@vcTrackingDetails varchar(100)=null,
	@bigEmployeeId bigint=null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_UpdateTracking] 
--	Description	:	To update the tracking details. 
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	22-Feb-2010	VN	Created Intial Version 
/******************************************************************************/
BEGIN
	
	UPDATE rvlfEmployeeShifts SET TRACKING=@vcTrackingDetails 
		WHERE ShiftDate=CONVERT(DATE,@dtRequisitionDate)
			AND EmployeeId=@bigEmployeeId  		
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateUserStatus]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateUserStatus]
(
	@Users varchar(max),
	@UserActiveStatus tinyint = 2,
	@UserLockStatus tinyint = 2,
	@UserGroupId int = 0,
	@AssignedBy bigint = 0,
	@AssignedDate DateTime,
	@SMSBasedActiveStatus bigint = 0
)

AS
/******************************************************************************/
--	Name		:	rvlf_sp_UpdateUserStatus
--	Description	:	To update the user status
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	29-Jul-2009		Created Intial Version 
--              :   Modified on 14-Aug-09
--				:	04-Feb-2010	MJJC	Included the validation of the administrator user and security admin check
--				:	10-Feb-2010 MJJC	Changed the checking based on the users list.
/******************************************************************************/
BEGIN
SET NOCOUNT ON 

	DECLARE @bitIsError bit = 0
	DECLARE @vcErrorMessage varchar(max)
	DECLARE @bigAdministratorUserID bigint
	DECLARE @bigOrganizationID bigint
	DECLARE @bitIsDefaultGroupUser bit
	DECLARE @bitIsAnyDefaultUser bit
	
	SELECT @bigOrganizationID = OrganizationId FROM rvlfUser where UserId 
		in (SELECT * FROM rvlf_fn_ConvertArrayToTable(@Users,','))
	--= @AssignedBy
	SELECT @bigAdministratorUserID = UserID FROM rvlfUser WHERE OrganizationId = @bigOrganizationID 
		AND UserName = 'Administrator'

	SELECT @bitIsDefaultGroupUser = g.IsDefaultUserGroup FROM rvlfUserGroupAssignment ga
		INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId
	WHERE UserId = @AssignedBy 
	
	SELECT @bitIsAnyDefaultUser = g.IsDefaultUserGroup FROM rvlfUserGroupAssignment ga
		INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId
	WHERE UserId IN (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@Users,',')) AND g.IsDefaultUserGroup= 1
		
	IF EXISTS(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@Users,',') Where FieldValue = @bigAdministratorUserID)
		BEGIN
			SET @vcErrorMessage = 'Changing status or reassigning of the Admimistrator user is not allowed'
			SET @bitIsError = 1
		END
	IF @bitIsDefaultGroupUser = 0 AND @bitIsAnyDefaultUser = 1
		BEGIN
			SET @vcErrorMessage = ISNULL(@vcErrorMessage+'\n','') + 'Changing status or reassigning of the security admin users are not allowed'
			SET @bitIsError = 1
		END
	IF @bitIsError = 0
		BEGIN	
			IF(@UserActiveStatus <> 2 OR @UserLockStatus <> 2)
				BEGIN
					UPDATE rvlfUser SET IsActive = (CASE WHEN @UserActiveStatus <> 2 THEN @UserActiveStatus ELSE IsActive END), 
						IsLocked = (CASE WHEN @UserLockStatus <> 2 THEN @UserLockStatus ELSE IsLocked END) 
						WHERE UserId IN (SELECT FieldValue FROM rvlf_fn_ConvertArrayToTable(@Users,','))
			END
			
			IF(@UserGroupId > 0)
				BEGIN
					DELETE FROM rvlfUserGroupAssignment WHERE UserId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@Users,','))
					INSERT INTO rvlfUserGroupAssignment(UserId, UserGroupId, AssignedBy, AssignedDate)
						(SELECT v.UserId, @UserGroupId, @AssignedBy, @AssignedDate FROM rvlfUser v 
						WHERE v.UserId IN (SELECT * FROM rvlf_fn_ConvertArrayToTable(@Users,',')))
				END
		END
	ELSE
		BEGIN
			raiserror (@vcErrorMessage,16,1)
		END	
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateVehicleExpiredDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateVehicleExpiredDetails]	
	@vcVehId varchar(max)=null,
	@bitType bit=null
AS
/******************************************************************************/
--	Name		:	[rvlf_sp_UpdateVehicleExpiredDetails]
--	Description	:	To update the vehicle expire details.
--	Author		:	V.Narayanasamy
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	28-July-2010	VN Created initial version
/******************************************************************************/
BEGIN
	IF(@bitType=1)
		BEGIN
			UPDATE rvlfVehicle SET ISEMAILSENT=1 WHERE VehicleId IN (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@vcVehId,','))
		END
	ELSE
		BEGIN
			UPDATE rvlfVehicle SET ISSMSSENT=1 WHERE VehicleId =CAST(@vcVehId AS BIGINT) 
		END
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateVehicleInfo]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[rvlf_sp_UpdateVehicleInfo]
/******************************************************
Stored Procedure Name : rvlf_sp_UpdateVehicleInfo
Purpose     : Update vehicle information
Created by    : Uma
Created date   : 20-Jul-09
Updated by    :
Updated date   :
*******************************************************/
@VehicleId  bigint   = Null,
@VehTypeID  tinyint   = Null,
@VehName  varchar(50)  = Null,
@MakeID   smallint  = Null,
@VIN   varchar(20)  = Null,
@ModelID  smallint  = Null,
@LICPlate  varchar(20)  = Null,
@Year   smallint  = Null,
@TimeZoneId bigint,
@Email   varchar(2010) = Null,
@Color   varchar(20)  = Null,
@SMS varchar(160) = null,
@Notify bit,
@Warning bit,
@Critical bit,
@Modifiedby	bigint	= Null,
@ModifiedDateTime DateTime,
@tblNotificationsList As NotificaitonUserList READONLY

AS      

BEGIN       

 SET NOCOUNT ON

	--DECLARE @isVehNameExist AS INT = 0
	--DECLARE @isVINExist AS INT = 0
	--DECLARE @isLicensePlateExist AS INT = 0
	
	--SET @isVehNameExist = (SELECT COUNT(*) FROM rvlfVehicle WHERE VehicleId <> @VehicleId AND VehicleDescription = @VehName)
	--SET @isVINExist = (SELECT COUNT(*) FROM rvlfVehicle WHERE VehicleId <> @VehicleId AND Vin = @VIN)
 --   SET @isLicensePlateExist = (SELECT COUNT(*) FROM rvlfVehicle WHERE VehicleId <> @VehicleId AND LicensePlate = @LICPlate)
    
	--IF((@isVehNameExist = 0) and (@isVINExist = 0) and (@isLicensePlateExist = 0))
	--	BEGIN
		   IF (@VehicleId > 0)
			 BEGIN
				 UPDATE rvlfVehicle SET
				 VehicleTypeId =@VehTypeID,
				 VehicleDescription=@VehName,
				 MakeId=@MakeID,
				 Vin=@VIN,
				 ModelId=@ModelID,
				 LicensePlate=@LICPlate,
				 ModelYear= @Year,
				 TimeZone=@TimeZoneId,
				 Email=@Email,
				 Color=@Color,
				 SMS=@SMS,
				 Notify=@Notify,
				 Warning=@Warning,
				 Critical=@Critical,
				 ModifiedBy=@Modifiedby,
				 [Modified DateTime]=@ModifiedDateTime
				 WHERE VehicleId =@VehicleId

				 DELETE FROM rvlfNotificationList WHERE TypeID = @VehicleId AND NotificationType = 4

				 exec rvlf_sp_Save_notificationsList @tblNotificationsList,4,@VehicleId
				 
				 SELECT 'Success' AS 'UpdateStatus'
		    END
	--	END
	--ELSE
	--	BEGIN
	--		IF(@isVehNameExist <> 0)
	--			BEGIN
	--				 SELECT 'VName' AS 'UpdateStatus'
	--			END
	--		ELSE IF (@isVINExist <> 0)
	--			BEGIN
	--				 SELECT 'VIN' AS 'UpdateStatus'
	--			END
	--		ELSE IF (@isLicensePlateExist <> 0)
	--			BEGIN
	--				 SELECT 'LPlate' AS 'UpdateStatus'
	--			END
	--	END
	SET NOCOUNT OFF

END



exec rvlf_sp_UpdateVehicleInfo @Warning=N'False',@Email=N'',@Year=N'2009',@Modifiedby=N'3',@ModifiedDateTime='2009-09-17 12:11:36.4700000',@Notify=N'False',@MakeID=N'1',@SMS=N'',@VIN=N'1M8GDM9AXKP042760',@VehTypeID=N'1',@Critical=N'False',@VehicleId=N'9',@ModelID=N'1',@TimeZoneId=N'1',@LICPlate=N'TN 32 112212',@Color=N'Silky Silver',@VehName=N'Test Device'

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateVehicleNearingPercentage]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
CREATE Procedure [dbo].[rvlf_sp_UpdateVehicleNearingPercentage]          
AS          
/******************************************************************************/          
-- Name  : rvlf_sp_UpdateVehicleNearingPercentage          
-- Description : To update the current Vehicle Odometer Reading & Engine Hours,           
--     Nearing Percentage and IsNearing          
-- Author  : Kumuthini. L          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
/******************************************************************************/          
BEGIN          
SET NOCOUNT ON           
           
 -- Select the vehicles for which the current readings, nearing (%) and IsNearing has to be calculated          
 CREATE TABLE #VehTemp (VehicleId BIGINT)          
          
 INSERT INTO #VehTemp (VehicleId)          
 SELECT DISTINCT VehicleId FROM rvlfVehicle v          
 INNER JOIN rvlfOrganizationPackage op ON op.OrganizationID = v.OrganizationId         
 INNER JOIN rvlfPackageOperations po ON po.PackageId = op.PackageId          
 WHERE (po.ModuleID = 29 OR v.OrganizationId = 36) -- 36 (Cube enabled for live testing)          
 AND v.OrganizationId NOT IN (15, 30) -- 15 (Sun Tech.) & 30 (Demo)          
          
 -- ENGINE HOURS          
    -- Get the dates for the vehicles for which the manual entry is present          
 CREATE TABLE #ManualTemp (OriginDateTime Date, VehicleId BIGINT)          
          
 INSERT INTO #ManualTemp (OriginDateTime, VehicleId)          
  SELECT DISTINCT CONVERT(DATE, h.OriginDateTime), va.VehicleId FROM rvlfMsgInHst h            
  INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId          
  INNER JOIN #VehTemp vt ON vt.VehicleId = va.VehicleId          
  WHERE h.BoxMsgInTypeId = 3 AND CONVERT(DATE, h.OriginDateTime) IN           
   (          
    SELECT CONVERT(DATE, h.OriginDateTime) FROM rvlfManualEntry me           
    WHERE me.VehicleId = va.VehicleId AND           
    CONVERT(DATE, h.OriginDateTime) BETWEEN me.FromDate AND me.ToDate          
   )          
          
 -- Fetch total Engine Hours for each applicable vehicles except the engine hrs present during the Manual           
 -- Entry Duration    
 CREATE TABLE #CalculTemp (VehicleId BIGINT, EngineHrs BIGINT)   
 INSERT INTO #CalculTemp (VehicleId, EngineHrs)        
 SELECT v.VehicleId, EngineHrs = 0
 FROM rvlfMsgInHst_Techno h     
 INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId    
 INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId    
 INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId    
 WHERE h.BoxMsgInTypeId = 3 AND CONVERT(DATE, h.OriginDateTime) NOT IN     
  (SELECT mt.OriginDateTime FROM #ManualTemp mt WHERE mt.VehicleId = va.VehicleId)    
 GROUP BY h.BoxId, v.VehicleId,h.CustomProp    

  INSERT INTO #CalculTemp (VehicleId, EngineHrs)        
 SELECT v.VehicleId, EngineHrs = 0
 FROM rvlfMsgInHst_Techno_355 h     
 INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId    
 INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId    
 INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId    
 WHERE h.BoxMsgInTypeId = 3 AND CONVERT(DATE, h.OriginDateTime) NOT IN     
  (SELECT mt.OriginDateTime FROM #ManualTemp mt WHERE mt.VehicleId = va.VehicleId)    
 GROUP BY h.BoxId, v.VehicleId,h.CustomProp   
   
   DROP TABLE #ManualTemp          
 CREATE TABLE #tempEngineHrs(VehicleId BIGINT, EngineHrs BIGINT)          
 INSERT INTO #tempEngineHrs(VehicleId, EngineHrs)    
  select VehicleId,SUM(EngineHrs) from #CalculTemp group by VehicleId  
    -- Add the Manual Entry Engine Hrs to Total Engine Hours for each applicable vehicles    
 UPDATE #tempEngineHrs SET EngineHrs = EngineHrs +     
 (SELECT ISNULL(SUM(me.EngineHours),0) FROM rvlfManualEntry me WHERE me.VehicleId = #tempEngineHrs.VehicleId)       
 --INSERT INTO #tempEngineHrs(VehicleId, EngineHrs)          
 --SELECT v.VehicleId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,          
 --      CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -           
 --      (CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'          
 --FROM rvlfMsgInHst h           
 --INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId          
 --INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId          
 --INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId          
 --WHERE h.BoxMsgInTypeId = 3 AND CONVERT(DATE, h.OriginDateTime) NOT IN           
 -- (SELECT mt.OriginDateTime FROM #ManualTemp mt WHERE mt.VehicleId = va.VehicleId)          
 --GROUP BY h.BoxId, v.VehicleId        
       
          
 --   -- Add the Manual Entry Engine Hrs to Total Engine Hours for each applicable vehicles          
 --UPDATE #tempEngineHrs SET EngineHrs = EngineHrs +           
 --(SELECT ISNULL(SUM(me.EngineHours),0) FROM rvlfManualEntry me WHERE me.VehicleId = #tempEngineHrs.VehicleId)          
          
    -- ODOMETER READINGS          
 -- Fetch current Odometer Reading for each applicable vehicles          
 CREATE TABLE #tempOdometer(VehicleId BIGINT, OdometerReading BIGINT)           
            
 INSERT INTO #tempOdometer(VehicleId, OdometerReading)          
 SELECT t.VehicleId,0
 --#
 --MAX(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,          
 --(CHARINDEX(';',CustomProp, CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9)))          
 --#
 FROM (SELECT v.VehicleId, h.BoxId, MAX(OriginDateTime) AS OriginDateTime          
 FROM rvlfMsgInHst_Techno h           
 INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId          
 INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId          
 INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId          
 WHERE h.CustomProp LIKE '%Odometer%'          
 GROUP BY h.BoxId, v.VehicleId) t          
 INNER JOIN rvlfMsgInHst_Techno hh ON hh.BoxId = t.BoxId          
 WHERE hh.OriginDateTime = t.OriginDateTime AND hh.CustomProp LIKE '%Odometer%'  AND BoxMsgInTypeId <> 77          
 GROUP BY t.VehicleId        
 
  INSERT INTO #tempOdometer(VehicleId, OdometerReading)          
 SELECT t.VehicleId,0
 --#
 --MAX(SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,          
 --(CHARINDEX(';',CustomProp, CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9)))          
 --#
 FROM (SELECT v.VehicleId, h.BoxId, MAX(OriginDateTime) AS OriginDateTime          
 FROM rvlfMsgInHst_Techno_355 h           
 INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId          
 INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId          
 INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId          
 WHERE h.CustomProp LIKE '%Odometer%'          
 GROUP BY h.BoxId, v.VehicleId) t          
 INNER JOIN rvlfMsgInHst_Techno_355 hh ON hh.BoxId = t.BoxId          
 WHERE hh.OriginDateTime = t.OriginDateTime AND hh.CustomProp LIKE '%Odometer%'  AND BoxMsgInTypeId <> 77          
 GROUP BY t.VehicleId  
           
 -- Add the Manual Entry Kilometers Run to Odometer Reading for each applicable vehicles          
 UPDATE #tempOdometer SET OdometerReading = OdometerReading +            
 ISNULL((SELECT ISNULL(SUM(me.Kilometers), 0) AS Kilometers FROM rvlfManualEntry me           
   WHERE me.VehicleId = #tempOdometer.VehicleId           
    AND me.FromDate > (SELECT CONVERT(DATE, MAX(OriginDateTime)) FROM rvlfMsgInHst_Techno h           
          INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId          
          INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId          
          INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId          
          WHERE v.VehicleId = me.VehicleId          
          GROUP BY v.VehicleId          
         )           
   GROUP BY me.VehicleId          
     ), 0)      
	 
UPDATE #tempOdometer SET OdometerReading = OdometerReading +            
 ISNULL((SELECT ISNULL(SUM(me.Kilometers), 0) AS Kilometers FROM rvlfManualEntry me           
   WHERE me.VehicleId = #tempOdometer.VehicleId           
    AND me.FromDate > (SELECT CONVERT(DATE, MAX(OriginDateTime)) FROM rvlfMsgInHst_Techno_355 h           
          INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId          
          INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId          
          INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId          
          WHERE v.VehicleId = me.VehicleId          
          GROUP BY v.VehicleId          
         )           
   GROUP BY me.VehicleId          
     ), 0) 
          
    -- READINGS TABLE          
 CREATE TABLE #tempReadings(VehicleId bigint, OdometerReading bigint, EngineHrs bigint)          
              
 INSERT INTO #tempReadings(VehicleId, OdometerReading, EngineHrs)           
 SELECT vt.VehicleId, ISNULL(o.OdometerReading, 0), ISNULL(e.EngineHrs, 0) FROM #VehTemp vt          
 LEFT OUTER JOIN #tempEngineHrs e ON e.VehicleId = vt.VehicleId          
 LEFT OUTER JOIN #tempOdometer o ON o.VehicleId = vt.VehicleId          
          
 DROP TABLE #tempEngineHrs          
 DROP TABLE #tempOdometer          
           
 -- Update the current readings in the vehicle current readings table for the selected vehicles          
 UPDATE vcr SET vcr.CurrentEngineHours = (CASE WHEN tr.EngineHrs > 0 THEN tr.EngineHrs ELSE vcr.CurrentEngineHours END),           
 vcr.CurrentOdometerReading = (CASE WHEN tr.OdometerReading > 0 THEN tr.OdometerReading ELSE vcr.CurrentOdometerReading END)          
 FROM rvlfVehicleCurrentReadings vcr          
 INNER JOIN #tempReadings tr ON tr.VehicleId = vcr.VehicleId          
          
 DROP TABLE #tempReadings          
 DROP TABLE #VehTemp    
 DROP TABLE #CalculTemp
           
 -- Calculate Nearing Percentage for the selected vehicles          
 CREATE TABLE #tempNearingPer(ServiceDetailsId bigint, Nearing int)           
          
 INSERT INTO #tempNearingPer(ServiceDetailsId, Nearing)          
 SELECT vm.ServiceDetailsId,           
 ((CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3  THEN (CASE WHEN mp.RecurringService = 0 THEN (ISNULL(CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0))as FLOAT)/ 3600 as DECIMAL(18,2)),0) * 100)
    ELSE (CASE WHEN ((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours, 0)) - vm.StatusChangeOn) >= 0 THEN (((ISNULL(CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0)) as FLOAT)/ 3600 as DECIMAL(18,2)),0)) - vm.StatusChangeOn) * 100) ELSE 0 END) END)   
     WHEN vm.ServiceType = 1 THEN (CASE WHEN mp.RecurringService = 0 THEN (cr.CurrentOdometerReading * 100)          
    ELSE (CASE WHEN (cr.CurrentOdometerReading - vm.StatusChangeOn) >= 0 THEN ((cr.CurrentOdometerReading - vm.StatusChangeOn) * 100) ELSE 0 END) END)           
     WHEN vm.ServiceType = 2 THEN (CASE WHEN (CONVERT(DATE, vm.DueOnDate) = CONVERT(DATE, GETUTCDATE()) AND mp.RecurringService = 0) THEN 100 ELSE (CASE WHEN DATEDIFF(D, vm.StartDate, GETUTCDATE()) > 0 THEN DATEDIFF(D, vm.StartDate, GETUTCDATE()) ELSE 0 END) * 100 END)          
   END) / (CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 1 OR vm.ServiceType = 3  THEN (CASE WHEN mp.RecurringService = 0 THEN vm.DueOn ELSE pd.ServiceInterval END) ELSE (          
        CASE WHEN mp.RecurringService = 1 THEN          
        (CASE WHEN vm.Frequency = 0 THEN pd.ServiceInterval          
          WHEN vm.Frequency = 1 THEN (pd.ServiceInterval * 30)          
          WHEN vm.Frequency = 2 THEN (pd.ServiceInterval * 365) END)          
        ELSE (CASE WHEN CONVERT(DATE, vm.DueOnDate) = CONVERT(DATE, GETUTCDATE()) THEN 1 ELSE (CASE WHEN DATEDIFF(D, vm.StartDate, vm.DueOnDate) > 0 THEN DATEDIFF(D, vm.StartDate, vm.DueOnDate) ELSE 1 END) END) END          
    )           
    END)           
 ) AS Nearing          
 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          
 WHERE vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1 AND v.OrganizationId NOT IN (15, 30)          
            
 -- Update the calculated nearing percentage and Overdue Date          
 UPDATE ms SET NearingPercentage = np.Nearing, OverdueDate = (CASE WHEN np.Nearing >= 100 AND OverdueDate IS NULL THEN GETUTCDATE() ELSE OverdueDate END),          
 EngineHrsOnDue = (CASE WHEN np.Nearing >= 100 AND EngineHrsOnDue IS NULL THEN CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0)) as FLOAT)/ 3600 as decimal(18,2)) ELSE EngineHrsOnDue END),           
 OdometerReadingOnDue = (CASE WHEN np.Nearing >= 100 AND OdometerReadingOnDue IS NULL THEN cr.CurrentOdometerReading ELSE OdometerReadingOnDue END)          
 FROM rvlfVehicleMaintenanceService ms          
 INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = ms.VehiclePlanId          
    INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId          
    INNER JOIN rvlfVehicle v ON v.VehicleId = cr.VehicleId           
    INNER JOIN #tempNearingPer np ON np.ServiceDetailsId = ms.ServiceDetailsId          
           
 DROP TABLE #tempNearingPer          
           
 -- Update IsNearing field for the plan using the calculated nearing (%)          
 CREATE TABLE #tempIsNearing(VehiclePlanId bigint, Nearing int)           
          
 INSERT INTO #tempIsNearing(VehiclePlanId, Nearing)          
 SELECT vm.VehiclePlanId, MAX(vm.NearingPercentage) AS Nearing FROM rvlfVehicleMaintenanceService vm          
 INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId          
 INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId           
 WHERE vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1           
 GROUP BY vm.VehiclePlanId          
          
 UPDATE vm SET vm.IsNearing = (CASE WHEN vm.NearingPercentage = t.Nearing THEN 1 ELSE 0 END) FROM rvlfVehicleMaintenanceService vm          
 INNER JOIN #tempIsNearing t ON t.VehiclePlanId = vm.VehiclePlanId          
 WHERE vm.Status = 0          
          
 DROP TABLE #tempIsNearing          
           
SET NOCOUNT OFF          
END 


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateVehicleNearingPercentage_20210626]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Procedure [dbo].[rvlf_sp_UpdateVehicleNearingPercentage_20210626]
AS
/******************************************************************************/
-- Name : rvlf_sp_UpdateVehicleNearingPercentage
-- Description : To update the current Vehicle Odometer Reading & Engine Hours,
-- Nearing Percentage and IsNearing
-- Author : Kumuthini. L
-- Company : Angler Technologies
-- History : <<Date(dd-MON-yyyy)>> Initial Reason
/******************************************************************************/
	BEGIN
		SET NOCOUNT ON
		-- Select the vehicles for which the current readings, nearing (%) and IsNearing has to be calculated
		CREATE TABLE #VehTemp (VehicleId BIGINT INDEX IX2ver NONCLUSTERED)

		INSERT INTO #VehTemp (VehicleId)
		SELECT DISTINCT VehicleId FROM rvlfVehicle v
		INNER JOIN rvlfOrganizationPackage op ON op.OrganizationID = v.OrganizationId
		INNER JOIN rvlfPackageOperations po ON po.PackageId = op.PackageId
		WHERE (po.ModuleID = 29 ) 
		--v.OrganizationId IN (1,6,86,132) AND (po.ModuleID = 29 ) --OR v.OrganizationId = 36
		-- 36 (Cube enabled for live testing)
		--AND v.OrganizationId NOT IN (15, 30) -- 15 (Sun Tech.) & 30 (Demo)
		 
		-- ENGINE HOURS
		-- Get the dates for the vehicles for which the manual entry is present
		CREATE TABLE #ManualTemp (OriginDateTime Date, VehicleId BIGINT INDEX IX2Manual NONCLUSTERED)

		INSERT INTO #ManualTemp (OriginDateTime, VehicleId)
		SELECT DISTINCT CONVERT(DATE, h.OriginDateTime), va.VehicleId FROM rvlfMsgInHst h
		INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId
		INNER JOIN #VehTemp vt ON vt.VehicleId = va.VehicleId
		WHERE-- h.BoxMsgInTypeId = 3 AND
		CONVERT(DATE, h.OriginDateTime) IN
		(
			SELECT CONVERT(DATE, h.OriginDateTime) FROM rvlfManualEntry me
			WHERE me.VehicleId = va.VehicleId AND
			CONVERT(DATE, h.OriginDateTime) BETWEEN me.FromDate AND me.ToDate
		)

		-- Fetch total Engine Hours for each applicable vehicles except the engine hrs present during the Manual
		-- Entry Duration
		CREATE TABLE #CalculTemp (VehicleId BIGINT INDEX IDX_CalculTemp_Vehicle NONCLUSTERED, EngineHrs BIGINT INDEX IDX_CalculTemp_EngineHrs NONCLUSTERED)

		--INSERT INTO #CalculTemp (VehicleId, EngineHrs)
		--Select a.VehicleId, sum(EngineHrs) from (
		--SELECT v.VehicleId, EngineHrs =
		--(case when vt1.VehicleTypeId in (1,2) and isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR1=',';'),0) > p.RC1
		--then isnull(Datediff(HH,min(origindatetime),max(Origindatetime)),0)
		--when vt1.VehicleTypeId in (3,4) and isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR1=',';'),0) > p.RC1 and isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR2=',';'),0) > p.RC2
		--then isnull(Datediff(HH,min(origindatetime),max(Origindatetime)),0)
		--else 0 end)
		--FROM rvlfMsgInHst h
		--inner join rvlfParamRange p on h.BoxId=p.Boxid
		--inner join rvlfMAKDevices md on md.BoxId=h.BoxId
		--inner join rvlfVehicleType vt1 on vt1.VehicleTypeId=md.SubTypeId
		--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
		--INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		--INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId
		--WHERE --h.BoxMsgInTypeId = 3 AND
		--(h.OriginDateTime between dateadd(MONTH,-6,GETUTCDATE()) and GETUTCDATE()) and
		--CONVERT(DATE, h.OriginDateTime) NOT IN
		--(SELECT mt.OriginDateTime FROM #ManualTemp mt WHERE mt.VehicleId = va.VehicleId)
		--GROUP BY h.BoxId, v.VehicleId,h.CustomProp, vt1.VehicleTypeId,RC1,RC2 ) as a GROUP BY a.VehicleId

		--7410
		INSERT INTO #CalculTemp (VehicleId, EngineHrs)
		Select a.VehicleId, sum(EngineHrs) from (
		SELECT v.VehicleId, EngineHrs =0
		FROM rvlfMsgInHst_Techno h
		--inner join rvlfParamRange p on h.BoxId=p.Boxid
		inner join rvlfMAKDevices md on md.BoxId=h.BoxId
		inner join rvlfVehicleType vt1 on vt1.VehicleTypeId=md.SubTypeId
		INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId
		WHERE --h.BoxMsgInTypeId = 3 AND
		(h.OriginDateTime between dateadd(MONTH,-6,GETUTCDATE()) and GETUTCDATE()) and
		CONVERT(DATE, h.OriginDateTime) NOT IN
		(SELECT mt.OriginDateTime FROM #ManualTemp mt WHERE mt.VehicleId = va.VehicleId)
		GROUP BY h.BoxId, v.VehicleId,h.CustomProp, vt1.VehicleTypeId) as a GROUP BY a.VehicleId

		--355
		INSERT INTO #CalculTemp (VehicleId, EngineHrs)
		Select a.VehicleId, sum(EngineHrs) from (
		SELECT v.VehicleId, EngineHrs =0
		FROM rvlfMsgInHst_Techno_355 h
		--inner join rvlfParamRange p on h.BoxId=p.Boxid
		inner join rvlfMAKDevices md on md.BoxId=h.BoxId
		inner join rvlfVehicleType vt1 on vt1.VehicleTypeId=md.SubTypeId
		INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId
		WHERE --h.BoxMsgInTypeId = 3 AND
		(h.OriginDateTime between dateadd(MONTH,-6,GETUTCDATE()) and GETUTCDATE()) and
		CONVERT(DATE, h.OriginDateTime) NOT IN
		(SELECT mt.OriginDateTime FROM #ManualTemp mt WHERE mt.VehicleId = va.VehicleId)
		GROUP BY h.BoxId, v.VehicleId,h.CustomProp, vt1.VehicleTypeId) as a GROUP BY a.VehicleId

		DROP TABLE #ManualTemp

		CREATE TABLE #tempEngineHrs(VehicleId BIGINT INDEX IDX_tempEngineHrs_VehicleId NONCLUSTERED, EngineHrs BIGINT INDEX IDX_tempEngineHrs_EngineHrs NONCLUSTERED)

		INSERT INTO #tempEngineHrs(VehicleId, EngineHrs)
		select VehicleId,SUM(EngineHrs) from #CalculTemp group by VehicleId

		-- Add the Manual Entry Engine Hrs to Total Engine Hours for each applicable vehicles
		UPDATE #tempEngineHrs SET EngineHrs = ISNULL(EngineHrs,0) + (SELECT ISNULL(SUM(me.EngineHours),0) FROM rvlfManualEntry me WHERE me.VehicleId = #tempEngineHrs.VehicleId)
		--INSERT INTO #tempEngineHrs(VehicleId, EngineHrs)
		--SELECT v.VehicleId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,
		-- CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -
		-- (CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'
		--FROM rvlfMsgInHst h
		--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
		--INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		--INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId
		--WHERE h.BoxMsgInTypeId = 3 AND CONVERT(DATE, h.OriginDateTime) NOT IN
		-- (SELECT mt.OriginDateTime FROM #ManualTemp mt WHERE mt.VehicleId = va.VehicleId)
		--GROUP BY h.BoxId, v.VehicleId
		-- -- Add the Manual Entry Engine Hrs to Total Engine Hours for each applicable vehicles
		--UPDATE #tempEngineHrs SET EngineHrs = EngineHrs +
		--(SELECT ISNULL(SUM(me.EngineHours),0) FROM rvlfManualEntry me WHERE me.VehicleId = #tempEngineHrs.VehicleId)
		-- ODOMETER READINGS
		-- Fetch current Odometer Reading for each applicable vehicles

		CREATE TABLE #tempOdometer(VehicleId BIGINT INDEX IDX_tempOdometer_VehicleId NONCLUSTERED, OdometerReading BIGINT INDEX IDX_tempOdometer_OdometerReading NONCLUSTERED)

		INSERT INTO #tempOdometer(VehicleId, OdometerReading)
		SELECT t.VehicleId, MAX(
		--SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,
		--(CHARINDEX(';',CustomProp, CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9))
		ISNULL(CAST([dbo].[rvlf_fn_GetParamValueWithIndex](CustomProp,'Odometer=',';') AS INT),0)
		)
		FROM (SELECT v.VehicleId, h.BoxId, MAX(OriginDateTime) AS OriginDateTime
		FROM rvlfMsgInHst h
		INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId
		WHERE
		--h.CustomProp LIKE '%Odometer%'
		h.odometer > 0
		GROUP BY h.BoxId, v.VehicleId) t
		INNER JOIN rvlfMsgInHst hh ON hh.BoxId = t.BoxId
		WHERE hh.OriginDateTime = t.OriginDateTime AND
		--hh.CustomProp LIKE '%Odometer%'
		hh.odometer > 0
		AND BoxMsgInTypeId <> 77
		GROUP BY t.VehicleId
		-- Add the Manual Entry Kilometers Run to Odometer Reading for each applicable vehicles

		UPDATE #tempOdometer SET OdometerReading = ISNULL(OdometerReading,0) + ISNULL((SELECT ISNULL(SUM(me.Kilometers), 0) AS Kilometers FROM rvlfManualEntry me
		WHERE me.VehicleId = #tempOdometer.VehicleId
		AND me.FromDate > (SELECT CONVERT(DATE, MAX(OriginDateTime)) FROM rvlfMsgInHst h
		INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId
		WHERE v.VehicleId = me.VehicleId
		GROUP BY v.VehicleId
		)
		GROUP BY me.VehicleId
		), 0)
		-- READINGS TABLE

		CREATE TABLE #tempReadings(VehicleId bigint INDEX IDX_tempReadings_VehicleId NONCLUSTERED, OdometerReading bigint INDEX IDX_tempReadings_OdometerReading NONCLUSTERED, EngineHrs bigint INDEX IDX_OdometerReading_EngineHrs NONCLUSTERED)

		INSERT INTO #tempReadings(VehicleId, OdometerReading, EngineHrs)
		SELECT vt.VehicleId, ISNULL(o.OdometerReading, 0), ISNULL(e.EngineHrs, 0) FROM #VehTemp vt
		LEFT OUTER JOIN #tempEngineHrs e ON e.VehicleId = vt.VehicleId
		LEFT OUTER JOIN #tempOdometer o ON o.VehicleId = vt.VehicleId

		DROP TABLE #tempEngineHrs

		DROP TABLE #tempOdometer

		-- Update the current readings in the vehicle current readings table for the selected vehicles
		UPDATE vcr SET vcr.CurrentEngineHours = (CASE WHEN ISNULL(tr.EngineHrs,0) > 0 THEN ISNULL(tr.EngineHrs,0) ELSE ISNULL(vcr.CurrentEngineHours,0) END),
		vcr.CurrentOdometerReading = (CASE WHEN ISNULL(tr.OdometerReading,0) > 0 THEN ISNULL(tr.OdometerReading,0) ELSE ISNULL(vcr.CurrentOdometerReading,0) END)
		FROM rvlfVehicleCurrentReadings vcr
		INNER JOIN #tempReadings tr ON tr.VehicleId = vcr.VehicleId

		DROP TABLE #tempReadings

		DROP TABLE #VehTemp

		-- Calculate Nearing Percentage for the selected vehicles
		CREATE TABLE #tempNearingPer(ServiceDetailsId bigint INDEX IDX_tempNearingPer_ServiceDetailsId NONCLUSTERED, Nearing int INDEX IDX_tempNearingPer_Nearing NONCLUSTERED)

		INSERT INTO #tempNearingPer(ServiceDetailsId, Nearing)
		SELECT vm.ServiceDetailsId,
		(
		(
			CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3 THEN 
				(
					CASE WHEN mp.RecurringService = 0 THEN 
						(ISNULL(CAST(CAST((ISNULL(cr.CurrentEngineHours,0) + ISNULL(v.OpeningEngineHours * 3600, 0))as FLOAT)/ 3600 as DECIMAL(18,2)),0) * 100)
					ELSE 
						(
							CASE WHEN ((ISNULL(cr.CurrentEngineHours,0) + ISNULL(v.OpeningEngineHours, 0)) - ISNULL(vm.StatusChangeOn,0)) >= 0 THEN 
								(((ISNULL(CAST(CAST((ISNULL(cr.CurrentEngineHours,0) + ISNULL(v.OpeningEngineHours * 3600, 0)) as FLOAT)/ 3600 as DECIMAL(18,2)),0)) - ISNULL(vm.StatusChangeOn,0)) * 100) 
							ELSE 
								0 
							END
						) 
					END
				)
			WHEN vm.ServiceType = 1 THEN 
				(
					CASE WHEN mp.RecurringService = 0 THEN 
						(ISNULL(cr.CurrentOdometerReading,0) * 100)
					ELSE 
						(
							CASE WHEN (ISNULL(cr.CurrentOdometerReading,0) - ISNULL(vm.StatusChangeOn,0)) >= 0 THEN 
								((ISNULL(cr.CurrentOdometerReading,0) - ISNULL(vm.StatusChangeOn,0)) * 100) 
							ELSE 
								0 
							END
						) 
					END
				)
			WHEN vm.ServiceType = 2 THEN 
				(
					CASE WHEN (CONVERT(DATE, vm.DueOnDate) = CONVERT(DATE, GETUTCDATE()) AND mp.RecurringService = 0) THEN 
						100 
					ELSE 
						(
							CASE WHEN DATEDIFF(D, vm.StartDate, GETUTCDATE()) > 0 THEN 
								DATEDIFF(D, vm.StartDate, GETUTCDATE()) 
							ELSE 
								(ServiceInterval - DATEDIFF(D, GETUTCDATE(), vm.DueOnDate)) 
							END
						) * 100 
					END
				) END) 
				
				/ 

				(
					CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 1 OR vm.ServiceType = 3 THEN 
						(
							CASE WHEN mp.RecurringService = 0 THEN 
								vm.DueOn 
							ELSE 
								pd.ServiceInterval 
							END
						) 
					ELSE 
						(
							CASE WHEN mp.RecurringService = 1 THEN
								(
									CASE WHEN vm.Frequency = 0 THEN 
										pd.ServiceInterval
									WHEN vm.Frequency = 1 THEN 
										(pd.ServiceInterval * 30)
									WHEN vm.Frequency = 2 THEN 
										(pd.ServiceInterval * 365) 
									END
								)
							ELSE 
								(
									CASE WHEN CONVERT(DATE, vm.DueOnDate) = CONVERT(DATE, GETUTCDATE()) THEN 
										1 
									ELSE 
										(
											ServiceInterval
										) END
								) 
							END
						)
					END
				)
		) AS Nearing
		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 #CalculTemp vt ON vt.VehicleId = v.VehicleId
		WHERE vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1 --AND v.OrganizationId IN (1,6,86,132) --AND v.OrganizationId NOT IN (15, 30)

		--select * 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 #CalculTemp vt ON vt.VehicleId = v.VehicleId
		--WHERE vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1

		DROP TABLE #CalculTemp

		-- Update the calculated nearing percentage and Overdue Date

		UPDATE ms SET NearingPercentage = np.Nearing, OverdueDate = (CASE WHEN np.Nearing >= 100 AND OverdueDate IS NULL THEN GETUTCDATE() ELSE OverdueDate END),
		EngineHrsOnDue = (CASE WHEN np.Nearing >= 100 AND EngineHrsOnDue IS NULL THEN CAST(CAST((ISNULL(cr.CurrentEngineHours,0) + ISNULL(v.OpeningEngineHours * 3600, 0)) as FLOAT)/ 3600 as decimal(18,2)) ELSE EngineHrsOnDue END),
		OdometerReadingOnDue = (CASE WHEN np.Nearing >= 100 AND OdometerReadingOnDue IS NULL THEN ISNULL(cr.CurrentOdometerReading,0) ELSE ISNULL(OdometerReadingOnDue,0) END)
		FROM rvlfVehicleMaintenanceService ms
		INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = ms.VehiclePlanId
		INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId
		INNER JOIN rvlfVehicle v ON v.VehicleId = cr.VehicleId
		INNER JOIN #tempNearingPer np ON np.ServiceDetailsId = ms.ServiceDetailsId

		DROP TABLE #tempNearingPer

		-- Update IsNearing field for the plan using the calculated nearing (%)
		CREATE TABLE #tempIsNearing(VehiclePlanId bigint INDEX IDX_tempIsNearing_VehiclePlanId NONCLUSTERED, Nearing int INDEX IDX_tempIsNearing_Nearing NONCLUSTERED)

		INSERT INTO #tempIsNearing(VehiclePlanId, Nearing)
		SELECT vm.VehiclePlanId, MAX(vm.NearingPercentage) AS Nearing FROM rvlfVehicleMaintenanceService vm
		INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId
		INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId
		WHERE vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1
		GROUP BY vm.VehiclePlanId

		UPDATE vm SET vm.IsNearing = (CASE WHEN vm.NearingPercentage = t.Nearing THEN 1 ELSE 0 END) FROM rvlfVehicleMaintenanceService vm
		INNER JOIN #tempIsNearing t ON t.VehiclePlanId = vm.VehiclePlanId
		WHERE vm.Status = 0

		DROP TABLE #tempIsNearing

		SET NOCOUNT OFF
	END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateVehicleNearingPercentage_Old]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Procedure [dbo].[rvlf_sp_UpdateVehicleNearingPercentage_Old]
AS
/******************************************************************************/
-- Name : rvlf_sp_UpdateVehicleNearingPercentage
-- Description : To update the current Vehicle Odometer Reading & Engine Hours,
-- Nearing Percentage and IsNearing
-- Author : Kumuthini. L
-- Company : Angler Technologies
-- History : <<Date(dd-MON-yyyy)>> Initial Reason
/******************************************************************************/
	BEGIN
		SET NOCOUNT ON
		-- Select the vehicles for which the current readings, nearing (%) and IsNearing has to be calculated
		CREATE TABLE #VehTemp (VehicleId BIGINT INDEX IX2ver NONCLUSTERED)

		INSERT INTO #VehTemp (VehicleId)
		SELECT DISTINCT VehicleId FROM rvlfVehicle v
		INNER JOIN rvlfOrganizationPackage op ON op.OrganizationID = v.OrganizationId
		INNER JOIN rvlfPackageOperations po ON po.PackageId = op.PackageId
		WHERE (po.ModuleID = 29 OR v.OrganizationId = 36)
		-- 36 (Cube enabled for live testing)
		--AND v.OrganizationId NOT IN (15, 30) -- 15 (Sun Tech.) & 30 (Demo)
		AND v.OrganizationId IN (1,6,86,132)

		-- ENGINE HOURS
		-- Get the dates for the vehicles for which the manual entry is present
		CREATE TABLE #ManualTemp (OriginDateTime Date, VehicleId BIGINT INDEX IX2Manual NONCLUSTERED)

		INSERT INTO #ManualTemp (OriginDateTime, VehicleId)
		SELECT DISTINCT CONVERT(DATE, h.OriginDateTime), va.VehicleId FROM rvlfMsgInHst h
		INNER JOIN rvlfVehicleAssignment va ON va.BoxId = h.BoxId
		INNER JOIN #VehTemp vt ON vt.VehicleId = va.VehicleId
		WHERE-- h.BoxMsgInTypeId = 3 AND
		CONVERT(DATE, h.OriginDateTime) IN
		(
			SELECT CONVERT(DATE, h.OriginDateTime) FROM rvlfManualEntry me
			WHERE me.VehicleId = va.VehicleId AND
			CONVERT(DATE, h.OriginDateTime) BETWEEN me.FromDate AND me.ToDate
		)

		-- Fetch total Engine Hours for each applicable vehicles except the engine hrs present during the Manual
		-- Entry Duration
		CREATE TABLE #CalculTemp (VehicleId BIGINT INDEX IDX_CalculTemp_Vehicle NONCLUSTERED, EngineHrs BIGINT INDEX IDX_CalculTemp_EngineHrs NONCLUSTERED)

		INSERT INTO #CalculTemp (VehicleId, EngineHrs)
		Select a.VehicleId, sum(EngineHrs) from (
		SELECT v.VehicleId, EngineHrs =
		(case when vt1.VehicleTypeId in (1,2) and isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR1=',';'),0) > p.RC1
		then isnull(Datediff(HH,min(origindatetime),max(Origindatetime)),0)
		when vt1.VehicleTypeId in (3,4) and isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR1=',';'),0) > p.RC1 and isnull(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'CR2=',';'),0) > p.RC2
		then isnull(Datediff(HH,min(origindatetime),max(Origindatetime)),0)
		else 0 end)
		FROM rvlfMsgInHst h
		inner join rvlfParamRange p on h.BoxId=p.Boxid
		inner join rvlfMAKDevices md on md.BoxId=h.BoxId
		inner join rvlfVehicleType vt1 on vt1.VehicleTypeId=md.SubTypeId
		INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId
		WHERE --h.BoxMsgInTypeId = 3 AND
		(h.OriginDateTime between dateadd(MONTH,-12,GETUTCDATE()) and GETUTCDATE()) and
		CONVERT(DATE, h.OriginDateTime) NOT IN
		(SELECT mt.OriginDateTime FROM #ManualTemp mt WHERE mt.VehicleId = va.VehicleId)
		GROUP BY h.BoxId, v.VehicleId,h.CustomProp, vt1.VehicleTypeId,RC1,RC2 ) as a GROUP BY a.VehicleId

		DROP TABLE #ManualTemp

		CREATE TABLE #tempEngineHrs(VehicleId BIGINT INDEX IDX_tempEngineHrs_VehicleId NONCLUSTERED, EngineHrs BIGINT INDEX IDX_tempEngineHrs_EngineHrs NONCLUSTERED)

		INSERT INTO #tempEngineHrs(VehicleId, EngineHrs)
		select VehicleId,SUM(EngineHrs) from #CalculTemp group by VehicleId

		-- Add the Manual Entry Engine Hrs to Total Engine Hours for each applicable vehicles
		UPDATE #tempEngineHrs SET EngineHrs = ISNULL(EngineHrs,0) + (SELECT ISNULL(SUM(me.EngineHours),0) FROM rvlfManualEntry me WHERE me.VehicleId = #tempEngineHrs.VehicleId)
		--INSERT INTO #tempEngineHrs(VehicleId, EngineHrs)
		--SELECT v.VehicleId, ISNULL(SUM(CAST (SUBSTRING (CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16,
		-- CHARINDEX(';',CustomProp,CHARINDEX('SENSOR_DURATION=',CustomProp,1)) -
		-- (CHARINDEX('SENSOR_DURATION=',CustomProp,1)+16)) as int)),0) AS 'EngineHrs'
		--FROM rvlfMsgInHst h
		--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
		--INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		--INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId
		--WHERE h.BoxMsgInTypeId = 3 AND CONVERT(DATE, h.OriginDateTime) NOT IN
		-- (SELECT mt.OriginDateTime FROM #ManualTemp mt WHERE mt.VehicleId = va.VehicleId)
		--GROUP BY h.BoxId, v.VehicleId
		-- -- Add the Manual Entry Engine Hrs to Total Engine Hours for each applicable vehicles
		--UPDATE #tempEngineHrs SET EngineHrs = EngineHrs +
		--(SELECT ISNULL(SUM(me.EngineHours),0) FROM rvlfManualEntry me WHERE me.VehicleId = #tempEngineHrs.VehicleId)
		-- ODOMETER READINGS
		-- Fetch current Odometer Reading for each applicable vehicles

		CREATE TABLE #tempOdometer(VehicleId BIGINT INDEX IDX_tempOdometer_VehicleId NONCLUSTERED, OdometerReading BIGINT INDEX IDX_tempOdometer_OdometerReading NONCLUSTERED)

		INSERT INTO #tempOdometer(VehicleId, OdometerReading)
		SELECT t.VehicleId, MAX(
		--SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,
		--(CHARINDEX(';',CustomProp, CHARINDEX('Odometer=',CustomProp,1))) - (CHARINDEX('Odometer=',CustomProp,1)+9))
		ISNULL(CAST([dbo].[rvlf_fn_GetParamValueWithIndex](CustomProp,'Odometer=',';') AS INT),0)
		)
		FROM (SELECT v.VehicleId, h.BoxId, MAX(OriginDateTime) AS OriginDateTime
		FROM rvlfMsgInHst h
		INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId
		WHERE
		--h.CustomProp LIKE '%Odometer%'
		h.odometer > 0
		GROUP BY h.BoxId, v.VehicleId) t
		INNER JOIN rvlfMsgInHst hh ON hh.BoxId = t.BoxId
		WHERE hh.OriginDateTime = t.OriginDateTime AND
		--hh.CustomProp LIKE '%Odometer%'
		hh.odometer > 0
		AND BoxMsgInTypeId <> 77
		GROUP BY t.VehicleId
		-- Add the Manual Entry Kilometers Run to Odometer Reading for each applicable vehicles

		UPDATE #tempOdometer SET OdometerReading = ISNULL(OdometerReading,0) + ISNULL((SELECT ISNULL(SUM(me.Kilometers), 0) AS Kilometers FROM rvlfManualEntry me
		WHERE me.VehicleId = #tempOdometer.VehicleId
		AND me.FromDate > (SELECT CONVERT(DATE, MAX(OriginDateTime)) FROM rvlfMsgInHst h
		INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		INNER JOIN #VehTemp vt ON vt.VehicleId = v.VehicleId
		WHERE v.VehicleId = me.VehicleId
		GROUP BY v.VehicleId
		)
		GROUP BY me.VehicleId
		), 0)
		-- READINGS TABLE

		CREATE TABLE #tempReadings(VehicleId bigint INDEX IDX_tempReadings_VehicleId NONCLUSTERED, OdometerReading bigint INDEX IDX_tempReadings_OdometerReading NONCLUSTERED, EngineHrs bigint INDEX IDX_OdometerReading_EngineHrs NONCLUSTERED)

		INSERT INTO #tempReadings(VehicleId, OdometerReading, EngineHrs)
		SELECT vt.VehicleId, ISNULL(o.OdometerReading, 0), ISNULL(e.EngineHrs, 0) FROM #VehTemp vt
		LEFT OUTER JOIN #tempEngineHrs e ON e.VehicleId = vt.VehicleId
		LEFT OUTER JOIN #tempOdometer o ON o.VehicleId = vt.VehicleId

		DROP TABLE #tempEngineHrs

		DROP TABLE #tempOdometer

		-- Update the current readings in the vehicle current readings table for the selected vehicles
		UPDATE vcr SET vcr.CurrentEngineHours = (CASE WHEN ISNULL(tr.EngineHrs,0) > 0 THEN ISNULL(tr.EngineHrs,0) ELSE ISNULL(vcr.CurrentEngineHours,0) END),
		vcr.CurrentOdometerReading = (CASE WHEN ISNULL(tr.OdometerReading,0) > 0 THEN ISNULL(tr.OdometerReading,0) ELSE ISNULL(vcr.CurrentOdometerReading,0) END)
		FROM rvlfVehicleCurrentReadings vcr
		INNER JOIN #tempReadings tr ON tr.VehicleId = vcr.VehicleId

		DROP TABLE #tempReadings

		DROP TABLE #VehTemp

		-- Calculate Nearing Percentage for the selected vehicles
		CREATE TABLE #tempNearingPer(ServiceDetailsId bigint INDEX IDX_tempNearingPer_ServiceDetailsId NONCLUSTERED, Nearing int INDEX IDX_tempNearingPer_Nearing NONCLUSTERED)

		INSERT INTO #tempNearingPer(ServiceDetailsId, Nearing)
		SELECT vm.ServiceDetailsId,
		(
		(
			CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 3 THEN 
				(
					CASE WHEN mp.RecurringService = 0 THEN 
						(ISNULL(CAST(CAST((ISNULL(cr.CurrentEngineHours,0) + ISNULL(v.OpeningEngineHours * 3600, 0))as FLOAT)/ 3600 as DECIMAL(18,2)),0) * 100)
					ELSE 
						(
							CASE WHEN ((ISNULL(cr.CurrentEngineHours,0) + ISNULL(v.OpeningEngineHours, 0)) - ISNULL(vm.StatusChangeOn,0)) >= 0 THEN 
								(((ISNULL(CAST(CAST((ISNULL(cr.CurrentEngineHours,0) + ISNULL(v.OpeningEngineHours * 3600, 0)) as FLOAT)/ 3600 as DECIMAL(18,2)),0)) - ISNULL(vm.StatusChangeOn,0)) * 100) 
							ELSE 
								0 
							END
						) 
					END
				)
			WHEN vm.ServiceType = 1 THEN 
				(
					CASE WHEN mp.RecurringService = 0 THEN 
						(ISNULL(cr.CurrentOdometerReading,0) * 100)
					ELSE 
						(
							CASE WHEN (ISNULL(cr.CurrentOdometerReading,0) - ISNULL(vm.StatusChangeOn,0)) >= 0 THEN 
								((ISNULL(cr.CurrentOdometerReading,0) - ISNULL(vm.StatusChangeOn,0)) * 100) 
							ELSE 
								0 
							END
						) 
					END
				)
			WHEN vm.ServiceType = 2 THEN 
				(
					CASE WHEN (CONVERT(DATE, vm.DueOnDate) = CONVERT(DATE, GETUTCDATE()) AND mp.RecurringService = 0) THEN 
						100 
					ELSE 
						(
							CASE WHEN DATEDIFF(D, vm.StartDate, GETUTCDATE()) > 0 THEN 
								DATEDIFF(D, vm.StartDate, GETUTCDATE()) 
							ELSE 
								0 
							END
						) * 100 
					END
				) END) 
				
				/ 

				(
					CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 1 OR vm.ServiceType = 3 THEN 
						(
							CASE WHEN mp.RecurringService = 0 THEN 
								vm.DueOn 
							ELSE 
								pd.ServiceInterval 
							END
						) 
					ELSE 
						(
							CASE WHEN mp.RecurringService = 1 THEN
								(
									CASE WHEN vm.Frequency = 0 THEN 
										pd.ServiceInterval
									WHEN vm.Frequency = 1 THEN 
										(pd.ServiceInterval * 30)
									WHEN vm.Frequency = 2 THEN 
										(pd.ServiceInterval * 365) 
									END
								)
							ELSE 
								(
									CASE WHEN CONVERT(DATE, vm.DueOnDate) = CONVERT(DATE, GETUTCDATE()) THEN 
										1 
									ELSE 
										(
											CASE WHEN DATEDIFF(D, vm.StartDate, vm.DueOnDate) > 0 THEN 
												DATEDIFF(D, vm.StartDate, vm.DueOnDate) 
											ELSE 
												1 
											END
										) END
								) 
							END
						)
					END
				)
		) AS Nearing
		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 #CalculTemp vt ON vt.VehicleId = v.VehicleId
		WHERE vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1 AND v.OrganizationId IN (1,6,86,132) --AND v.OrganizationId NOT IN (15, 30)

		DROP TABLE #CalculTemp

		-- Update the calculated nearing percentage and Overdue Date

		UPDATE ms SET NearingPercentage = np.Nearing, OverdueDate = (CASE WHEN np.Nearing >= 100 AND OverdueDate IS NULL THEN GETUTCDATE() ELSE OverdueDate END),
		EngineHrsOnDue = (CASE WHEN np.Nearing >= 100 AND EngineHrsOnDue IS NULL THEN CAST(CAST((ISNULL(cr.CurrentEngineHours,0) + ISNULL(v.OpeningEngineHours * 3600, 0)) as FLOAT)/ 3600 as decimal(18,2)) ELSE EngineHrsOnDue END),
		OdometerReadingOnDue = (CASE WHEN np.Nearing >= 100 AND OdometerReadingOnDue IS NULL THEN ISNULL(cr.CurrentOdometerReading,0) ELSE ISNULL(OdometerReadingOnDue,0) END)
		FROM rvlfVehicleMaintenanceService ms
		INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = ms.VehiclePlanId
		INNER JOIN rvlfVehicleCurrentReadings cr ON cr.VehicleId = vp.VehicleId
		INNER JOIN rvlfVehicle v ON v.VehicleId = cr.VehicleId
		INNER JOIN #tempNearingPer np ON np.ServiceDetailsId = ms.ServiceDetailsId

		DROP TABLE #tempNearingPer

		-- Update IsNearing field for the plan using the calculated nearing (%)
		CREATE TABLE #tempIsNearing(VehiclePlanId bigint INDEX IDX_tempIsNearing_VehiclePlanId NONCLUSTERED, Nearing int INDEX IDX_tempIsNearing_Nearing NONCLUSTERED)

		INSERT INTO #tempIsNearing(VehiclePlanId, Nearing)
		SELECT vm.VehiclePlanId, MAX(vm.NearingPercentage) AS Nearing FROM rvlfVehicleMaintenanceService vm
		INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = vm.VehiclePlanId
		INNER JOIN rvlfMaintenancePlan mp ON mp.PlanId = vp.PlanId
		WHERE vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1
		GROUP BY vm.VehiclePlanId

		UPDATE vm SET vm.IsNearing = (CASE WHEN vm.NearingPercentage = t.Nearing THEN 1 ELSE 0 END) FROM rvlfVehicleMaintenanceService vm
		INNER JOIN #tempIsNearing t ON t.VehiclePlanId = vm.VehiclePlanId
		WHERE vm.Status = 0

		DROP TABLE #tempIsNearing

		SET NOCOUNT OFF
	END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateVehiclePlanStatus]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_sp_UpdateVehiclePlanStatus]
	
@bigVehiclePlanId bigint,
@bitStatus bit

AS
/******************************************************************************/
--	Name		:	[rvlf_sp_UpdateVehiclePlanStatus]
--	Description	:	To update the vehicle plan assignment status
--	Author		:	Kumuthini. L
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	22-Jun-2010	LK	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Local variables to hold the intermediate results
	DECLARE @ErrorMessage varchar(3000)
		 
	BEGIN TRY
		
		UPDATE rvlfVehiclePlanAssignment SET IsActive = @bitStatus WHERE VehiclePlanId = @bigVehiclePlanId
		
	END TRY
	BEGIN CATCH
		SET @ErrorMessage = 'An Error occured during updation of vehicle plan assignment status : ' +ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateWeather_BgProcessTest]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_UpdateWeather_BgProcessTest]                        
(                                              
 @TableXML XML = NULL,
 @TableName varchar(20)=  NULL
)                
AS                                              
/***********************************************************************************************/                                              
-- Name  : rvlf_sp_UpdateWeather_BgProcessTest
-- Description : To get update the street address from the background process                                              
-- Author  : T. Sathish Kumar                                              
-- Company  : Angler Technologies                                              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                                                                                                                 
/***********************************************************************************************/                                              
BEGIN                                              
                                              
-- SET TRANSACTION ISOLATION LEVEL READ COMMITTED;        
                                                     
--DECLARE @bigOrganizationID bigint,@IntBoxid int=null,@landmarkID bigint        
        
DECLARE @tiBoxMsgInTypeId tinyint        
DECLARE @ErrorMessage varchar(200)        
                                             
BEGIN TRY
        
/*****************************************************************************************************/                            
/**********************************Insert the Xml data to a TempTable ********************************/                
/*****************************************************************************************************/                            
        
DECLARE @TemptblMaster TABLE            
( 
	Boxid BIGINT,                        
	WeatherInfo VARCHAR(MAX)                    
)              
                                
DECLARE @MapProvider AS INT                          
DECLARE @RowCount As BIGINT          
                
DECLARE @tblName varchar(30) = '/NewDataSet/TableNew'                   
SET @tblName = '/NewDataSet/' + @TableName                   
                                    
DECLARE @Index AS INT;                    
SET @Index = 0;                                    
EXEC Sp_xml_preparedocument  @Index OUTPUT,@TableXML                                      
                    
INSERT INTO @TemptblMaster(BoxId,WeatherInfo)           
SELECT SA.BoxId,              
       SA.WeatherInfo
FROM   OPENXML (@Index, @tblName)              
       WITH (BoxId			INT 'BoxId',                              
             WeatherInfo	VARCHAR(MAX) 'WeatherInfo') SA           
             INNER JOIN rvlfBoxId AS B ON SA.BoxId = B.BoxId

UPDATE BX         
SET    BX.WeatherInfo = SA.WeatherInfo
FROM   [DBO].[rvlfBoxID] AS BX WITH (nolock)              
INNER JOIN @TemptblMaster AS SA ON BX.BoxId = SA.Boxid

SELECT @RowCount = @@ROWCOUNT
SELECT @RowCount
                                               
END TRY                                              
BEGIN CATCH                                              
  -- ROLLBACK TRAN                                              
   SET @ErrorMessage = 'An Error occured during updating Weather info in background process : ' + ERROR_MESSAGE()                     
   RAISERROR( @ErrorMessage,16,1)                                           
END CATCH                  
                                              
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UploadServiceDocuments]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlf_sp_UploadServiceDocuments] 
	
	@ServiceID bigint=null,
	@Serviceimage1 nvarchar(Max)=null,
	@Serviceimage2 nvarchar(Max)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    update rvlfAdhocServices set Photo1=@Serviceimage1,Photo2=@Serviceimage2 where AdhocServiceId=@ServiceID
END


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_VehStatistics]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create proc [dbo].[rvlf_sp_VehStatistics]
(@bigQueryingUser bigint, 
@bigOrganizationID bigint)
as
--rvlf_sp_VehStatistics 
begin
select count(distinct(fv.VehicleId)) as 'No of Vehicles' from rvlfFleetUsers FU  inner join rvlfFleetVehicles fv                
 on fv.FleetId = FU.FleetId inner join rvlfFleet f on f.FleetId = fv.FleetId                 
 inner join rvlfVehicleAssignment VA on VA.VehicleId = FV.VehicleId                
 where FU.UserId= @bigQueryingUser and f.OrganizationId =@bigOrganizationID                
                 
;WITH cteVehicleStatus AS                 
(SELECT DISTINCT(b.BoxId),b.LastSensorMask,b.LastSpeed                
FROM rvlfBoxId b INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId                
INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = va.VehicleId                
INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId INNER JOIN rvlfFleetUsers fu ON fu.FleetId=f.FleetId                
INNER JOIN rvlfUser u ON u.UserId = fu.UserId WHERE u.OrganizationId = @bigOrganizationID and u.UserId=@bigQueryingUser)                 
SELECT isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0 THEN 1 ELSE 0 END),0) as Moving,                 
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN 1 ELSE 0 END),0) as Idling,                 
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =0 THEN 1 ELSE 0 END),0) as Parked  FROM cteVehicleStatus    
end


GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_ViewPackageDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE PROCEDURE [dbo].[rvlf_sp_ViewPackageDetails]  
 @bigPackageID bigint=NULL  
AS  
/******************************************************************************/  
-- Name  : rvlf_sp_ViewPackageDetails  8
-- Description : To get the Package details  
--    :   Pass the values to @bigEmployeeID   
-- Author  : V. Narayanasamy.  
-- Company  : Angler Technologies  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
--    : 27-Nov-2009 VN Created Intial Version   
/******************************************************************************/  
  
BEGIN  
  
 SELECT p.PackageId,p.PackageName,ModuleID ,ModuleDesc,OperationDesc,ModuleName,OperationTypeName    
  FROM(SELECT po.PackageId, m.ModuleID,m.ModuleDesc,m.ModuleName,op.OperationTypeName,op.OperationTypeId,op.OperationDesc    
    FROM rvlfPackageOperations po  
     INNER JOIN rvlfModule m ON m.ModuleID=po.ModuleID   
     INNER JOIN rvlfOperationType op ON op.OperationTypeId=po.OperationID AND m.ModuleID=op.ModuleID   
    WHERE (@bigPackageID IS NULL OR @bigPackageID = '' OR po.PackageId =@bigPackageID) and m.ModuleDesc != 'Temp')AS A  
  RIGHT OUTER JOIN rvlfPackage p ON p.PackageId=A.PackageId    
  WHERE (@bigPackageID IS NULL OR p.PackageId=@bigPackageID)  
END  






GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_VORDetails]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    
CREATE PROC [dbo].[rvlf_sp_VORDetails]    
(    
@Vno BIGINT=null,    
@FleetId BIGINT=null,    
@VehicleId BIGINT=null,    
@DateFrom DATETIME=null,    
@DateTo DATETIME=null,    
@RefDoc VARCHAR(50)=null,    
@AdditionalInfo VARCHAR(500)=null,    
@Reason VARCHAR(1000)=null,    
@bigOrganizationId BIGINT=null,    
@bigUserId BIGINT=null,    
@Operation CHAR(1)='S'    
)    
AS     
/******************************************************************************/                                              
-- Name  : rvlf_sp_VORDetails    
-- Description : Get and modify the VOR details    
-- Author  : Gopal.R      
-- Company  : Angler Technologies      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason      
--Created Date -11-jun-2015    
/******************************************************************************/      
BEGIN    
IF(@operation='S')    
BEGIN    
SELECT VOR.Vno,VOR.FleetId,F.FleetName,VOR.VehicleId,V.VehicleDescription,
--VOR.DateFrom,VOR.DateTo,
CONVERT (varchar(11),VOR.DateFrom,106) as DateFrom,              
  CONVERT (varchar(11),VOR.DateTo,106) as DateTo,              
VOR.RefDoc,VOR.AdditionalInfo,VOR.Reason    
FROM  rvlfVORDetails as VOR     
inner join rvlfFleet F on VOR.FleetId=f.FleetId    
inner join rvlfVehicle V on VOR.VehicleId=V.VehicleId    
WHERE (@Vno is null or @Vno =0 or Vno=@Vno) and (VOR.OrganizationId=@bigOrganizationId)    
END    
IF(@operation='I')    
BEGIN    
INSERT INTO rvlfVORDetails (FleetId,VehicleId,DateFrom,DateTo,RefDoc,AdditionalInfo,Reason,OrganizationId,CreatedBy,CreatedDateTime,    
ModifiedBy,Modified) VALUES (@FleetId,@VehicleId,@DateFrom,@DateTo,@RefDoc,@AdditionalInfo,@Reason,@bigOrganizationId,@bigUserId,GETUTCDATE(),    
@BigUserID,GETUTCDATE())    
END    
IF(@operation='U')    
BEGIN    
UPDATE rvlfVORDetails SET FleetId=@FleetId ,VehicleId=@VehicleId,DateFrom=@DateFrom,DateTo=@DateTo,RefDoc=@RefDoc,    
AdditionalInfo=@AdditionalInfo,Reason=@Reason,OrganizationId=@bigOrganizationId,ModifiedBy=@bigUserId,Modified=GETUTCDATE()    
 where Vno=@Vno    
END    
IF(@operation='D')    
BEGIN    
DELETE FROM rvlfVORDetails WHERE Vno=@Vno    
END    
END

 

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_WOEmailAttachment]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Anbarasu.E
-- Create date: 28-Dec-2015
-- Description:	For WO Email Attachemnt
--				rvlf_sp_WOEmailAttachment 219,6,1005
-- =============================================
CREATE PROCEDURE [dbo].[rvlf_sp_WOEmailAttachment]
	-- Add the parameters for the stored procedure here
	@bigUserId			bigint = NULL, 
	@bigOrganizationId	bigint = NULL,
	@bigWONo			bigint = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DECLARE @HoursToBeAdded INT = 0         
	DECLARE @MinsToBeAdded INT = 0                        
	DECLARE @DefaultDateFormat INT = 0           

    SELECT	@HoursToBeAdded = tz.HoursToBeAdded, @MinsToBeAdded = tz.MinToBeAdded,
			@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 = @bigUserId
	INNER	JOIN rvlfUser u			ON	u.UserId = up.UserId        
		
	Declare @WOStatus	tinyint
	Declare @AssignedTo nvarchar(100)
	Declare @ToAddress	nvarchar(100)
	
	Select	@WOStatus=Status From rvlfWOGeneration Where WONo = @bigWONo and IsDelete = 0

	IF @WOStatus = 1
	BEGIN
		SELECT @AssignedTo=DisplayName, @ToAddress=Email FROM rvlfUser Where UserId = 
		(SELECT AssignedTo From rvlfWOGeneration Where WONo = @bigWONo and IsDelete = 0)
	END	
	ELSE IF @WOStatus = 2
	BEGIN
		SELECT @AssignedTo=DisplayName, @ToAddress=Email FROM rvlfUser Where UserId = 
		(SELECT TOP 1 AssignedTo From rvlfWOApproval Where WONo = @bigWONo ORDER BY WOApprovalId DESC)
	END
	ELSE
	BEGIN		
		SELECT @AssignedTo=DisplayName, @ToAddress=Email FROM rvlfUser Where UserId = 
		(SELECT CreatedBy From rvlfWOGeneration Where WONo = @bigWONo and IsDelete = 0)		
	END
	--select @WOStatus,@AssignedTo,@ToAddress
	Select	WOGenId, WONo,(Case when  WOTypeId = 1	then 'Preventive Maintenance'	when  WOTypeId = 2  then 'Regular Maintenance'	 
								when  WOTypeId = 3	then 'Corrective maintenance'	when  WOTypeId = 4  then 'Predictive Maintenance'	 
								when  WOTypeId = 5	then 'Periodic maintenance'		when  WOTypeId = 6  then 'Zero Hours Maintenance'	
								when  WOTypeId = 7	then 'Others' end) as WOType, v.VehicleDescription, TVM.VendorName,
			(Case	when  WOG.WarrantyorContract = 1 then 'Basic (bumper-to-bumper)' when  WOG.WarrantyorContract = 2  then 'Powertrain'	 
					when  WOG.WarrantyorContract = 3 then 'Corrosion'				 when  WOG.WarrantyorContract = 4  then 'Roadside assistance'	 
					when  WOG.WarrantyorContract = 5 then 'Not under warranty'		 when  WOG.WarrantyorContract = 6  then 'Others' end) as WarrantyType,  
			Replace(convert(varchar,WarrantyEndDate,106),' ','-')  as WarrantyEndDate, 
			Replace(convert(varchar,StartDate,106),' ','-')  + ' & ' + Replace(convert(varchar,EDC,106),' ','-') as StartandEDC, 
			Case when WOG.Status = 1 then 'Generated'	when WOG.Status = 2 then 'Approved'		when WOG.Status = 3 then 'Redo'   
				 when WOG.Status = 4 then 'Rejected'	when WOG.Status = 5 then 'Closed'		when WOG.Status = 6 then 'Reopened'  
				 else '-'   end as WOStatus,
			/* U.DisplayName as AssignedTo, U.Email as ToAddress, */ @AssignedTo as AssignedTo, @ToAddress as ToAddress,
			Remarks, VPA.VehiclePlanId, mp.PlanName, ms.ServiceName, 
			dbo.rvlf_fn_GetMaintenanceServiceCategories(ms.ServiceId) as ServiceCategory,
			mps.PlannedCost, mp.TotalPlannedCost, U1.DisplayName as GeneratedBy, U1.Email as ccAddress, 
			Convert(varchar,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,WOG.CreatedDatetime)),@DefaultDateFormat)
			+ ' '+ Convert(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,WOG.CreatedDatetime)) as time),22) as GeneratedDate
		    --REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(17, WOG.WONo, 1,0,0),''),';',',') as EmailList,
		    --REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(17, WOG.WONo, 1,1,0),''),';',',') as UserNameList
	From	rvlfWOGeneration WOG
	Inner	Join rvlfVehiclePlanAssignment VPA On WOG.VehiclePlanId = VPA.VehiclePlanId
	Inner	Join rvlfMaintenancePlan mp On VPA.PlanId = mp.PlanId
	--Inner	Join rvlfMaintenancePlanDetails mpd On mp.PlanId = mpd.PlanId
	Inner	Join rvlfMaintenancePlanServices mps On mp.PlanId = mps.PlanId
	Inner	Join rvlfMaintenanceService ms On mps.ServiceId = ms.ServiceId
	--Right Join rvlfMaintenanceServiceDetails msd On mps.ServiceId = msd.ServiceId
	--Inner	Join rvlfMaintenanceServiceCategory msc On ms.ServiceCategoryId = msc.ServiceCategoryId
	Inner	Join rvlfVehicle v On VPA.VehicleId = v.VehicleId
	Inner	Join rvlfTyreVendorMaster TVM on TVM.VendorId = WOG.VendorId
	--Left	Join rvlfUser	U	On WOG.AssignedTo = U.UserId 
	Left	Join rvlfUser	U1	On WOG.CreatedBY = U1.UserId 
	Where	(@bigWONo IS NULL or @bigWONo = '' or WOG.WONo = @bigWONo)
	and		WOG.OrganizationId = @bigOrganizationId
	and		WOG.IsDelete = 0
END

GO
/****** Object:  StoredProcedure [dbo].[rvlf_UpdateNotifications]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[rvlf_UpdateNotifications]
	@uiMessageInID uniqueidentifier
AS
/******************************************************************************/
--	Name		:	rvlf_UpdateNotifications
--	Description	:	To update related to the notifications sent
--	Author		:	M. Jebamalai Jaya Chitra.
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	06-Jun-2009	MJJC	Created Intial Version 
/******************************************************************************/
BEGIN
SET NOCOUNT ON 
	-- Declares the required variables to hold the intermediate results.
	DECLARE @ErrorMessage varchar(200)
	
	IF EXISTS ( SELECT MessageInID FROM rvlfMsgInHst WHERE MessageInID = @uiMessageInID)
	BEGIN
		BEGIN TRAN Update_Notifications
		BEGIN TRY
			UPDATE rvlfMsgInHst SET IsNotificationSent = 1 WHERE MessageInID = @uiMessageInID
			COMMIT TRAN
		END TRY
	BEGIN CATCH
		ROLLBACK TRAN 
		SET @ErrorMessage = 'An Error occured during updating notifiations : ' + ERROR_MESSAGE()
		RAISERROR( @ErrorMessage,16,1)
	END CATCH
	END

	ELSE
	BEGIN
		SET @ErrorMessage = 'No such message exists : ' + CAST(@uiMessageInID as varchar(36))
		RAISERROR( @ErrorMessage,16,1)
	END

SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[rvlfAutomateReportScheduleEx]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE proc [dbo].[rvlfAutomateReportScheduleEx]          
(          
@OrgId bigint=null,          
@ReportID int = null,          
@SchedulUser varchar(300)=null,          
@WeekDay tinyint=null           
)          
as          
/******************************************************************************/                                                    
-- Name  : rvlfAutomateReportScheduleEx            
-- Description : Create Automatic schedule for the reports          
-- Author  : Gopal.R            
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--Created Date -08-May-2015          
--@weekday = 1 generate on tuesday if 5 then saturday based on the utc              
/******************************************************************************/            
begin          
declare @Scheduleid bigint,@userid tinyint=0            
Declare @date1 datetime='2015-05-06 19:30:00.000'          
set @date1 = DATEADD(day,DATEDIFF(day,@date1,getutcdate()),@date1)          
 Declare @date datetime =null
IF(@ReportID=3)  --alarm           
BEGIN        
 set @Scheduleid=(select top 1 ReportScheduleId from rvlfSchedulingReport where ReportTypesId=3 and CreatedBy=0 and IsScheduled=1)    
 if (@Scheduleid is null or @Scheduleid=0)    
 begin      
  set @date = dateadd(MINUTE,10,DATEADD(day,DATEDIFF(day,@date1,getutcdate()),@date1))      
  INSERT into rvlfSchedulingReport        
  select OrganizationId,3,FleetId,0,GETUTCDATE(),null,'1900-01-01 19:30:00.000','1900-01-01 19:30:00.000','1900-01-01 19:40:00.000', 
  DATEADD(day,-7,dateadd(dd,-datediff(dd,6+@WeekDay,@date1)%7+7,@date1)),          
  dateadd(dd,-datediff(dd,6+@WeekDay,@date1)%7+7,@date1),          
  dateadd(dd,-datediff(dd,6+@WeekDay,@date)%7+7,@date),1,1,'','VehicleID:0','VehicleDescription',0,0,1,0,          
  null,1,GETUTCDATE(),@userid,GETUTCDATE(),@userid,0,7,6,7,0,null,1 from rvlfFleet f where OrganizationId =@OrgId and FleetName='ALL'    
  set @Scheduleid=IDENT_CURRENT('rvlfSchedulingReport')          
 end    
 INSERT into rvlfNotificationList        
 select u.UserId,5,@Scheduleid,1,null,getutcdate() from rvlfUserGroupAssignment uga inner join rvlfUserGroup ug on uga.UserGroupId=ug.UserGroupId          
 inner join rvlfUser u on uga.UserId=u.UserId          
 where UserGroupName = 'Security Admin' and ug.OrganizationId =@OrgId and u.IsActive=1 and IsLocked=0 and u.IsDelete=0 and        
 (@SchedulUser is null  or u.UserId in (SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@SchedulUser,',')) )      
 if (@SchedulUser is not null) begin set @ReportID=36 set @WeekDay=5  end    
END          
If(@ReportID=36)  --Daily trip         
Begin      
 set @Scheduleid=(select top 1 ReportScheduleId from rvlfSchedulingReport where ReportTypesId=36 and CreatedBy=0 and IsScheduled=1)    
 if (@Scheduleid is null or @Scheduleid=0)        
 begin          
  set @date = dateadd(HOUR,1,DATEADD(day,DATEDIFF(day,@date1,getutcdate()),@date1))      
  INSERT into rvlfSchedulingReport          
  select OrganizationId,36,FleetId,0,GETUTCDATE(),null,'1900-01-01 19:30:00.000','1900-01-01 19:30:00.000','1900-01-01 20:30:00.000', 
  DATEADD(day,-7,dateadd(dd,-datediff(dd,6+@WeekDay,@date1)%7+7,@date1)),          
  dateadd(dd,-datediff(dd,6+@WeekDay,@date1)%7+7,@date1),          
  dateadd(dd,-datediff(dd,6+@WeekDay,@date)%7+7,@date),1,1,'','VehicleID:0','VehicleDescription',0,0,1,0,          
  null,1,GETUTCDATE(),@userid,GETUTCDATE(),@userid,0,7,6,7,0,null,1 from rvlfFleet f where OrganizationId =@OrgId and FleetName='ALL'          
  set @Scheduleid=IDENT_CURRENT('rvlfSchedulingReport')          
 End    
 INSERT into rvlfNotificationList          
 select u.UserId,5,@Scheduleid,1,null,getutcdate() from rvlfUserGroupAssignment uga inner join rvlfUserGroup ug on uga.UserGroupId=ug.UserGroupId 
 inner join rvlfUser u on uga.UserId=u.UserId          
 where UserGroupName = 'Security Admin' and ug.OrganizationId =@OrgId and u.IsActive=1 and IsLocked=0 and u.IsDelete=0 and        
 (@SchedulUser is null or u.UserId in(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@SchedulUser,',')) )    
 if (@SchedulUser is not null ) begin set @ReportID=26  set @WeekDay=5 end                
End      
If(@ReportID=26)    --Weekly fleet     
Begin      
 set @Scheduleid=(select top 1 ReportScheduleId from rvlfSchedulingReport where ReportTypesId=26 and CreatedBy=0 and IsScheduled=1)    
 if (@Scheduleid is null or @Scheduleid=0)        
 begin      
  set @date = dateadd(HOUR,2,DATEADD(day,DATEDIFF(day,@date1,getutcdate()),@date1))       
  INSERT into rvlfSchedulingReport          
  select OrganizationId,26,FleetId,0,GETUTCDATE(),null,'1900-01-01 19:30:00.000','1900-01-01 19:30:00.000','1900-01-01 21:30:00.000', 
  DATEADD(day,-7,dateadd(dd,-datediff(dd,6+@WeekDay,@date1)%7+7,@date1)),          
  dateadd(dd,-datediff(dd,6+@WeekDay,@date1)%7+7,@date1),          
  dateadd(dd,-datediff(dd,6+@WeekDay,@date)%7+7,@date),1,1,'','','Username',0,0,1,0,          
  null,1,GETUTCDATE(),@userid,GETUTCDATE(),@userid,0,7,6,7,0,null,1 from rvlfFleet f where OrganizationId =@OrgId and FleetName='ALL'          
  set @Scheduleid=IDENT_CURRENT('rvlfSchedulingReport')       
 End       
 INSERT into rvlfNotificationList          
 select u.UserId,5,@Scheduleid,1,null,getutcdate() from rvlfUserGroupAssignment uga inner join rvlfUserGroup ug on uga.UserGroupId=ug.UserGroupId          
 inner join rvlfUser u on uga.UserId=u.UserId          
 where UserGroupName = 'Security Admin' and ug.OrganizationId =@OrgId and u.IsActive=1 and IsLocked=0 and u.IsDelete=0 and        
 (@SchedulUser is null or u.UserId in(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@SchedulUser,',')) )     
 if (@SchedulUser is not null) begin set @ReportID=29 set @WeekDay=1 end    
End          
If (@ReportID=29) --fleet idling         
Begin       
 set @Scheduleid=(select top 1 ReportScheduleId from rvlfSchedulingReport where ReportTypesId=29 and CreatedBy=0 and IsScheduled=1)    
 if (@Scheduleid is null or @Scheduleid=0)        
 begin    
  set @date = dateadd(MINUTE,30,DATEADD(day,DATEDIFF(day,@date1,getutcdate()),@date1))        
  INSERT into rvlfSchedulingReport          
  select OrganizationId,29,FleetId,0,GETUTCDATE(),null,'1900-01-01 19:30:00.000','1900-01-01 19:30:00.000','1900-01-01 20:00:00.000',         DATEADD(day,-7,dateadd(dd,-datediff(dd,6+@WeekDay,@date1)%7+7,@date1)),          
  dateadd(dd,-datediff(dd,6+@WeekDay,@date1)%7+7,@date1),          
  dateadd(dd,-datediff(dd,6+@WeekDay,@date)%7+7,@date),1,1,'','','VehicleDescription',0,0,1,0,          
  null,1,GETUTCDATE(),@userid,GETUTCDATE(),@userid,0,3,2,3,0,null,1 from rvlfFleet f where OrganizationId =@OrgId and FleetName='ALL'          
  set @Scheduleid=IDENT_CURRENT('rvlfSchedulingReport')          
 end    
 INSERT into rvlfNotificationList          
 select u.UserId,5,@Scheduleid,1,null,getutcdate() from rvlfUserGroupAssignment uga inner join rvlfUserGroup ug on uga.UserGroupId=ug.UserGroupId 
 inner join rvlfUser u on uga.UserId=u.UserId          
 where UserGroupName = 'Security Admin' and ug.OrganizationId =@OrgId and u.IsActive=1 and IsLocked=0 and u.IsDelete=0 and        
 (@SchedulUser is null or u.UserId in(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@SchedulUser,',')))   
 if (@SchedulUser is not null)begin set @ReportID=39 set @WeekDay=1 end            
End          
If(@ReportID=39)  --Portal Usage         
Begin        
 set @Scheduleid=(select top 1 ReportScheduleId from rvlfSchedulingReport where ReportTypesId=39 and CreatedBy=0 and IsScheduled=1)    
 if (@Scheduleid is null or @Scheduleid=0)        
 begin    
  set @date = dateadd(MINUTE,90,DATEADD(day,DATEDIFF(day,@date1,getutcdate()),@date1))       
  INSERT into rvlfSchedulingReport          
  select OrganizationId,39,FleetId,0,GETUTCDATE(),null,'1900-01-01 19:30:00.000','1900-01-01 19:30:00.000','1900-01-01 21:00:00.000', 
  DATEADD(day,-7,dateadd(dd,-datediff(dd,6+@WeekDay,@date1)%7+7,@date1)),          
  dateadd(dd,-datediff(dd,6+@WeekDay,@date1)%7+7,@date1),          
  dateadd(dd,-datediff(dd,6+@WeekDay,@date)%7+7,@date),1,1,'','','Username',0,0,1,0,          
  null,1,GETUTCDATE(),@userid,GETUTCDATE(),@userid,0,3,2,3,0,null,1 from rvlfFleet f where OrganizationId =@OrgId and FleetName='ALL'          
  set @Scheduleid=IDENT_CURRENT('rvlfSchedulingReport')          
 end    
 Insert into rvlfNotificationList          
 select u.UserId,5,@Scheduleid,1,null,getutcdate() from rvlfUserGroupAssignment uga inner join rvlfUserGroup ug on uga.UserGroupId=ug.UserGroupId 
 inner join rvlfUser u on uga.UserId=u.UserId          
 where UserGroupName = 'Security Admin' and ug.OrganizationId =@OrgId and u.IsActive=1 and IsLocked=0 and u.IsDelete=0 and        
 (@SchedulUser is null or u.UserId in(SELECT * FROM dbo.rvlf_fn_ConvertArrayToTable(@SchedulUser,',')))  
End          
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlfDashboard_ADOR]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rvlfDashboard_ADOR]
(
@bigOrganizationID bigint,
@bigFleetID bigint = null,
@dtStartDate datetime,
@dtEndDate datetime,
@bigQueryingUser bigint,
@bigVehicleTypeID bigint = null,
@bigVehicleID bigint = null,
@CustomerID bigint = null
)
AS
/******************************************************************************/
-- Name : rvlfDashboard_ADOR 132,null,'27-feb-19','28-feb-19',578,0,null,null
-- Description : To get the organization statistics.
-- Author : V.Narayanasamy
-- Company : Angler Technologies
-- History : <<Date(dd-MON-yyyy)>> Initial Reason
-- : 12-May-2011 VN Altered the running and idling logic
/******************************************************************************/
	BEGIN
		Declare @bigOrganizationID1 bigint=@bigOrganizationID,
		@bigFleetID1 bigint = @bigFleetID,
		@dtStartDate1 datetime=@dtStartDate,
		@dtEndDate1 datetime=@dtEndDate,
		@bigQueryingUser1 bigint=@bigQueryingUser,
		@bigVehicleTypeID1 bigint = @bigVehicleTypeID,
		@bigVehicleID1 bigint = @bigVehicleID

		DECLARE @HoursToBeAdded INT = 0
		DECLARE @MinsToBeAdded INT = 0
		DECLARE @ConversionFactor numeric (10,2) = 1.0
		DECLARE @CaptionPrefix varchar(10)
		DECLARE @DefaultDateFormat INT = 0
		DECLARE @VarUserPreferedChart varchar(max) = null
		Declare @bigTopNos bigint = 10
		DECLARE @Distance varchar(20)

		SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded, @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END , @CaptionPrefix = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'kms' END, @Distance = CASE WHEN up.Distance



 = 0 THEN 'miles' ELSE 'km' END, @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 = @bigQueryingUser1

		SELECT @VarUserPreferedChart = ISNULL(UserPreferedChart,'1,3,5,373,287') from rvlfUserPreferences WHERE UserId = @bigQueryingUser1
		--IF @bigFleetID1 IS NULL
		--	SELECT @bigFleetID1 = FleetID FROM rvlfFleet where OrganizationId = @bigOrganizationID1 and IsDefault=1
		/***************** Organization Statistics ******************************************************************/
		declare @IsAngAdmin int
		select @IsAngAdmin =(case when UserGroupId = 1 then 1 else 0 end) from rvlfUserGroupAssignment where UserId= @bigQueryingUser1
		select null as 'No of Vehicles'
		select null as Moving,null as Idling,null as Parked
		DECLARE @tblDashboardChartIndex table
		(
			ChartIndex int
		)
		insert into @tblDashboardChartIndex
		select * from rvlf_fn_ConvertArrayToTable(@VarUserPreferedChart,',')
		/********************* Alarms *******************************************************************************/
		if Exists(select * from @tblDashboardChartIndex where ChartIndex =1)
			begin
				Declare @TempAlarm as Table(
				AlarmTID INT IDENTITY(1, 1),
				VehicleTypeName varchar(500),
				VehicleDescription varchar(1000),
				AlarmLevelId BIGINT,
				ControllerID Bigint,
				Boxid varchar(15)
				)
				Insert into @TempAlarm
				Select Distinct vt.VehicleTypeName,Vi.VehicleDescription,a.AlarmLevelId, a.ControllerID,a.BoxId from rvlfAlarmTransaction a
				Inner Join rvlfalarm a1 on a.AlarmId=a1.AlarmId
				inner join rvlfVehicleAssignment v on v.BoxId=a.BoxId inner join rvlfVehicle vi on vi.VehicleId =v.VehicleId
				INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId inner join rvlfBoxMsgInType mt on a.AlarmType=mt.BoxMsgInTypeId
				inner join rvlfVehicleType vt on vt.VehicleTypeId =vi.VehicleTypeId
				inner join rvlfMAKDevices MK on a1.BoxId=mk.BoxId
				where (vi.OrganizationId = @bigOrganizationID) AND (@CustomerID is null or @CustomerID = '' or @CustomerID=0 or mk.CustomerId=@CustomerID) and 
				(@bigFleetID1 is null or @bigFleetID1 = '' or @bigFleetID1=0 or fv.FleetId = @bigFleetID1) and
				a.AlarmLevelId in(2,1,3) and a.AlarmType = mt.BoxMsgInTypeId and isnull(a1.IsClosed,0) <> 1 order by VehicleTypeName
				select 1 as CriticalAlarms,0 as VehicleTypeId,0 as VehicleTypeName, 0 as NoofAlarmsCritical,0 as NoofAlarmsWarning1,0 as NoofAlarmsWarning2, 0 as TotalCount,
				1 as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+
				Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,'Alarms' -- from @TempAlarm
				Where 1 = 2 
			end
		else
			begin
				select Null as CriticalAlarms,Null as BoxId,Null as VehicleDescription,Null as VehicleName, Null as PasGenerateddate,Null as DriverDetails,'Alarms' Where 1 = 2
			end
		--/********************* Productwise ********************/
		DECLARE @tblmsgsDeviceType table
		(
		VehicleName varchar(200),
		VehicleTypeId bigint,
		VehicleTypeName varchar(200),
		FleetName varchar(200),
		TotalCount Bigint,
		OnlineCount Bigint,
		OfflineCount Bigint,
		StatusType varchar(50),
		LastStatusDateTime datetime,
		ControllerId Bigint
		)
		insert into @tblmsgsDeviceType
		select distinct v.Vehicledescription as VehicleName, 1 as VehicleTypeId, 1 as VehicleTypeName,0 as SiteName,0 as TotalCount, 0 as OnlineCount,
		0 as OfflineCount,(Case when DATEDIFF(MINUTE,B.LastStatusDateTime,GETUTCDATE()) > ((cast(isnull(v.RptInterval,900) as int)/60)*3)  then 'Offline' ELSE 'Online' end)  as StatusType,
		b.LastStatusDateTime,b.ControllerId
		from rvlfBoxId b
		inner join rvlfVehicleAssignment va on va.BoxId =b.BoxId
		inner join rvlfVehicle v on v.VehicleId =va.VehicleId
		inner join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId
		inner join rvlffleet f on f.FleetId=fv.Fleetid
		--inner join rvlfVehicleType vt on vt.VehicleTypeId =v.VehicleTypeId
		inner join rvlfMAKDevices md on md.VehicleId=v.VehicleId
		where b.OrganizationId= @bigOrganizationID1 and  (@bigFleetID1 is null or @bigFleetID1 = '' or @bigFleetID1=0 or fv.FleetId = @bigFleetID1)  
		--AND (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR v.VehicleTypeId = @bigVehicleTypeID1)
		--AND (@bigVehicleID1 IS NULL OR @bigVehicleID1='' OR v.VehicleId = @bigVehicleID1)
		And (md.IsDelete = 0) AND (@CustomerID is null or @CustomerID = '' or @CustomerID=0 or md.CustomerId=@CustomerID) 
		Declare @Oncount Bigint = 0,@Offcount bigint = 0
		Select distinct VehicleName, VehicleTypeId, VehicleTypeName,FleetName as SiteName,@Oncount as OnlineCount,
		@Offcount as OfflineCount,TotalCount = @Oncount + @Offcount,StatusType,
		Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22)
		as PasGenerateddate,ControllerId,'Productwise'
		from @tblmsgsDeviceType
		------------***************************Equipment Usage********************************************--/
		select null as EQUsageColumn,
		null as EQUsageColumnVal,
		null as RunningHours,
		null as PasGenerateddate,null as Spliter,null as DataOrder,null as VehicleTypeID,null as VehicleTypeName,
		null as GridSeparator
		where 1= 2
		--where SeparatorValue > 0
		/***************** Maintenance ****************************************************************/
		select null as VehicleTypeID,null as VehicleTypeName, null as LowCount,null as MediumCount,null as HighCount,null as HighAboveCount,null as TotalCount,
		null as PasGenerateddate where 1 = 2
		/***************** Get login active users ****************************************************************/
		SELECT COUNT(UserId)AS ActiveUsers
		FROM rvlfUserLogin
		WHERE CONVERT(DATE,LoginDateTime)=CONVERT(DATE,GETUTCDATE()) AND LogOffDateTime IS NULL
		UNION ALL
		SELECT COUNT(UserId) AS InternalUsers
		FROM rvlfUserLogin UL
		WHERE CONVERT(DATE,LoginDateTime)=CONVERT(DATE,GETUTCDATE()) AND LogOffDateTime IS NULL AND OrgId IN(1,6)
		/***************** Get User Prefered Chart****************************************************************/
		DECLARE @List as varchar(max)
		DECLARE @ISExport int
		SELECT @ISExport = ug.OperationTypeId from rvlfOperationType op
		INNER JOIN rvlfUserGroupSecurity ug on ug.OperationTypeId = op.OperationTypeId
		INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId
		INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId
		INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId
		INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId
		INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId
		WHERE ga.UserId = @bigQueryingUser1 and ug.ModuleId = 1 and ug.OperationTypeId not in (1,3,286,287)
		--SELECT distinct(case when @ISExport is not null or @ISExport = '' then @VarUserPreferedChart + ',5' else @VarUserPreferedChart end)
		DECLARE @tblmsgs table
		(
			OperationTypeId varchar(100),
			Export Bigint
		)
		insert into @tblmsgs(OperationTypeId,Export)
		select distinct(ug.OperationTypeId), Export = case when ug.OperationTypeId in (1,3,5,286,287) Then '5' END from rvlfOperationType op
		INNER JOIN rvlfUserGroupSecurity ug on ug.OperationTypeId = op.OperationTypeId
		INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId
		INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId
		INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId
		INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId
		INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId
		where ga.UserId = @bigQueryingUser1 and ug.ModuleId = 1 order by ug.OperationTypeId desc

		SELECT @List = case WHEN @ISExport is not null THEN COALESCE(@List + ',','5,') + cast(OperationTypeId as varchar(25)) ELSE COALESCE(@List + ',','') + cast(OperationTypeId as varchar(25)) END from @tblmsgs where OperationTypeId in
		(SELECT * FROM rvlf_fn_ConvertArrayToTable(@VarUserPreferedChart, ','))

		select @VarUserPreferedChart=''
		select @VarUserPreferedChart = @VarUserPreferedChart + cast(DI.ChartIndex as nvarchar(100)) + ','  from @tblDashboardChartIndex DI
		inner join rvlfOperationType op on DI.ChartIndex=op.OperationTypeId
		INNER JOIN rvlfUserGroupSecurity ug on ug.OperationTypeId = op.OperationTypeId
		INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId
		INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId
		INNER JOIN rvlfUser ur on ur.UserId=ga.UserId and ur.OrganizationId = u.OrganizationId
		INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId
		INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId where ga.UserId = @bigQueryingUser1  and ur.OrganizationId=@bigOrganizationID1

		select @VarUserPreferedChart=SUBSTRING(@VarUserPreferedChart, 0, LEN(@VarUserPreferedChart))

		SELECT @VarUserPreferedChart,@List as OperationTypeId
		--SELECT '1,3,5,286,287' as OperationTypeId
		/****************************Fleet Statistics******************************************/
		--select count(distinct(fv.VehicleId)) as 'No of Vehicles' from rvlfFleetUsers FU inner join rvlfFleetVehicles fv
		--on fv.FleetId = FU.FleetId inner join rvlfFleet f on f.FleetId = fv.FleetId
		--inner join rvlfVehicleAssignment VA on VA.VehicleId = FV.VehicleId
		--where f.OrganizationId =@bigOrganizationID1 AND
		--f.FleetId =@bigFleetID1
		select 0 as 'No of Vehicles'
		----FU.UserId= @bigUserID Unassign user for fleet
		--;WITH cteVehicleStatusbyFleet AS
		--(SELECT DISTINCT(b.BoxId),b.LastSensorMask,b.LastSpeed
		--FROM rvlfBoxId b INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId
		--INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = va.VehicleId
		--INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId INNER JOIN rvlfFleetUsers fu ON fu.FleetId=f.FleetId
		--LEFT OUTER JOIN rvlfUser u ON u.UserId = fu.UserId WHERE u.OrganizationId= @bigOrganizationID1 and
		--f.FleetId = @bigFleetID1)

		--SELECT isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0 THEN 1 ELSE 0 END),0) as Moving,
		--isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN 1 ELSE 0 END),0) as Idling,
		--isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =0 THEN 1 ELSE 0 END),0) as Parked FROM
		--cteVehicleStatusbyFleet
		SELECT 0 as Moving,		0 as Idling,		0 as Parked 
		select null as vehicleTypeId, null as VehicleDescription, null as TotalDevices,null as Warranty, null as NonWarranty,null as PasGenerateddate,'Warranty Active' where 1=2
		/****************************Portal usage***********************************************/
		if Exists(select * from @tblDashboardChartIndex where ChartIndex =287)
			begin
				SELECT DISTINCT u.UserName,-- SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime))as Seconds,
				CEILING(SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime)) / 60.00) as DurationInMinutes,
				dbo.rvlf_fn_GetTimeFromSeconds(SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime))) AS [UsageTimeFormatted],
				row_number() over(order by SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime)) desc) as PortalUsageRowno,
				'-' as DriverName,
				CONVERT(VARCHAR,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+
				' '+ CONVERT(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) AS TIME),22) as PasGenerateddate
				FROM dbo.rvlfUserLogin ul
				INNER JOIN dbo.rvlfUser u ON u.UserId=ul.UserId AND u.UserId IN
				(SELECT DISTINCT fu.UserID FROM dbo.rvlfFleetUsers fu INNER JOIN dbo.rvlfFleet f ON f.FleetId=fu.FleetId
				WHERE f.OrganizationID=@bigOrganizationID1)-- AND f.FleetId=@bigFleetID1)
				INNER JOIN rvlfUserPreferences up ON up.UserId=u.UserId
				WHERE u.IsHidden=0 AND ul.LoginDateTime BETWEEN @dtStartDate1 AND getdate() and ul.LogoffDateTime is not null  
				AND (@CustomerID is null or @CustomerID = '' or @CustomerID=0 or u.CustomerID=@CustomerID) 
				group by u.UserName
			End
		Else
			Begin
				select distinct 1 as UserName,Null as DurationInMinutes,
				Null as [UsageTimeFormatted],Null as PortalUsageRowno,Null as DriverName,Null as PasGenerateddate Where 1 = 2
			End
		/*****************I/O Monitor**********/
		select null as Sno,null as InType,NULL as AnalogOP1, null as AnalogOP2,null as AnalogOP3, null as AnalogOP4,
		null as Value,null as AnalogInput,null as AnalogOutput,null as DigitalInput,null as DigitalOutput,null as CmdStatus ,'I/O Monitor' Where 1 = 2
		select NULL AS VehicleTypeName,null as OpenCases ,null as ClosedCases,
		null as PasGenerateddate,'I/O Monitor' where 1 =2
		/*****************For Product/ESP status chart data***********************/
		Select 'Total' as VehicleTypeName,count( StatusType) as OnlineTotalCount,0 as OfflineTotalCount,0 as TotalCount, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+
		Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate
		from @tblmsgsDeviceType 
		union all
		Select StatusType as VehicleTypeName, count( StatusType) as OnlineTotalCount,0 as OfflineTotalCount,
		0 as TotalCount, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+
		Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate
		from @tblmsgsDeviceType  group by  StatusType

		Declare @TempAlarm1 as Table(
		AlarmTID INT IDENTITY(1, 1),
		VehicleTypeName varchar(500),
		VehicleDescription varchar(1000)
		)
		Declare @TempAlarmFinal1 as Table(
			AlarmTID INT IDENTITY(1, 1),
			VehicleTypeName varchar(500),
			NoofAlarmsCritical bigint,
			NoofAlarmsWarning1 bigint,
			NoofAlarmsWarning2 bigint,
			TotalCount bigint
		)
		insert into @TempAlarm1
		select distinct VehicleTypeName,VehicleDescription from @TempAlarm
		insert into @TempAlarmFinal1
		select distinct VehicleTypeName,0,0,0,0 from @TempAlarm
		DECLARE @intBoxLooping varchar(max)
		Declare @TempAlarmFinal  as Table( 
			AlarmTID INT IDENTITY(1, 1), 
			VehicleTypeName  varchar(500),  
			NoofAlarmsCritical bigint 
		)
		insert into @TempAlarmFinal 
		select  s.AlarmLevelName ,count(distinct b.ControllerID) 
		from rvlfBoxId b   
		inner join rvlfMAKDevices md on b.BoxId=md.BoxId
		inner join rvlfVehicleAssignment va on va.BoxId =b.BoxId  	
		inner join rvlfFleetVehicles fv on fv.VehicleId=md.VehicleId  	
		--inner join rvlffleet f on f.FleetId=fv.Fleetid
		inner join rvlfVehicleType vt on vt.VehicleTypeId =md.SubTypeId
		inner join rvlfSeverity s on b.ControllerID=s.AlarmLevelId		
		where b.OrganizationId= @bigOrganizationID1 and  (@bigFleetID1 is null or @bigFleetID1 = '' or @bigFleetID1=0 or fv.FleetId = @bigFleetID1) -- and fv.FleetId IN  (@bigFleetID1)
		And (md.IsDelete = 0) and b.ControllerID is not null and b.ControllerID !=0 AND (@CustomerID is null or @CustomerID = '' or @CustomerID=0 or md.CustomerId=@CustomerID) 
		--and CM.AlarmLevelId in(2,1,3) --and cm.IsAlarm= 1 
		group by b.ControllerID,s.AlarmLevelName	

		if exists(Select * from @TempAlarmFinal)
			Begin
				insert into @TempAlarmFinal
				select 'Total', sum(NoofAlarmsCritical) from @TempAlarmFinal  
			End

		select 1 as CriticalAlarms,VehicleTypeName,NoofAlarmsCritical,0 as NoofAlarmsWarning1,0 as NoofAlarmsWarning2,
		0 as TotalCount,1 as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+
		Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,'critical' from @TempAlarmFinal
		/**************** Nearing maintenacne Chart***********************/
		if Exists(select * from @tblDashboardChartIndex where ChartIndex =373)
			begin
				Declare @temp TABLE(ServiceDetailsId bigint, VehiclePlanId bigint, PlanDetailsId bigint, VehicleId bigint,                       
				PlanName varchar(100), ServiceType tinyint, Frequency tinyint, ServicesPlanned varchar(2000),                       
				ServiceCategoryId bigint, DueOn varchar(35), CurrentReadings FLOAT, Nearing int, IsRecurring bit,              
				ServicesDone varchar(2000), ExpectedDueOn bigint, CurrentValues Varchar(30))                      
				INSERT INTO @temp(ServiceDetailsId, VehiclePlanId, PlanDetailsId, VehicleId, PlanName, ServiceType, Frequency,                       
				DueOn, CurrentReadings, Nearing, IsRecurring, ServicesDone, ExpectedDueOn, CurrentValues)                      
				SELECT distinct vm.ServiceDetailsId, vm.VehiclePlanId, vm.PlanDetailsId, vp.VehicleId, mp.PlanName, vm.ServiceType, vm.Frequency,                       
				CASE WHEN vm.ServiceType = 0 OR vm.ServiceType = 1  OR vm.ServiceType = 3 THEN CONVERT(VARCHAR(35), vm.DueOn) ELSE CONVERT(VARCHAR(10), vm.DueOnDate, 101) END AS DueOn,                      
				CASE WHEN vm.ServiceType = 0  OR vm.ServiceType = 3 THEN  CAST(CAST((cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0))AS FLOAT)/(3600)AS Decimal(18,2))                      
				WHEN vm.ServiceType = 1 THEN cr.CurrentOdometerReading                       
				WHEN vm.ServiceType = 2 THEN (                      
				CASE WHEN vm.Frequency = 0 THEN DATEDIFF(D, vm.StartDate, GETUTCDATE())                       
				WHEN vm.Frequency = 1 THEN DATEDIFF(M, vm.StartDate, GETUTCDATE())                      
				WHEN vm.Frequency = 2 THEN DATEDIFF(YEAR, vm.StartDate, GETUTCDATE()) END                      
				)                      
				END AS CurrentReadings, NearingPercentage AS Nearing, mp.RecurringService, dbo.rvlf_fn_GetMaintenanceServices(1, null, vm.ServiceDetailsId) AS ServicesDone,                      
				null  AS ExpectedDueOn,                      
				CONVERT(VARCHAR(30), COnvert(varchar(30),ISNULL(CAST(CAST(cr.CurrentEngineHours + ISNULL(v.OpeningEngineHours * 3600, 0) AS FLOAT)/3600 AS DECIMAL(18,2)),0)))  + ' hrs; ' + CONVERT(VARCHAR(10), CONVERT(INT, ROUND((ISNULL(cr.CurrentOdometerReading, 0)


 
* 
				@ConversionFactor), 0, 0))) AS CurrentValues                      
				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 md on v.VehicleId=md.VehicleId                     
				INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId                      
				--INNER JOIN @tempLastReadings lr ON lr.VehicleId = v.VehicleId                      
				WHERE mp.OrganizationId = @bigOrganizationID1 AND vm.Status = 0 AND vp.IsActive = 1 AND vp.AssignedStatus = 1                       
				--AND (@bigFleetID1 IS NULL OR @bigFleetID1='' OR fv.FleetId = @bigFleetID1)   
				and  (@bigFleetID1 is null or @bigFleetID1 = '' or @bigFleetID1=0 or fv.FleetId = @bigFleetID1) 
				AND (@CustomerID is null or @CustomerID = '' or @CustomerID=0 or md.CustomerId=@CustomerID)                     
				--AND (@tiServiceType IS NULL OR @tiServiceType='' OR vm.ServiceType = @tiServiceType)                      
				--AND (@dtStartDate1 IS NULL OR vm.DueOnDate BETWEEN @dtStartDate1 AND @dtEndDate1)                      
				AND NearingPercentage >= pd.Notification1 AND IsNearing = 1     
				Declare @tempNearingData TABLE
				(  
					NearingPercentage Nvarchar(20),  
					TotalVehicleCount bigint,
					NearingMaintenanceRowno int,
					NearingMaintenanceTooltip varchar(500)
				)  
				Declare @EngineHoursbasedCntHighAbove varchar(10) = '0',@OdometerbasedCntHighAbove varchar(10) = '0',@TimeBasedCntHighAbove varchar(10) = '0',
				@EngineHoursbasedCntHigh varchar(10) = '0',@OdometerbasedCntHigh varchar(10) = '0',@TimeBasedCntHigh varchar(10) = '0',
				@EngineHoursbasedCntMedium varchar(10) = '0',@OdometerbasedCntMedium varchar(10) = '0',@TimeBasedCntMedium varchar(10) = '0',
				@EngineHoursbasedCntLow varchar(10) = '0',@OdometerbasedCntLow varchar(10) = '0',@TimeBasedCntLow varchar(10) = '0'
				Declare @NearingMaintenanceTooltipHighAbove varchar(500),@NearingMaintenanceTooltipHigh varchar(500),
				@NearingMaintenanceTooltipMedium varchar(500),@NearingMaintenanceTooltipLow varchar(500)
				Select @EngineHoursbasedCntHighAbove= count(*) from @temp where serviceType = 0 and (Nearing >= 100 )
				Select @EngineHoursbasedCntHigh= count(*) from @temp where serviceType = 0 and (Nearing >= 70 and Nearing <= 99)
				Select @EngineHoursbasedCntMedium= count(*) from @temp where serviceType = 0 and (Nearing >= 21 and Nearing <= 69)
				Select @EngineHoursbasedCntLow= count(*) from @temp where serviceType = 0 and (Nearing > 0 and Nearing <= 20)
				Select @OdometerbasedCntHighAbove= count(*) from @temp where serviceType = 1 and (Nearing >= 100 )
				Select @OdometerbasedCntHigh= count(*) from @temp where serviceType = 1 and (Nearing >= 70 and Nearing <= 99)
				Select @OdometerbasedCntMedium= count(*) from @temp where serviceType = 1 and (Nearing >= 21 and Nearing <= 69)
				Select @OdometerbasedCntLow= count(*) from @temp where serviceType = 1 and (Nearing > 0 and Nearing <= 20 )
				Select @TimeBasedCntHighAbove= count(*) from @temp where serviceType = 2 and (Nearing >= 100 )
				Select @TimeBasedCntHigh= count(*) from @temp where serviceType = 2 and (Nearing >= 70 and Nearing <= 99)
				Select @TimeBasedCntMedium= count(*) from @temp where serviceType = 2 and (Nearing >= 21 and Nearing <= 69)
				Select @TimeBasedCntLow= count(*) from @temp where serviceType = 2 and (Nearing > 0 and Nearing <= 20 )
				set @NearingMaintenanceTooltipHighAbove = 'Engine hours based : ' + @EngineHoursbasedCntHighAbove + ', Odometer based : ' + @OdometerbasedCntHighAbove + ', Time based : ' + @TimeBasedCntHighAbove
				set @NearingMaintenanceTooltipHigh = 'Engine hours based : ' + @EngineHoursbasedCntHigh + ', Odometer based : ' + @OdometerbasedCntHigh + ', Time based : ' + @TimeBasedCntHigh
				set @NearingMaintenanceTooltipMedium = 'Engine hours based : ' + @EngineHoursbasedCntMedium + ', Odometer based : ' + @OdometerbasedCntMedium + ', Time based : ' + @TimeBasedCntMedium
				set @NearingMaintenanceTooltipLow = 'Engine hours based : ' + @EngineHoursbasedCntLow + ', Odometer based : ' + @OdometerbasedCntLow + ', Time based : ' + @TimeBasedCntLow
				insert into @tempNearingData
				Select '0 - 20%', COUNT(nearing),1,@NearingMaintenanceTooltipLow from @temp where Nearing > 0 and Nearing <= 20  
				insert into @tempNearingData
				Select '21 - 69%', COUNT(nearing),2,@NearingMaintenanceTooltipMedium from @temp where Nearing >= 21 and Nearing <= 69   
				insert into @tempNearingData
				Select '70 - 99%', COUNT(nearing),3,@NearingMaintenanceTooltipHigh from @temp where Nearing >= 70 and Nearing <= 99   
				insert into @tempNearingData
				Select 'Above 100%', COUNT(nearing),4,@NearingMaintenanceTooltipHighAbove from @temp where Nearing >= 100  
				if exists(select * from @tempNearingData where TotalVehicleCount > 0)
					Begin
						select *, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+
						Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate from @tempNearingData order by NearingMaintenanceRowno asc
					end
				else
					Begin
						select null as NearingPercentage,NULL as TotalVehicleCount,null as NearingMaintenanceRowno Where 1 = 2 
					End
			end 
		ELSE
			begin 
				select null as NearingPercentage,NULL as TotalVehicleCount,null as NearingMaintenanceRowno Where 1 = 2
			end         
		select distinct null as VehicleTypeName, null as OnlineTotalCount ,null as OfflineTotalCount ,null as TotalCount,'HVR Communication Status' Where 1 = 2
		select distinct null as CriticalAlarms, null as VehicleTypeName ,null as NoofAlarmsCritical ,null as NoofAlarmsWarning1,null as NoofAlarmsWarning2,
		null as TotalCount, null as AlarmsRowno, null as PasGenerateddate,'HVR Alarm Status' Where 1 = 2
		select distinct null as CriticalAlarms, null as VehicleTypeName ,null as NoofAlarmsCritical ,null as NoofAlarmsWarning1,null as NoofAlarmsWarning2,
		null as TotalCount, null as AlarmsRowno, null as PasGenerateddate,null as ControllerID,'HVR Warranty Alarm Status' Where 1 = 2
		select null as vehicleTypeId, null as VehicleDescription, null as TotalDevices,null as Warranty, null as NonWarranty,null as PasGenerateddate,'ESP Warranty in communication' where 1=2
		select null as vehicleTypeId, null as VehicleDescription, null as TotalDevices,null as Warranty, null as NonWarranty,null as PasGenerateddate, 'HVR Warranty in communication' where 1=2
		select null as vehicleTypeId, null as VehicleDescription, null as TotalDevices,null as Warranty, null as NonWarranty,null as PasGenerateddate, 'HVR Installed Warranty Status' where 1=2
		select distinct null as CriticalAlarms, null as VehicleTypeName ,null as NoofAlarmsCritical ,null as NoofAlarmsWarning1,null as NoofAlarmsWarning2,
		null as TotalCount, null as AlarmsRowno, null as PasGenerateddate,null as ControllerID,'HVR Non-Warranty Alarm Status' Where 1 = 2
	End

GO
/****** Object:  StoredProcedure [dbo].[rvlfDashboard_ADOR_bkp]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[rvlfDashboard_ADOR_bkp]            
(            
 @bigOrganizationID bigint,            
 @bigFleetID bigint = null,            
 @dtStartDate datetime,            
 @dtEndDate datetime,            
 @bigQueryingUser bigint,  
 @bigVehicleTypeID bigint = null,  
 @bigVehicleID bigint = null  
)               
AS            
/******************************************************************************/  
-- Name  : rvlfDashboard_ADOR 86,176,'10-oct-17','11-Oct-17',322,null,null  
-- Description : To get the organization statistics.            
-- Author  : V.Narayanasamy            
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--    : 12-May-2011 VN Altered the running and idling logic                   
/******************************************************************************/   
BEGIN       

 Declare @bigOrganizationID1 bigint=@bigOrganizationID,            
 @bigFleetID1 bigint = @bigFleetID,            
 @dtStartDate1 datetime=@dtStartDate,            
 @dtEndDate1 datetime=@dtEndDate,            
 @bigQueryingUser1 bigint=@bigQueryingUser,  
 @bigVehicleTypeID1 bigint = @bigVehicleTypeID,  
 @bigVehicleID1 bigint = @bigVehicleID  
              
 DECLARE @HoursToBeAdded INT = 0                
 DECLARE @MinsToBeAdded INT = 0                
 DECLARE @ConversionFactor numeric (10,2) = 1.0                
 DECLARE @CaptionPrefix varchar(10)                
 DECLARE @DefaultDateFormat INT = 0       
   DECLARE @VarUserPreferedChart  varchar(max) = null   
   Declare @bigTopNos bigint   = 10    
   DECLARE @Distance varchar(20)                   
                
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                
     @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,                
     @CaptionPrefix = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'kms' END,              
     @Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END,     
     @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end)  
     --,@VarUserPreferedChart = ISNULL(UserPreferedChart,'1,2,3,4,5')   
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz                
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser1                         
          
       SELECT @VarUserPreferedChart = ISNULL(UserPreferedChart,'1,3,5,286,287') from rvlfUserPreferences  WHERE UserId = @bigQueryingUser1                
                  
    IF @bigFleetID1 IS NULL                
  SELECT @bigFleetID1 = FleetID FROM rvlfFleet where OrganizationId = @bigOrganizationID1 and  IsDefault=1                
                    
/***************** Organization Statistics ******************************************************************/                
             
              
 declare @IsAngAdmin int               
 select @IsAngAdmin =(case when UserGroupId = 1 then 1  else 0 end) from rvlfUserGroupAssignment where UserId= @bigQueryingUser1              
               
            
           
  select null as 'No of Vehicles'  
  select null as Moving,null as Idling,null as Parked        
           
  DECLARE @tblDashboardChartIndex table                
  (  
    ChartIndex int  
  )                
  insert into @tblDashboardChartIndex  
  select * from rvlf_fn_ConvertArrayToTable(@VarUserPreferedChart,',')                              
/********************* Alarms *******************************************************************************/                
               
	if Exists(select * from @tblDashboardChartIndex where ChartIndex =1)  
	begin 
     
	Declare @TempAlarm as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500),  
	VehicleDescription varchar(1000),
	AlarmLevelId BIGINT,
	ControllerID Bigint
	)	

	Insert into @TempAlarm
	Select Distinct vt.VehicleTypeName,Vi.VehicleDescription,AlarmLevelId, ControllerID      from rvlfAlarm a      
	inner join rvlfVehicleAssignment v on v.BoxId=a.BoxId inner join rvlfVehicle vi on vi.VehicleId =v.VehicleId
	INNER JOIN rvlfFleetVehicles fv ON vi.VehicleId = fv.VehicleId  inner join rvlfBoxMsgInType mt on a.AlarmType=mt.BoxMsgInTypeId 
	inner join rvlfVehicleType vt on vt.VehicleTypeId =vi.VehicleTypeId
	where  	(vi.OrganizationId = @bigOrganizationID) AND
			(fv.FleetId = @bigFleetID) and
	--(vi.OrganizationId = 86) AND     (fv.FleetId = 176) and
	CONVERT(date,a.DateTimeCreated)  between Convert(Date,dateadd(dd,-1,getutcdate())) and Convert(Date,getutcdate())  and
	--CONVERT(date,a.DateTimeCreated)  between CONVERT(date,@dtStartDate) and CONVERT(date,@dtEndDate)  and
	--CONVERT(date,a.DateTimeCreated)  between'25-July-15' and '26-July-17' and
		(@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR vi.VehicleTypeId = @bigVehicleTypeID1) AND  
	a.AlarmLevelId in(2,1,3) and a.AlarmType = mt.BoxMsgInTypeId	order by VehicleTypeName

		select 1 as CriticalAlarms,0 as VehicleTypeId,0 as VehicleTypeName, 0 as NoofAlarmsCritical,0 as NoofAlarmsWarning1,0 as NoofAlarmsWarning2, 0 as TotalCount, 1 as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ 
	Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate -- from @TempAlarm 
	Where 1 = 2 

	end     
	else            
	begin            
	select Null as CriticalAlarms,Null as BoxId,Null as VehicleDescription,Null as VehicleName, Null as  PasGenerateddate,Null as DriverDetails Where 1 = 2  
	end               
  --/********************* Productwise ********************/          

	DECLARE @tblmsgsDeviceType table                      
	(      
	VehicleName varchar(200),  
	VehicleTypeId bigint,
	VehicleTypeName  varchar(200),  
	FleetName varchar(200),
	TotalCount Bigint,  
	OnlineCount Bigint,  
	OfflineCount Bigint,
	StatusType varchar(50),
	LastStatusDateTime datetime,
	ControllerId Bigint  
	)   

	insert into @tblmsgsDeviceType
	select distinct v.Vehicledescription as VehicleName, vt.VehicleTypeId, vt.VehicleTypeName,f.FleetName as SiteName,0 as TotalCount, 0 as OnlineCount,
	0 as OfflineCount,(Case when DATEDIFF(HH,b.LastCommunicatedDateTime,getutcdate()) <= 12 then 'Online' else 'Offline' end) as StatusType,
	b.LastStatusDateTime,b.ControllerId
	from rvlfBoxId b   
	inner join rvlfVehicleAssignment va on va.BoxId =b.BoxId  
	inner join rvlfVehicle v on v.VehicleId =va.VehicleId  
	inner join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
	inner join rvlffleet f on f.FleetId=fv.Fleetid
	inner join rvlfVehicleType vt on vt.VehicleTypeId =v.VehicleTypeId  
	inner join rvlfMAKDevices md on md.VehicleId=v.VehicleId  
	where b.OrganizationId= @bigOrganizationID1 and fv.FleetId IN  (@bigFleetID1)   
	AND  (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR v.VehicleTypeId = @bigVehicleTypeID1)   
	AND (@bigVehicleID1 IS NULL OR @bigVehicleID1='' OR v.VehicleId = @bigVehicleID1) 
	And (md.IsDelete = 0)   

	Declare @Oncount Bigint = 0,@Offcount bigint = 0 
  

	Select distinct VehicleName, VehicleTypeId, VehicleTypeName,FleetName as SiteName,@Oncount as OnlineCount,
	@Offcount as OfflineCount,TotalCount = @Oncount + @Offcount,StatusType,
	Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) 
	as PasGenerateddate,ControllerId
	from @tblmsgsDeviceType  
   
------------***************************Equipment Usage********************************************--/  
  
 
	select  null  as  EQUsageColumn,  
	null as EQUsageColumnVal,  
	null as RunningHours,  
	null as PasGenerateddate,null as Spliter,null as DataOrder,null as VehicleTypeID,null as VehicleTypeName,  
	null as GridSeparator    
	where 1= 2  
	--where SeparatorValue > 0  


                 
 /***************** Maintenance ****************************************************************/   

	select null as VehicleTypeID,null as VehicleTypeName, null as LowCount,null as MediumCount,null as HighCount,null as HighAboveCount,null as TotalCount,  
	null as  PasGenerateddate where 1 = 2       
              
/***************** Get login active users ****************************************************************/                   
	SELECT COUNT(UserId)AS ActiveUsers               
	FROM rvlfUserLogin               
	WHERE CONVERT(DATE,LoginDateTime)=CONVERT(DATE,GETUTCDATE()) AND LogOffDateTime IS NULL              
	UNION ALL              
	SELECT COUNT(UserId) AS InternalUsers              
	FROM rvlfUserLogin UL               
	WHERE CONVERT(DATE,LoginDateTime)=CONVERT(DATE,GETUTCDATE()) AND LogOffDateTime IS NULL AND OrgId IN(1,6)              
          
              
/***************** Get User Prefered Chart****************************************************************/              
  DECLARE @List as varchar(max)                
  DECLARE @ISExport  int                
  SELECT @ISExport = ug.OperationTypeId  from rvlfOperationType op                 
  INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId                 
  INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId                
  INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId                
  INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId                
  INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId                
  INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId                  
  WHERE  ga.UserId = @bigQueryingUser1 and ug.ModuleId = 1 and ug.OperationTypeId not in (1,3,286,287)                
                
  --SELECT distinct(case when @ISExport is not null or @ISExport = '' then @VarUserPreferedChart + ',5' else @VarUserPreferedChart end)                  
                  
  DECLARE @tblmsgs table                      
  (                         
  OperationTypeId varchar(100),                
 Export  Bigint                 
  )                
  insert into @tblmsgs(OperationTypeId,Export)                 
  select  distinct(ug.OperationTypeId), Export = case when ug.OperationTypeId in (1,3,5,286,287) Then '5'  END   from rvlfOperationType op                 
  INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId                 
  INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId                
  INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId                
  INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId                
  INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId                
  INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId                 
  where ga.UserId = @bigQueryingUser1 and ug.ModuleId = 1 order by ug.OperationTypeId  desc                 
  SELECT @List = case  WHEN  @ISExport is not  null THEN COALESCE(@List + ',','5,') + cast(OperationTypeId as varchar(25)) ELSE   COALESCE(@List + ',','') + cast(OperationTypeId as varchar(25))  END  from @tblmsgs where OperationTypeId  in   
  (SELECT * FROM rvlf_fn_ConvertArrayToTable(@VarUserPreferedChart, ','))                
  SELECT @List as OperationTypeId     
  --SELECT '1,3,5,286,287' as OperationTypeId     
  /****************************Fleet Statistics******************************************/        
      
	select count(distinct(fv.VehicleId)) as 'No of Vehicles' from rvlfFleetUsers FU  inner join rvlfFleetVehicles fv                  
	on fv.FleetId = FU.FleetId inner join rvlfFleet f on f.FleetId = fv.FleetId         
	inner join rvlfVehicleAssignment VA on VA.VehicleId = FV.VehicleId                  
	where  f.OrganizationId =@bigOrganizationID1 AND 
	f.FleetId =@bigFleetID1       
	--FU.UserId= @bigUserID  Unassign user for fleet      
         
	;WITH cteVehicleStatusbyFleet AS                  
	(SELECT DISTINCT(b.BoxId),b.LastSensorMask,b.LastSpeed                  
	FROM rvlfBoxId b INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId                  
	INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = va.VehicleId                  
	INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId INNER JOIN rvlfFleetUsers fu ON fu.FleetId=f.FleetId                  
	LEFT OUTER JOIN rvlfUser u ON u.UserId = fu.UserId WHERE u.OrganizationId= @bigOrganizationID1 and       
	f.FleetId =  @bigFleetID1)                   
	SELECT isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0 THEN 1 ELSE 0 END),0) as Moving,                   
	isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN 1 ELSE 0 END),0) as Idling,                   
	isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =0 THEN 1 ELSE 0 END),0) as Parked  FROM                  
	cteVehicleStatusbyFleet   
  
  
/****************************Warranty Active******************************************START***/     
  
	declare @Temp as Table(  
	Total  BIGINT,  
	Warranty BIGINT,  
	NonWarranty BIGINT,  
	VehicleDescription varchar(150),  
	vehicleTypeId int  
	)  
  
	if (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='') AND (@bigVehicleID1 IS NULL OR @bigVehicleID1='' )  
  
	Begin  
	insert into @Temp (vehicleTypeId,VehicleDescription)  
	select DISTINCT VehicleTypeId,VehicleTypeName from rvlfVehicleType  
  
	End  
	else  
  
	Begin   
  
	insert into @Temp (vehicleTypeId,VehicleDescription)  
  
	select distincT VT.VehicleTypeId,VT.VehicleTypeName   
	from  rvlfVehicleType VT   
	INNER JOIN rvlfVehicle V   
	on VT.VehicleTypeId = V.VehicleTypeId   
	INNER join rvlfFleetVehicles fv   
	on fv.VehicleId=v.VehicleId  
	INNER JOIN rvlfFleet f   
	ON fv.FleetId = F.FleetId  
	INNER JOIN rvlfMAKDevices MD on V.VehicleId = MD.VehicleId  
	WHERE   
	(@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR VT.VehicleTypeId = @bigVehicleTypeID1)  
	AND f.FleetId IN(@bigFleetID1)     
	AND (@bigVehicleID1 IS NULL OR @bigVehicleID1='' OR MD.VehicleId = @bigVehicleID1)      
	End  
	--SELECT * FROM @Temp  
  
	update T set T.Total = A.Total from @Temp T INNER JOIN   
	(   
	select COUNT(*) as Total, NULL as Warranty,NULL as NonWarranty, vt.VehicleTypeName as VehicleDescription,vt.VehicleTypeId  
	from rvlfMakdevices MD 
	--rvlfMakSubProducts SP on MD.SubTypeId = SP.SubtypeId  
	INNER join rvlfVehicle v on v.VehicleId =MD.VehicleId  
	LEFT JOIN rvlfVehicleType vt on V.VehicleTypeId = vt.VehicleTypeId  
	LEFT join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
	LEFT JOIN rvlfFleet f ON fv.FleetId = F.FleetId  
	WHERE   
	MD.OrganizationId= @bigOrganizationID1 and fv.FleetId IN  (@bigFleetID1)   
	AND  (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR vt.VehicleTypeId = @bigVehicleTypeID1)   
	AND (@bigVehicleID1 IS NULL OR @bigVehicleID1='' OR MD.VehicleId = @bigVehicleID1)   
	and vt.VehicleTypeId is not NULL  
	and MD.IsDelete = 0  
	--AND SP.Isdelete =0  
	GROUP BY vt.VehicleTypeName,vt.VehicleTypeId) A  
	on T.vehicleTypeId = A.VehicleTypeId  
	--SELECT * FROM @Temp  
  
	update T1 set T1.NonWarranty = ISNULL(B.NonWarranty,0) from @Temp T1 INNER JOIN   
	(  
	select NULL as Total, NULL as Warranty, COUNT(*) as NonWarranty,vt.VehicleTypeName as VehicleDescription,vt.VehicleTypeId  
	from rvlfMakdevices MD 
	--LEFT JOIN rvlfMakSubProducts SP on MD.SubTypeId = SP.SubtypeId  
	INNER join rvlfVehicle v on v.VehicleId =MD.VehicleId  
	LEFT JOIN rvlfVehicleType vt on V.VehicleTypeId = vt.VehicleTypeId  
	LEFT join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
	LEFT JOIN rvlfFleet f ON fv.FleetId = F.FleetId  
	WHERE MD.WarrantyEndDate IS NULL and   
	MD.OrganizationId= @bigOrganizationID1 and fv.FleetId IN  (@bigFleetID1)   
	AND  (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR vt.VehicleTypeId = @bigVehicleTypeID1)   
	and vt.VehicleTypeId is not NULL  
	AND (@bigVehicleID1 IS NULL OR @bigVehicleID1='' OR MD.VehicleId = @bigVehicleID1)   
	and MD.IsDelete = 0  
	--AND SP.Isdelete =0  
	GROUP BY vt.VehicleTypeName,vt.VehicleTypeId  
	) B   
	on T1.vehicleTypeId = B.VehicleTypeId  
  
  
	update T2 set T2.NonWarranty = ISNULL(T2.NonWarranty,0) + ISNULL(C.NonWarranty,0) from @Temp T2 INNER JOIN  
	(select NULL as Total, NULL as Warranty,COUNT(*) as NonWarranty,vt.VehicleTypeName as VehicleDescription,vt.VehicleTypeId  
	from rvlfMakdevices MD 
	--LEFT JOIN rvlfMakSubProducts SP on MD.SubTypeId = SP.SubtypeId  
	INNER join rvlfVehicle v on v.VehicleId =MD.VehicleId  
	LEFT JOIN rvlfVehicleType vt on V.VehicleTypeId = vt.VehicleTypeId   
	LEFT join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
	LEFT JOIN rvlfFleet f ON fv.FleetId = F.FleetId  
	WHERE --MD.WarrantyEndDate IS NOT NULL  
	MD.WarrantyEndDate < CONVERT(date,@dtEndDate1)  
	and   
	MD.OrganizationId= @bigOrganizationID1 and fv.FleetId IN  (@bigFleetID1)   
	AND  (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR vt.VehicleTypeId = @bigVehicleTypeID1)   
	and vt.VehicleTypeId is not NULL  
	AND (@bigVehicleID1 IS NULL OR @bigVehicleID1='' OR MD.VehicleId = @bigVehicleID1)   
	and MD.IsDelete = 0  
	--AND SP.Isdelete =0  
	GROUP BY vt.VehicleTypeName,vt.VehicleTypeId) C   
	on T2.vehicleTypeId = C.VehicleTypeId  
  
	update T3 set T3.Warranty = ISNULL(D.Warranty,0) from @Temp T3 INNER JOIN  
	(  
	select NULL as Total, COUNT(*) as Warranty, NULL as NonWarranty,vt.VehicleTypeName as VehicleDescription,vt.VehicleTypeId  
	from rvlfMakdevices MD 
	--LEFT JOIN rvlfMakSubProducts SP on MD.SubTypeId = SP.SubtypeId  
	INNER join rvlfVehicle v on v.VehicleId =MD.VehicleId  
	LEFT JOIN rvlfVehicleType vt on V.VehicleTypeId = vt.VehicleTypeId  
	LEFT join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
	LEFT JOIN rvlfFleet f ON fv.FleetId = F.FleetId  
	WHERE --MD.WarrantyEndDate IS NOT NULL  
	MD.WarrantyEndDate >= CONVERT(date,@dtEndDate1)  
	and   
	MD.OrganizationId= @bigOrganizationID1 and fv.FleetId IN  (@bigFleetID1)   
	AND  (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR vt.VehicleTypeId = @bigVehicleTypeID1)   
	and vt.VehicleTypeId is not NULL  
	AND (@bigVehicleID1 IS NULL OR @bigVehicleID1='' OR MD.VehicleId = @bigVehicleID1)   
	and MD.IsDelete = 0  
	--AND SP.Isdelete =0  
	GROUP BY vt.VehicleTypeName,vt.VehicleTypeId) D  
	on T3.vehicleTypeId = D.VehicleTypeId  
  
	if EXISTS (select VehicleDescription from @Temp group by VehicleDescription having COUNT(Total) > 0 OR COUNT(Warranty) > 0 OR COUNT (NonWarranty) > 0 )  

	select vehicleTypeId, VehicleDescription,ISNULL(Total,0) TotalDevices,ISNULL(Warranty,0) as Warranty,ISNULL(NonWarranty,0)as NonWarranty,SUM(ISNULL(Warranty,0)),SUM(ISNULL(NonWarranty,0)),  
	Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' ' 
	+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate  
	from @Temp  
	WHERE  (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR vehicleTypeId = @bigVehicleTypeID1)   
	group by vehicleTypeId,VehicleDescription,Total,Warranty,NonWarranty  
	--HAVING (ISNULL(SUM(Warranty),0) > 0 OR ISNULL(SUM(NonWarranty),0) > 0 OR ISNULL(SUM(Total),0) > 0)  
	--AND (@bigVehicleID1 IS NULL OR @bigVehicleID1='' OR VehicleId = @bigVehicleID1)   
	Union All
	Select 0 as VehicleTypeId, 'Total' as VehicleDescription, SUM(Total), SUM(Warranty), SUM(NonWarranty), 0, 0, 
	Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' ' 
	+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate from @Temp  
	order by  vehicleTypeId  
  
	ELSE  
  
	select null as vehicleTypeId, null as VehicleDescription, null as TotalDevices,null as Warranty, null as NonWarranty,null as PasGenerateddate where 1=2  
/****************************Warranty Active****************************************** END*****/   
  
	if Exists(select * from @tblDashboardChartIndex where ChartIndex =287)  
	begin  
   
	SELECT DISTINCT  u.UserName,-- SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime))as Seconds,   
	CEILING(SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime)) / 60.00) as DurationInMinutes,  
	dbo.rvlf_fn_GetTimeFromSeconds(SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime))) AS [UsageTimeFormatted],       
	row_number() over(order by SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime)) desc) as PortalUsageRowno,  
	'-' as DriverName,  
	CONVERT(VARCHAR,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+   
	' '+ CONVERT(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) AS TIME),22) as PasGenerateddate   
	FROM dbo.rvlfUserLogin ul    
	INNER JOIN dbo.rvlfUser u ON u.UserId=ul.UserId AND u.UserId IN   
	(SELECT DISTINCT fu.UserID FROM dbo.rvlfFleetUsers fu INNER JOIN dbo.rvlfFleet f ON f.FleetId=fu.FleetId  
	WHERE f.OrganizationID=@bigOrganizationID1 AND f.FleetId=@bigFleetID1)    
	INNER JOIN rvlfUserPreferences up ON up.UserId=u.UserId  
	WHERE u.IsHidden=0 AND ul.LoginDateTime BETWEEN @dtStartDate1 AND @dtEndDate1 and ul.LogoffDateTime is not null group by u.UserName  
	End  
	Else  
	Begin  
	select distinct Null as UserName,Null as DurationInMinutes,              
	Null as [UsageTimeFormatted],Null as PortalUsageRowno,Null as DriverName,Null as PasGenerateddate Where 1 = 2  
	End    
  
/*****************I/O Monitor**********/  
  
	select null as Sno,null as InType,NULL as AnalogOP1, null as AnalogOP2,null as AnalogOP3, null as AnalogOP4,  
	null as Value,null as AnalogInput,null as AnalogOutput,null as DigitalInput,null as DigitalOutput,null as CmdStatus  Where 1 = 2  
   
	select NULL AS VehicleTypeName,null as OpenCases ,null as ClosedCases,  
	null as PasGenerateddate where 1 =2      
 
/*****************For Product/ESP status chart data***********************/

	Select 'Total' as VehicleTypeName,sum(case when StatusType = 'Online'  then 1 else 0 end) as OnlineTotalCount,0 as OfflineTotalCount,(sum((case when StatusType in ('Online','Offline')  then 1 else 0 end))) as TotalCount
	from @tblmsgsDeviceType where (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR VehicleTypeId = @bigVehicleTypeID1)
	union all
	Select VehicleTypeName, sum(case when StatusType = 'Online'  then 1 else 0 end) as OnlineTotalCount,sum(case when StatusType = 'Offline'  then 1 else 0 end) as OfflineTotalCount,
	(sum(case when StatusType = 'Online'  then 1 else 0 end)  + sum(case when StatusType = 'Offline'  then 1 else 0 end)) as TotalCount
	from @tblmsgsDeviceType where (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR VehicleTypeId = @bigVehicleTypeID1) group by VehicleTypeName

	Declare @TempAlarm1 as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500), 
	VehicleDescription varchar(1000)
	)

	Declare @TempAlarmFinal as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500),  
	NoofAlarmsCritical bigint,
	NoofAlarmsWarning1 bigint,
	NoofAlarmsWarning2 bigint,
	TotalCount bigint
	)
	insert into @TempAlarm1
	select distinct VehicleTypeName,VehicleDescription from @TempAlarm	

	insert into @TempAlarmFinal 
	select distinct VehicleTypeName,0,0,0,0 from @TempAlarm			

	DECLARE @intBoxLooping varchar(max)                                 
	SELECT @intBoxLooping = MIN(AlarmTID) from @TempAlarm1            
	WHILE @intBoxLooping IS NOT NULL                
	BEGIN    
	Declare @TAlarmTypeCritical bigint=0,@TAlarmTypeWarning1 bigint=0,@TAlarmTypeWarning2 bigint =0,@TAlarmTotalCount bigint =0           
	   

		if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @TempAlarm1 where AlarmTID = @intBoxLooping) and AlarmLevelId = 3)
		Begin
			Set @TAlarmTypeCritical = 1
		
		End
		Else if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @TempAlarm1 where AlarmTID = @intBoxLooping) and AlarmLevelId = 1)
		Begin
			Set @TAlarmTypeWarning1 = 1
		End
		Else if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @TempAlarm1 where AlarmTID = @intBoxLooping) and AlarmLevelId = 2)
		Begin
			Set @TAlarmTypeWarning2 = 1
		End
	   
		set @TAlarmTotalCount = (Select(sum(case when StatusType = 'Online'  then 1 else 0 end)  + sum(case when StatusType = 'Offline'  then 1 else 0 end)) from @tblmsgsDeviceType  where (VehicleTypeName = (select VehicleTypeName  from @TempAlarm1 where AlarmTID = @intBoxLooping)))
	   
		Update @TempAlarmFinal set NoofAlarmsCritical = NoofAlarmsCritical + @TAlarmTypeCritical,
		NoofAlarmsWarning1 = NoofAlarmsWarning1 + @TAlarmTypeWarning1, NoofAlarmsWarning2 = NoofAlarmsWarning2 + @TAlarmTypeWarning2,
		TotalCount= @TAlarmTotalCount
		where VehicleTypeName =  (select VehicleTypeName  from @TempAlarm1 where AlarmTID = @intBoxLooping)

		SELECT @intBoxLooping = MIN(AlarmTID) from @TempAlarm1 WHERE AlarmTID > @intBoxLooping                
	END


	if exists(Select * from @TempAlarmFinal)
	Begin
	insert into @TempAlarmFinal
	Select 'Total',sum(NoofAlarmsCritical),sum(NoofAlarmsWarning1),sum(NoofAlarmsWarning2),
	sum(TotalCount)
	from @TempAlarmFinal
	End

	Select distinct 1 as CriticalAlarms, VehicleTypeName , NoofAlarmsCritical ,NoofAlarmsWarning1,NoofAlarmsWarning2,
	TotalCount,
	1 as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ 
	Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate from @TempAlarmFinal

 /*************************************** HVR Communication Status  ***********************************/

 DECLARE @tblmsgsDeviceTypeHVRComm table                      
	(      
	VehicleName varchar(200),  
	VehicleTypeId bigint,
	VehicleTypeName  varchar(200),  
	FleetName varchar(200),
	TotalCount Bigint,  
	OnlineCount Bigint,  
	OfflineCount Bigint,
	StatusType varchar(50),
	LastStatusDateTime datetime,
	ControllerId Bigint  
	)   

	insert into @tblmsgsDeviceTypeHVRComm
	Select distinct v.Vehicledescription as VehicleName, vt.VehicleTypeId, vt.VehicleTypeName,f.FleetName as SiteName,0 as TotalCount, 0 as OnlineCount,
	0 as OfflineCount,(Case when DATEDIFF(HH,b.lastreportedatetime,getutcdate()) <= 12 then 'Online' else 'Offline' end) as StatusType,
	b.lastreportedatetime,b.ControllerId
	from adrControllerMaster b  	
	inner join rvlfVehicleAssignment va on va.BoxId =b.EquipmentID  
	inner join rvlfVehicle v on v.VehicleId =va.VehicleId  
	inner join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
	inner join rvlffleet f on f.FleetId=fv.Fleetid
	inner join rvlfVehicleType vt on vt.VehicleTypeId =v.VehicleTypeId  
	inner join rvlfMAKDevices md on md.VehicleId=v.VehicleId  
	where v.OrganizationId= @bigOrganizationID1 and 
	fv.FleetId IN  (@bigFleetID1)   
	AND  (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR v.VehicleTypeId = @bigVehicleTypeID1)   
	AND (@bigVehicleID1 IS NULL OR @bigVehicleID1='' OR v.VehicleId = @bigVehicleID1) 
	And (md.IsDelete = 0)  and b.IsDeleted = 0   

	Declare @OncountHVRComm Bigint = 0,@OffcountHVRComm  bigint = 0 
  

	--Select distinct VehicleName, VehicleTypeId, VehicleTypeName,FleetName as SiteName,@OncountHVRComm as OnlineCount,
	--@OffcountHVRComm  as OfflineCount,TotalCount = @OncountHVRComm + @OffcountHVRComm ,StatusType,
	--Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) 
	--as PasGenerateddate,ControllerId
	--from @tblmsgsDeviceTypeHVRComm  

    if Exists(select * from @tblmsgsDeviceTypeHVRComm)  
	begin  
 
    Select 'Total' as VehicleTypeName,sum(case when StatusType = 'Online'  then 1 else 0 end) as OnlineTotalCount,0 as OfflineTotalCount,(sum((case when StatusType in ('Online','Offline')  then 1 else 0 end))) as TotalCount
	from @tblmsgsDeviceTypeHVRComm where (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR VehicleTypeId = @bigVehicleTypeID1)
	union all
	Select VehicleTypeName, sum(case when StatusType = 'Online'  then 1 else 0 end) as OnlineTotalCount,sum(case when StatusType = 'Offline'  then 1 else 0 end) as OfflineTotalCount,
	(sum(case when StatusType = 'Online'  then 1 else 0 end)  + sum(case when StatusType = 'Offline'  then 1 else 0 end)) as TotalCount
	from @tblmsgsDeviceTypeHVRComm where (@bigVehicleTypeID1 IS NULL OR @bigVehicleTypeID1='' OR VehicleTypeId = @bigVehicleTypeID1) group by VehicleTypeName

	End  
	Else  
	Begin  
	select distinct null as VehicleTypeName, null as OnlineTotalCount ,null as OfflineTotalCount ,null as TotalCount Where 1 = 2  
	End 


  
 /*************************************** HVR Alarm Status  ***********************************/

	Declare @HVRTempAlarm as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500), 
	VehicleDescription varchar(1000),
	ControllerID Bigint
	)

	Declare @TempHVRAlarmFinal as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500),  
	NoofAlarmsCritical bigint,
	NoofAlarmsWarning1 bigint,
	NoofAlarmsWarning2 bigint,
	TotalCount bigint,
	ControllerID Bigint
	)
   
	insert into @HVRTempAlarm
	select distinct VehicleTypeName,VehicleDescription,ControllerID from @TempAlarm	

	insert into @TempHVRAlarmFinal 
	select distinct VehicleTypeName,0,0,0,0,ControllerID from @TempAlarm			

	DECLARE @intHVRAlarmBoxLooping varchar(max)                                 
	SELECT @intHVRAlarmBoxLooping = MIN(AlarmTID) from @HVRTempAlarm            
	WHILE @intHVRAlarmBoxLooping IS NOT NULL                
	BEGIN    
	Declare @THVRAlarmTypeCritical bigint=0,@THVRAlarmTypeWarning1 bigint=0,@THVRAlarmTypeWarning2 bigint =0,@THVRAlarmTotalCount bigint =0            
	   

		if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @HVRTempAlarm where AlarmTID = @intHVRAlarmBoxLooping) and AlarmLevelId = 3)
		Begin
			Set @THVRAlarmTypeCritical = 1		
		End
		Else if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @HVRTempAlarm where AlarmTID = @intHVRAlarmBoxLooping) and AlarmLevelId = 1)
		Begin
			Set @THVRAlarmTypeWarning1 = 1
		End
		Else if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @HVRTempAlarm where AlarmTID = @intHVRAlarmBoxLooping) and AlarmLevelId = 2)
		Begin
			Set @THVRAlarmTypeWarning2 = 1
		End
	   
		set @THVRAlarmTotalCount = (Select(sum(case when StatusType = 'Online'  then 1 else 0 end)  + sum(case when StatusType = 'Offline'  then 1 else 0 end)) from @tblmsgsDeviceType  where (VehicleTypeName = (select VehicleTypeName  from @HVRTempAlarm where AlarmTID = @intHVRAlarmBoxLooping)))
	   
		Update @TempHVRAlarmFinal set NoofAlarmsCritical = NoofAlarmsCritical + @THVRAlarmTypeCritical,
		NoofAlarmsWarning1 = NoofAlarmsWarning1 + @THVRAlarmTypeWarning1, NoofAlarmsWarning2 = NoofAlarmsWarning2 + @THVRAlarmTypeWarning2,
		TotalCount= @THVRAlarmTotalCount
		where VehicleTypeName =  (select VehicleTypeName  from @HVRTempAlarm where AlarmTID = @intHVRAlarmBoxLooping)

		SELECT @intHVRAlarmBoxLooping = MIN(AlarmTID) from @HVRTempAlarm WHERE AlarmTID > @intHVRAlarmBoxLooping                
	END


	if exists(Select * from @TempHVRAlarmFinal)
	Begin
	insert into @TempHVRAlarmFinal
	Select 'Total',sum(NoofAlarmsCritical),sum(NoofAlarmsWarning1),sum(NoofAlarmsWarning2),
	sum(TotalCount),ControllerID
		from @TempHVRAlarmFinal
		group by ControllerID
	End

    if Exists(select * from @HVRTempAlarm)  
	begin  
	Select distinct 1 as CriticalAlarms, VehicleTypeName , NoofAlarmsCritical ,NoofAlarmsWarning1,NoofAlarmsWarning2,
	TotalCount,		1 as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ 
	Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,ControllerID from @TempHVRAlarmFinal
	End  
	Else  
	Begin  
	select distinct null as CriticalAlarms, null as VehicleTypeName ,null as NoofAlarmsCritical ,null as NoofAlarmsWarning1,null as NoofAlarmsWarning2,
	null as TotalCount,	null as AlarmsRowno, null as PasGenerateddate,null as ControllerID Where 1 = 2  
	End 

	
/*************************************** HVR Warranty Alarm Status  ***********************************/

	Declare @WHVRTempAlarm as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500), 
	VehicleDescription varchar(1000),
	ControllerID Bigint
	)

	Declare @TempWHVRAlarmFinal as Table( 
	AlarmTID INT IDENTITY(1, 1), 
	VehicleTypeName  varchar(500),  
	NoofAlarmsCritical bigint,
	NoofAlarmsWarning1 bigint,
	NoofAlarmsWarning2 bigint,
	TotalCount bigint,
	ControllerID Bigint
	)
   
	insert into @WHVRTempAlarm
	select distinct A.VehicleTypeName,A.VehicleDescription,A.ControllerID from @TempAlarm	A
	inner join adrControllerMaster aCM on A.ControllerID = aCM.ControllerID
	where getutcdate() between aCM.WarrantyStartDate and aCM.WarrantyEndDate

	insert into @TempWHVRAlarmFinal 
	select distinct VehicleTypeName,0,0,0,0,ControllerID from @TempAlarm			

	DECLARE @intWHVRAlarmBoxLooping varchar(max)                                 
	SELECT @intWHVRAlarmBoxLooping = MIN(AlarmTID) from @WHVRTempAlarm            
	WHILE @intWHVRAlarmBoxLooping IS NOT NULL                
	BEGIN    
	Declare @TWHVRAlarmTypeCritical bigint=0,@TWHVRAlarmTypeWarning1 bigint=0,@TWHVRAlarmTypeWarning2 bigint =0,@TWHVRAlarmTotalCount bigint =0            
	   

	if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @WHVRTempAlarm where AlarmTID = @intWHVRAlarmBoxLooping) and AlarmLevelId = 3)
	Begin
		Set @TWHVRAlarmTypeCritical = 1		
	End
	Else if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @WHVRTempAlarm where AlarmTID = @intWHVRAlarmBoxLooping) and AlarmLevelId = 1)
	Begin
		Set @TWHVRAlarmTypeWarning1 = 1
	End
	Else if exists(select * from @TempAlarm where VehicleDescription =  (select VehicleDescription  from @WHVRTempAlarm where AlarmTID = @intWHVRAlarmBoxLooping) and AlarmLevelId = 2)
	Begin
		Set @TWHVRAlarmTypeWarning2 = 1
	End
	   
	set @TWHVRAlarmTotalCount = (Select(sum(case when StatusType = 'Online'  then 1 else 0 end)  + sum(case when StatusType = 'Offline'  then 1 else 0 end)) from @tblmsgsDeviceType  where (VehicleTypeName = (select VehicleTypeName  from @WHVRTempAlarm where 
AlarmTID = @intWHVRAlarmBoxLooping)))
	   
	Update @TempWHVRAlarmFinal set NoofAlarmsCritical = NoofAlarmsCritical + @TWHVRAlarmTypeCritical,
	NoofAlarmsWarning1 = NoofAlarmsWarning1 + @TWHVRAlarmTypeWarning1, NoofAlarmsWarning2 = NoofAlarmsWarning2 + @TWHVRAlarmTypeWarning2,
	TotalCount= @TWHVRAlarmTotalCount
	where VehicleTypeName =  (select VehicleTypeName  from @WHVRTempAlarm where AlarmTID = @intWHVRAlarmBoxLooping)

	SELECT @intWHVRAlarmBoxLooping = MIN(AlarmTID) from @WHVRTempAlarm WHERE AlarmTID > @intWHVRAlarmBoxLooping            
	END

	if exists(Select * from @TempWHVRAlarmFinal)
	Begin
	insert into @TempWHVRAlarmFinal
	Select 'Total',sum(NoofAlarmsCritical),sum(NoofAlarmsWarning1),sum(NoofAlarmsWarning2),
	sum(TotalCount),ControllerID
	from @TempWHVRAlarmFinal group by ControllerID
	End

	
	if Exists(select * from @WHVRTempAlarm)  
	begin  
   
	Select distinct 1 as CriticalAlarms, VehicleTypeName , NoofAlarmsCritical ,NoofAlarmsWarning1,NoofAlarmsWarning2,
	TotalCount,	1 as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ 
	Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,ControllerID from @TempWHVRAlarmFinal

	End  
	Else  
	Begin  
	select distinct null as CriticalAlarms, null as VehicleTypeName ,null as NoofAlarmsCritical ,null as NoofAlarmsWarning1,null as NoofAlarmsWarning2,
	null as TotalCount,	null as AlarmsRowno, null as PasGenerateddate,null as ControllerID Where 1 = 2  
	End 

End

GO
/****** Object:  StoredProcedure [dbo].[rvlfDashboard_MAK]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
   
CREATE  PROCEDURE [dbo].[rvlfDashboard_MAK]            
(            
 @bigOrganizationID bigint,            
 @bigFleetID bigint = null,            
 @dtStartDate datetime,            
 @dtEndDate datetime,            
 @bigQueryingUser bigint,  
 @bigVehicleTypeID bigint = null,  
 @bigVehicleID bigint = null  
)               
AS            
/******************************************************************************/  
-- Name  : rvlfDashboard_MAK 86,176,'11-Dec-16','13-Dec-16',322,null,null  
-- Description : To get the organization statistics.            
-- Author  : V.Narayanasamy            
-- Company  : Angler Technologies            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason            
--    : 12-May-2011 VN Altered the running and idling logic                   
/******************************************************************************/   
BEGIN                    
 DECLARE @HoursToBeAdded INT = 0                
 DECLARE @MinsToBeAdded INT = 0                
 DECLARE @ConversionFactor numeric (10,2) = 1.0                
 DECLARE @CaptionPrefix varchar(10)                
 DECLARE @DefaultDateFormat INT = 0       
   DECLARE @VarUserPreferedChart  varchar(max) = null   
   Declare @bigTopNos bigint   = 10    
   DECLARE @Distance varchar(20)                   
                
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                
     @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,                
     @CaptionPrefix = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'kms' END,              
     @Distance = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'km' END,     
     @DefaultDateFormat=(case when  isnull(up.DefaultDateFormat,0)=0 then 107 else up.DefaultDateFormat end)  
     --,@VarUserPreferedChart = ISNULL(UserPreferedChart,'1,2,3,4,5')   
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz                
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser                         
          
       SELECT @VarUserPreferedChart = ISNULL(UserPreferedChart,'1,2,3,4,5,286,287,304,368') from rvlfUserPreferences  WHERE UserId = @bigQueryingUser                
                  
    IF @bigFleetID IS NULL                
  SELECT @bigFleetID = FleetID FROM rvlfFleet where OrganizationId = @bigOrganizationID and  IsDefault=1                
                    
/***************** Organization Statistics ******************************************************************/                
             
              
 declare @IsAngAdmin int               
 select @IsAngAdmin =(case when UserGroupId = 1 then 1  else 0 end) from rvlfUserGroupAssignment where UserId= @bigQueryingUser              
               
            
           
  select null as 'No of Vehicles'  
  select null as Moving,null as Idling,null as Parked        
           
  DECLARE @tblDashboardChartIndex table                
  (  
    ChartIndex int  
  )                
  insert into @tblDashboardChartIndex  
  select * from rvlf_fn_ConvertArrayToTable(@VarUserPreferedChart,',')                              
/********************* Alarms *******************************************************************************/                
               
 if Exists(select * from @tblDashboardChartIndex where ChartIndex =1)  
 begin    
 select Alarms.CriticalAlarms, row_number() over(order by Alarms.CriticalAlarms DESC) as AlarmsRowno, Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ 
 Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate,VehicleTypeName  from                
  (SELECT TOP (@bigTopNos) SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) as CriticalAlarms,                
   vt.VehicleTypeName    
     
  FROM rvlfAlarm a                
   INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId                
   INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                
   INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId    
   inner join rvlfVehicleType vt on vt.VehicleTypeId =v.VehicleTypeId             
     
  WHERE                 
   (v.OrganizationId = @bigOrganizationID) AND                
   (@bigFleetID IS NULL OR @bigFleetID='' OR fv.FleetId = @bigFleetID) AND                 
   (CONVERT(date,a.DateTimeCreated) BETWEEN CONVERT(date,@dtStartDate) AND CONVERT(date,@dtEndDate))and  
   (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR v.VehicleTypeId = @bigVehicleTypeID) AND     
   (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID)                      
  GROUP BY vt.VehicleTypeName,v.OrganizationId  
  HAVING                
     SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) >0                
  ORDER BY                 
   CriticalAlarms DESC)as Alarms                  
    
   --union All         
   --Select 15 as CriticalAlarms, 1 as AlarmsRowno,GETUTCDATE() as PasGenerateddate, 'Top Float' as VehicleTypeName  
   -- union All         
   --Select 7 as CriticalAlarms, 1 as AlarmsRowno,GETUTCDATE() as PasGenerateddate, 'Bottom Float' as VehicleTypeName  
   -- union All         
   --Select 5 as CriticalAlarms, 1 as AlarmsRowno,GETUTCDATE() as PasGenerateddate, 'Tx.Temp High' as VehicleTypeName  
   --  union All         
   --Select 32 as CriticalAlarms,'16777472' as BoxId,'GPU_16777472' as VehicleDescription, 'GPU_16777472' as VehicleName, 1 as AlarmsRowno,GETUTCDATE() as PasGenerateddate, 'Conveyor Belt Loader' as VehicleTypeName  
    end     
  else            
  begin            
  select Null as CriticalAlarms,Null as BoxId,Null as VehicleDescription,Null as VehicleName, Null as  PasGenerateddate,Null as DriverDetails Where 1 = 2  
  end                  
  --/********************* Productwise ********************/                
           
 DECLARE @tblmsgsDeviceType table                      
(      
VehicleTypeID bigint,  
  VehicleTypeName  varchar(200),  
  TotalCount Bigint,  
  OnlineCount Bigint,  
  OfflineCount Bigint  
)   
  
if (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='') and (@bigVehicleID is null or @bigVehicleID='')  
Begin  
insert into @tblmsgsDeviceType (VehicleTypeID,VehicleTypeName)   
select distinct VehicleTypeId, VehicleTypeName from rvlfVehicleType  
End  
else  
Begin   
insert into @tblmsgsDeviceType (VehicleTypeID,VehicleTypeName)   
select distinct vt.VehicleTypeId, vt.VehicleTypeName from rvlfBoxId b   
inner join rvlfVehicleAssignment va on va.BoxId =b.BoxId  
inner join rvlfVehicle v on v.VehicleId =va.VehicleId  
inner join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
inner join rvlfVehicleType vt on vt.VehicleTypeId =v.VehicleTypeId  
where b.OrganizationId= @bigOrganizationID and fv.FleetId IN  (@bigFleetID)   
 AND  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR v.VehicleTypeId = @bigVehicleTypeID)   
 AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID)   
   
End  
  
DECLARE @tblmsgsDeviceTypeList table                      
(      
VehicleTypeID bigint,  
VehicleID  bigint    
)   
  
  insert into @tblmsgsDeviceTypeList  
  Select v.VehicleTypeId,v.VehicleId from rvlfVehicle v   
inner join rvlfMAKDevices md on md.VehicleId=v.VehicleId And (md.IsDelete = 0)  
where v.OrganizationId =@bigOrganizationID  
  
  
 DECLARE @intBoxLooping varchar(max)                
                 
 SELECT @intBoxLooping = MIN(VehicleTypeID) from @tblmsgsDeviceType            
 WHILE @intBoxLooping IS NOT NULL                
   BEGIN                 
   Declare @Oncount Bigint,@Offcount bigint  
  
  select @Oncount=count(Distinct(b.BoxId)) from rvlfMsgInHst b  
inner join rvlfVehicleAssignment va on va.BoxId = b.BoxId  
inner join @tblmsgsDeviceTypeList v on v.VehicleId =va.VehicleId  
inner join rvlfMAKDevices md on md.VehicleId=v.VehicleId  
where v.VehicleTypeId = @intBoxLooping and   
(CONVERT(date,b.OriginDateTime) BETWEEN CONVERT(date,@dtStartDate) AND CONVERT(date,@dtEndDate))  
--DATEDIFF(HH,B.LastStatusDateTime,GETDATE())<=24  
 AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID)   
 And (md.IsDelete = 0)  
   
  select @Offcount=  count(*) - @Oncount from @tblmsgsDeviceTypeList v  
  where v.VehicleTypeId = @intBoxLooping and  
 (@bigVehicleID IS NULL OR @bigVehicleID='' OR v.VehicleId = @bigVehicleID)   
  
   update @tblmsgsDeviceType set OnlineCount = @Oncount ,OfflineCount =@Offcount,TotalCount = @Oncount + @Offcount  
   where VehicleTypeID = @intBoxLooping      
                      
                      
       SELECT @intBoxLooping = MIN(VehicleTypeID) from @tblmsgsDeviceType WHERE VehicleTypeID > @intBoxLooping                
   END        
   IF EXISTS (select * from @tblmsgsDeviceType where TotalCount > 0)  
   Begin  
   select VehicleTypeID,VehicleTypeName, TotalCount,OnlineCount,  
   OfflineCount,Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) 
   as PasGenerateddate from 
   @tblmsgsDeviceType  
   End  
   else  
   Begin  
     select null as VehicleTypeID,null as VehicleTypeName, null as TotalCount,null as OnlineCount,  
   null as OfflineCount,null  as PasGenerateddate where 1 =2  
    
   End  
   
------------***************************Equipment Usage********************************************--/  
  
 
select  null  as  EQUsageColumn,  
null as EQUsageColumnVal,  
null as RunningHours,  
null as PasGenerateddate,null as Spliter,null as DataOrder,null as VehicleTypeID,null as VehicleTypeName,  
null as GridSeparator    
where 1= 2  
--where SeparatorValue > 0  


                 
 /***************** Maintenance ****************************************************************/      
   

      select null as VehicleTypeID,null as VehicleTypeName, null as LowCount,null as MediumCount,null as HighCount,null as HighAboveCount,null as TotalCount,  
   null as  PasGenerateddate where 1 = 2  
  
   
              
/***************** Get login active users ****************************************************************/                   
SELECT COUNT(UserId)AS ActiveUsers               
FROM rvlfUserLogin               
WHERE CONVERT(DATE,LoginDateTime)=CONVERT(DATE,GETUTCDATE()) AND LogOffDateTime IS NULL              
UNION ALL              
SELECT COUNT(UserId) AS InternalUsers              
FROM rvlfUserLogin UL               
WHERE CONVERT(DATE,LoginDateTime)=CONVERT(DATE,GETUTCDATE()) AND LogOffDateTime IS NULL AND OrgId IN(1,6)              
          
              
/***************** Get User Prefered Chart****************************************************************/              
  DECLARE @List as varchar(max)                
  DECLARE @ISExport  int                
  SELECT @ISExport = ug.OperationTypeId  from rvlfOperationType op                 
  INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId                 
  INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId                
  INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId                
  INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId                
  INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId                
  INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId                  
  WHERE  ga.UserId = @bigQueryingUser and ug.ModuleId = 1 and ug.OperationTypeId not in (1,3,286,287)                
                
  --SELECT distinct(case when @ISExport is not null or @ISExport = '' then @VarUserPreferedChart + ',5' else @VarUserPreferedChart end)                  
                  
  DECLARE @tblmsgs table                      
  (                         
  OperationTypeId varchar(100),                
 Export  Bigint                 
  )                
  insert into @tblmsgs(OperationTypeId,Export)                 
  select  distinct(ug.OperationTypeId), Export = case when ug.OperationTypeId in (1,3,5,286,287) Then '5'  END   from rvlfOperationType op                 
  INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId                 
  INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId                
  INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId                
  INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId                
  INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId                
  INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId                 
  where ga.UserId = @bigQueryingUser and ug.ModuleId = 1 order by ug.OperationTypeId  desc                 
  SELECT @List = case  WHEN  @ISExport is not  null THEN COALESCE(@List + ',','5,') + cast(OperationTypeId as varchar(25)) ELSE   COALESCE(@List + ',','') + cast(OperationTypeId as varchar(25))  END  from @tblmsgs where OperationTypeId  in   
  (SELECT * FROM rvlf_fn_ConvertArrayToTable(@VarUserPreferedChart, ','))                
  --SELECT @List as OperationTypeId     
  SELECT '1,3,5,286,287' as OperationTypeId     
  /****************************Fleet Statistics******************************************/        
      
 select count(distinct(fv.VehicleId)) as 'No of Vehicles' from rvlfFleetUsers FU  inner join rvlfFleetVehicles fv                  
 on fv.FleetId = FU.FleetId inner join rvlfFleet f on f.FleetId = fv.FleetId                   
 inner join rvlfVehicleAssignment VA on VA.VehicleId = FV.VehicleId                  
 where  f.OrganizationId =@bigOrganizationID AND 
 f.FleetId =@bigFleetID       
 --FU.UserId= @bigUserID  Unassign user for fleet      
         
 ;WITH cteVehicleStatusbyFleet AS                  
(SELECT DISTINCT(b.BoxId),b.LastSensorMask,b.LastSpeed                  
FROM rvlfBoxId b INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId                  
INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = va.VehicleId                  
INNER JOIN rvlfFleet f ON f.FleetId = fv.FleetId INNER JOIN rvlfFleetUsers fu ON fu.FleetId=f.FleetId                  
LEFT OUTER JOIN rvlfUser u ON u.UserId = fu.UserId WHERE u.OrganizationId= @bigOrganizationID and       
f.FleetId =  @bigFleetID)                   
SELECT isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0 THEN 1 ELSE 0 END),0) as Moving,                   
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN 1 ELSE 0 END),0) as Idling,                   
isnull(SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =0 THEN 1 ELSE 0 END),0) as Parked  FROM                  
cteVehicleStatusbyFleet   
  
  
/****************************Warranty Active******************************************START***/     
--select 50 as TotalDevices, 25 as Warranty,25 as NonWarranty,  
--'Kapil' as VehicleDescription  
  
--UNION  
  
--select 70 as TotalDevices, 20 as Warranty,50 as NonWarranty,  
--'Raj' as VehicleDescription  
  
declare @Temp as Table(  
Total  BIGINT,  
Warranty BIGINT,  
NonWarranty BIGINT,  
VehicleDescription varchar(150),  
vehicleTypreId int  
)  
  
if (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='') AND (@bigVehicleID IS NULL OR @bigVehicleID='' )  
  
Begin  
insert into @Temp (vehicleTypreId,VehicleDescription)  
select DISTINCT VehicleTypeId,VehicleTypeName from rvlfVehicleType  
  
End  
else  
  
Begin   
  
insert into @Temp (vehicleTypreId,VehicleDescription)  
  
select distincT VT.VehicleTypeId,VT.VehicleTypeName   
 from  rvlfVehicleType VT   
 INNER JOIN rvlfVehicle V   
 on VT.VehicleTypeId = V.VehicleTypeId   
 INNER join rvlfFleetVehicles fv   
 on fv.VehicleId=v.VehicleId  
 INNER JOIN rvlfFleet f   
 ON fv.FleetId = F.FleetId  
 INNER JOIN rvlfMAKDevices MD on V.VehicleId = MD.VehicleId  
 WHERE   
   (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR VT.VehicleTypeId = @bigVehicleTypeID)  
    AND f.FleetId IN(@bigFleetID)     
    AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID)      
End  
--SELECT * FROM @Temp  
  
update T set T.Total = A.Total from @Temp T INNER JOIN   
(   
select COUNT(*) as Total, NULL as Warranty,NULL as NonWarranty, vt.VehicleTypeName as VehicleDescription,vt.VehicleTypeId  
from rvlfMakdevices MD LEFT JOIN   
rvlfMakSubProducts SP on MD.SubTypeId = SP.SubtypeId  
LEFT JOIN rvlfVehicleType vt on SP.ProductId = vt.VehicleTypeId  
INNER join rvlfVehicle v on v.VehicleId =MD.VehicleId  
LEFT join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
LEFT JOIN rvlfFleet f ON fv.FleetId = F.FleetId  
WHERE   
MD.OrganizationId= @bigOrganizationID and fv.FleetId IN  (@bigFleetID)   
AND  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR vt.VehicleTypeId = @bigVehicleTypeID)   
AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID)   
and vt.VehicleTypeId is not NULL  
and MD.IsDelete = 0  
AND SP.Isdelete =0  
GROUP BY vt.VehicleTypeName,vt.VehicleTypeId) A  
on T.vehicleTypreId = A.VehicleTypeId  
--SELECT * FROM @Temp  
  
update T1 set T1.NonWarranty = ISNULL(B.NonWarranty,0) from @Temp T1 INNER JOIN   
(  
select NULL as Total, NULL as Warranty, COUNT(*) as NonWarranty,vt.VehicleTypeName as VehicleDescription,vt.VehicleTypeId  
from rvlfMakdevices MD LEFT JOIN   
rvlfMakSubProducts SP on MD.SubTypeId = SP.SubtypeId  
LEFT JOIN rvlfVehicleType vt on SP.ProductId = vt.VehicleTypeId  
INNER join rvlfVehicle v on v.VehicleId =MD.VehicleId  
LEFT join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
LEFT JOIN rvlfFleet f ON fv.FleetId = F.FleetId  
WHERE MD.WarrantyEndDate IS NULL and   
MD.OrganizationId= @bigOrganizationID and fv.FleetId IN  (@bigFleetID)   
AND  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR vt.VehicleTypeId = @bigVehicleTypeID)   
and vt.VehicleTypeId is not NULL  
 AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID)   
and MD.IsDelete = 0  
AND SP.Isdelete =0  
GROUP BY vt.VehicleTypeName,vt.VehicleTypeId  
) B   
on T1.vehicleTypreId = B.VehicleTypeId  
  
  
update T2 set T2.NonWarranty = ISNULL(T2.NonWarranty,0) + ISNULL(C.NonWarranty,0) from @Temp T2 INNER JOIN  
(select NULL as Total, NULL as Warranty,COUNT(*) as NonWarranty,vt.VehicleTypeName as VehicleDescription,vt.VehicleTypeId  
from rvlfMakdevices MD LEFT JOIN   
rvlfMakSubProducts SP on MD.SubTypeId = SP.SubtypeId  
LEFT JOIN rvlfVehicleType vt on SP.ProductId = vt.VehicleTypeId  
left join rvlfVehicle v on v.VehicleId =MD.VehicleId  
LEFT join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
LEFT JOIN rvlfFleet f ON fv.FleetId = F.FleetId  
WHERE --MD.WarrantyEndDate IS NOT NULL  
MD.WarrantyEndDate < CONVERT(date,@dtEndDate)  
and   
MD.OrganizationId= @bigOrganizationID and fv.FleetId IN  (@bigFleetID)   
AND  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR vt.VehicleTypeId = @bigVehicleTypeID)   
and vt.VehicleTypeId is not NULL  
 AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID)   
and MD.IsDelete = 0  
AND SP.Isdelete =0  
GROUP BY vt.VehicleTypeName,vt.VehicleTypeId) C   
on T2.vehicleTypreId = C.VehicleTypeId  
  
update T3 set T3.Warranty = ISNULL(D.Warranty,0) from @Temp T3 INNER JOIN  
(  
select NULL as Total, COUNT(*) as Warranty, NULL as NonWarranty,vt.VehicleTypeName as VehicleDescription,vt.VehicleTypeId  
from rvlfMakdevices MD LEFT JOIN   
rvlfMakSubProducts SP on MD.SubTypeId = SP.SubtypeId  
LEFT JOIN rvlfVehicleType vt on SP.ProductId = vt.VehicleTypeId  
left join rvlfVehicle v on v.VehicleId =MD.VehicleId  
LEFT join rvlfFleetVehicles fv on fv.VehicleId=v.VehicleId  
LEFT JOIN rvlfFleet f ON fv.FleetId = F.FleetId  
WHERE --MD.WarrantyEndDate IS NOT NULL  
MD.WarrantyEndDate >= CONVERT(date,@dtEndDate)  
and   
MD.OrganizationId= @bigOrganizationID and fv.FleetId IN  (@bigFleetID)   
AND  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR vt.VehicleTypeId = @bigVehicleTypeID)   
and vt.VehicleTypeId is not NULL  
 AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR MD.VehicleId = @bigVehicleID)   
and MD.IsDelete = 0  
AND SP.Isdelete =0  
GROUP BY vt.VehicleTypeName,vt.VehicleTypeId) D  
on T3.vehicleTypreId = D.VehicleTypeId  
  
if EXISTS (select VehicleDescription from @Temp group by VehicleDescription having COUNT(Total) > 0 OR COUNT(Warranty) > 0 OR COUNT (NonWarranty) > 0 )  
  
select vehicleTypreId ,VehicleDescription,ISNULL(Total,0) TotalDevices,ISNULL(Warranty,0) as Warranty,ISNULL(NonWarranty,0)as NonWarranty,SUM(ISNULL(Warranty,0)),SUM(ISNULL(NonWarranty,0)),  
Convert(varchar,dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+ ' '+ Convert(varchar,cast(dateadd(hour,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) as time),22) as PasGenerateddate  from @Temp

  
WHERE  (@bigVehicleTypeID IS NULL OR @bigVehicleTypeID='' OR vehicleTypreId = @bigVehicleTypeID)   
group by vehicleTypreId,VehicleDescription,Total,Warranty,NonWarranty  
--HAVING (ISNULL(SUM(Warranty),0) > 0 OR ISNULL(SUM(NonWarranty),0) > 0 OR ISNULL(SUM(Total),0) > 0)  
 --AND (@bigVehicleID IS NULL OR @bigVehicleID='' OR VehicleId = @bigVehicleID)   
order by  VehicleDescription  
  
ELSE  
  
select null as vehicleTypreId, null as VehicleDescription, null as TotalDevices,null as Warranty, null as NonWarranty,null as PasGenerateddate where 1=2  
/****************************Warranty Active****************************************** END*****/   
  
if Exists(select * from @tblDashboardChartIndex where ChartIndex =287)  
 begin  
   
SELECT DISTINCT  u.UserName,-- SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime))as Seconds,   
 CEILING(SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime)) / 60.00) as DurationInMinutes,  
    dbo.rvlf_fn_GetTimeFromSeconds(SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime))) AS [UsageTimeFormatted],       
 row_number() over(order by SUM(DATEDIFF(SECOND,UL.LoginDateTime,UL.LogOffDateTime)) desc) as PortalUsageRowno,  
 '-' as DriverName,  
  CONVERT(VARCHAR,DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())),@DefaultDateFormat)+   
 ' '+ CONVERT(varchar,CAST(DATEADD(HOUR,@HoursToBeAdded,DATEADD(MINUTE,@MinsToBeAdded,GETUTCDATE())) AS TIME),22) as PasGenerateddate   
 FROM dbo.rvlfUserLogin ul    
 INNER JOIN dbo.rvlfUser u ON u.UserId=ul.UserId AND u.UserId IN   
   (SELECT DISTINCT fu.UserID FROM dbo.rvlfFleetUsers fu INNER JOIN dbo.rvlfFleet f ON f.FleetId=fu.FleetId  
 WHERE f.OrganizationID=@bigOrganizationID AND f.FleetId=@bigFleetID)    
 INNER JOIN rvlfUserPreferences up ON up.UserId=u.UserId  
 WHERE u.IsHidden=0 AND ul.LoginDateTime BETWEEN @dtStartDate AND @dtEndDate and ul.LogoffDateTime is not null group by u.UserName  
End  
Else  
Begin  
select distinct Null as UserName,Null as DurationInMinutes,              
   Null as [UsageTimeFormatted],Null as PortalUsageRowno,Null as DriverName,Null as PasGenerateddate Where 1 = 2  
End    
  
  
  
/*****************I/O Monitor**********/  

  
select null as Sno,null as InType,NULL as AnalogOP1, null as AnalogOP2,null as AnalogOP3, null as AnalogOP4,  
null as Value,null as AnalogInput,null as AnalogOutput,null as DigitalInput,null as DigitalOutput,null as CmdStatus  Where 1 = 2  
  
  
  
   
 select NULL AS VehicleTypeName,null as OpenCases ,null as ClosedCases,  
 null as PasGenerateddate where 1 =2   
   
   

  End

GO
/****** Object:  StoredProcedure [dbo].[rvlfGetSetUOM]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[rvlfGetSetUOM]  
(  
	@Uno tinyint=0,  
	@UOM varchar(15)=null,  
	@Description varchar(100)=null,  
	@Operation char(1)='S',
	@OrganizationID bigint=null  
)  
AS   
	BEGIN
		IF(@Operation='S')  
			BEGIN 
				SELECT * from rvlfUOM where (@Uno is null or @Uno=0 or Uno=@Uno) and (@OrganizationID is null or @OrganizationID=0 or OrganizationID=@OrganizationID)
			END
		IF(@Operation='I')  
		IF exists(SELECT * FROM rvlfUOM where UOM=@UOM and OrganizationID=@OrganizationID)
			RAISERROR('UoM already exists!',15,0)                    
		ELSE
			INSERT INTO rvlfUOM VALUES (@UOM,@Description,@OrganizationID)  
		If(@Operation='U')  
			UPDATE rvlfUOM set UOM=@UOM, [Description]=@Description where Uno=@Uno and OrganizationID=@OrganizationID
		IF(@Operation='D')  
			begin
				declare @UoMID bigint
				select @UoMID=Uno from rvlfUOM where UOM=@UOM and OrganizationID=@OrganizationID
				if(@UoMID is null)
					begin
						Select 'Please check the Item UoM name.' as ConfrimMessage
					end
				else
					begin
						if exists(select * from rvlfInvItemMaster where UOM=@UoMID AND IsActive=1)
							begin
								Select 'This Item UoM has been already assigned to item master. Cannot be deleted.' as ConfrimMessage
							end
						else
							begin
								DELETE FROM rvlfUOM where UOM=@UOM and OrganizationID=@OrganizationID
								Select 'Item UoM Deleted Successfully.' as ConfrimMessage
							end
					end
				
			end
	END

GO
/****** Object:  StoredProcedure [dbo].[rvlt_sp_AddEditViewUserPreferences]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlt_sp_AddEditViewUserPreferences]              
(                   
   @Operation char(50),                  
   @UserId bigint,                  
   @TimezoneId bigint=NULL,                  
   @Distance int = 1,                  
   @DefaultFleetId bigint=NULL,                  
   @RefreshFrequencyId bigint=NULL,                  
   @bigOrganizationId bigint=0,                  
   @bigLandingPageId bigint=null,                  
   @Fuel int=1,                
   @varLang varchar(100) = NULL,              
   @intDefaultDateFormat int =NULL,          
   @UserPreferedChart varchar(500)=NULL,        
   @Hours varchar(10) = NULL,          
   @FromDate DateTime = NULL,          
   @TODate DateTime = NULL,
   @ChartPosition varchar(500) = null                         
)                  
AS                  
/****************************************************************************************************************/                  
-- Name           : rvlt_sp_AddEditViewUserPreferencesNew                  
-- Description    : To Add or Update the User Preferences or to view the User Preferences based on the user id                  
-- Author         : Kumuthini. L               
-- Created Date   : 14-July-09                  
--  Modified Date : 17-Aug-2010 Added the organizationid for partner login.                  
--                : 11-Jan-2011 VN Included the Landing page functionalities.                  
--                : 26-July-2011 - Ranjith - Updating user default Language           
--      : 18-Apr-2012 - Selvakumar -DayLight Savings functionalities.         
/****************************************************************************************************************/                  
BEGIN                  
 SET NOCOUNT ON                   
                   
 IF(@DefaultFleetId = 0)                  
 BEGIN                  
                   
  SET @DefaultFleetId = NULL                  
                   
 END           
 IF(@FromDate = '' OR  @TODate = '')          
 BEGIN           
 Select @FromDate = NUll          
 Select @TODate =NUll          
 END                
                   
 -- If Operation is 'Save'                  
 IF(@Operation = 'Save')                  
  BEGIN                  
   -- Check whether the User Preferences already exists for the particular User Id                  
   DECLARE @isExist INT                    
   SET @isExist  = (SELECT COUNT(*) FROM rvlfUserPreferences WHERE UserId = @UserId)                    
                        
   -- If User Preferences exist for an user, then update the preferences using the User Id                  
   IF(@isExist >= 1)                    
    BEGIN                    
     UPDATE rvlfUserPreferences SET TimezoneId = @TimezoneId,Distance = @Distance,                  
       DefaultFleetId = @DefaultFleetId,RefreshFrequencyId = @RefreshFrequencyId,organizationId=@bigOrganizationId,                  
       LandingPageId=@bigLandingPageId,Fuel=@Fuel,lang=@varLang ,DefaultDateFormat=@intDefaultDateFormat,UserPreferedChart=@UserPreferedChart,        
        Hours =@Hours, FromDate  = @FromDate,TODate = @TODate,ChartPosition = @ChartPosition                         
      WHERE UserId = @UserId                    
    END                    
   ELSE                    
    -- If User Preferences does not exists, then insert the preferences into the User Preferences Table                  
    BEGIN                     
       INSERT INTO rvlfUserPreferences (UserId,TimezoneId,Distance,DefaultFleetId,RefreshFrequencyId,organizationId,LandingPageId,Fuel,lang,DefaultDateFormat,UserPreferedChart,Hours,FromDate,ToDate,ChartPosition)                       
       VALUES(@UserId,@TimezoneId ,@Distance ,@DefaultFleetId ,@RefreshFrequencyId,@bigOrganizationId,@bigLandingPageId,@Fuel,@varLang,@intDefaultDateFormat,@UserPreferedChart,@Hours,@FromDate,@TODate,@ChartPosition)                      
     END                    
  END                  
 -- If Operation is 'View'                  
 ELSE IF (@Operation = 'View')                   
  BEGIN         
      -- Get the User Preferences based on the User Id                  
   SELECT TimezoneId,Distance,DefaultFleetId,RefreshFrequencyId,organizationId,LandingPageId,Fuel,    
   isnull(lang,'LanguageEn') as lang,isnull(DefaultDateFormat,106) as DefaultDateFormat,case when UserPreferedChart= '' then null else UserPreferedChart end as UserPreferedChart,Hours,FromDate,ToDate  FROM rvlfUserPreferences WHERE UserId = @UserId                  
 --  select distinct(ug.OperationTypeId),ug.UserGroupId from rvlfOperationType op         
 --INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId         
 --INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId        
 --INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId        
 --INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId        
 --INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId        
 --INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId      
 --where ga.UserId = @UserId      
 SELECT DISTINCT (ug.OperationTypeId) as OperationTypeId,ug.UserGroupId from rvlfOperationType op             
 INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId             
 INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId            
 INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId            
 INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId             
 INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId            
 INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId       
 --and ug.OperationTypeId IN(SELECT * FROM rvlf_fn_ConvertArrayToTable(up.UserPreferedChart,','))         
 where ga.UserId = @UserId and M.ModuleID = 1   
 
  select o.OrgLangSettings from rvlfOrganization o   
 inner join rvlfUser u on u.OrganizationId = o.OrganizationId  
 where u.UserId = @UserId  
 
  END                  
Else IF(@Operation = 'SaveDashboard')                  
  BEGIN                    
   UPDATE rvlfUserPreferences SET UserPreferedChart=@UserPreferedChart WHERE UserId = @UserId        
 End                   
 Else IF(@Operation = 'ViewDashboard')                  
  BEGIN                    
 Select  UserPreferedChart from rvlfUserPreferences WHERE UserId = @UserId        
 End                                              
 SET NOCOUNT OFF                  
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlt_sp_AddEditViewUserPreferencesForDashboardPosition]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlt_sp_AddEditViewUserPreferencesForDashboardPosition]              
(                   
   @Operation char(4),                  
   @UserId bigint,                  
   @TimezoneId bigint=NULL,                  
   @Distance int = 1,                  
   @DefaultFleetId bigint=NULL,                  
   @RefreshFrequencyId bigint=NULL,                  
   @bigOrganizationId bigint=0,                  
   @bigLandingPageId bigint=null,                  
   @Fuel int=1,                
   @varLang varchar(100) = NULL,              
   @intDefaultDateFormat int =NULL,          
   @UserPreferedChart varchar(50)=NULL,        
   @Hours varchar(10) = NULL,          
   @FromDate DateTime = NULL,          
   @TODate DateTime = NULL,
   @ChartPosition varchar(200) = null                         
)                  
AS                  
/****************************************************************************************************************/                  
-- Name           : rvlt_sp_AddEditViewUserPreferencesNewForDashboardPosition                 
-- Description    : To Add or Update the User Preferences or to view the User Preferences based on the user id                  
-- Author         : Kumuthini. L               
-- Created Date   : 13-May-14                           
-- Created By : Kapil 

/****************************************************************************************************************/                  
BEGIN                  
 SET NOCOUNT ON                   
                   
 IF(@DefaultFleetId = 0)                  
 BEGIN                  
                   
  SET @DefaultFleetId = NULL                  
                   
 END           
 IF(@FromDate = '' OR  @TODate = '')          
 BEGIN           
 Select @FromDate = NUll          
 Select @TODate =NUll          
 END                
                   
 -- If Operation is 'Save'                  
 IF(@Operation = 'Save')                  
  BEGIN                  
   -- Check whether the User Preferences already exists for the particular User Id                  
   DECLARE @isExist INT                    
   SET @isExist  = (SELECT COUNT(*) FROM rvlfUserPreferences WHERE UserId = @UserId)                    
                        
   -- If User Preferences exist for an user, then update the preferences using the User Id                  
   IF(@isExist >= 1)                    
    BEGIN                    
     UPDATE rvlfUserPreferences SET TimezoneId = @TimezoneId,Distance = @Distance,                  
       DefaultFleetId = @DefaultFleetId,RefreshFrequencyId = @RefreshFrequencyId,organizationId=@bigOrganizationId,                  
       LandingPageId=@bigLandingPageId,Fuel=@Fuel,lang=@varLang ,DefaultDateFormat=@intDefaultDateFormat,UserPreferedChart=@UserPreferedChart,        
        Hours =@Hours, FromDate  = @FromDate,TODate = @TODate,ChartPosition = @ChartPosition                         
      WHERE UserId = @UserId                    
    END                    
   ELSE                    
    -- If User Preferences does not exists, then insert the preferences into the User Preferences Table                  
    BEGIN                     
       INSERT INTO rvlfUserPreferences (UserId,TimezoneId,Distance,DefaultFleetId,RefreshFrequencyId,organizationId,LandingPageId,Fuel,lang,DefaultDateFormat,UserPreferedChart,Hours,FromDate,ToDate,ChartPosition)                       
       VALUES(@UserId,@TimezoneId ,@Distance ,@DefaultFleetId ,@RefreshFrequencyId,@bigOrganizationId,@bigLandingPageId,@Fuel,@varLang,@intDefaultDateFormat,@UserPreferedChart,@Hours,@FromDate,@TODate,@ChartPosition)                      
     END                    
  END                  
 -- If Operation is 'View'                  
 ELSE IF (@Operation = 'View')                   
  BEGIN         
      -- Get the User Preferences based on the User Id                  
   SELECT TimezoneId,Distance,DefaultFleetId,RefreshFrequencyId,organizationId,LandingPageId,Fuel,    
   isnull(lang,'LanguageEn') as lang,isnull(DefaultDateFormat,106) as DefaultDateFormat, isnull(UserPreferedChart,'1,2,3,4,5,302,303,315') as UserPreferedChart,Hours,FromDate,ToDate  FROM rvlfUserPreferences WHERE UserId = @UserId                  
 --  select distinct(ug.OperationTypeId),ug.UserGroupId from rvlfOperationType op         
 --INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId         
 --INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId        
 --INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId        
 --INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId        
 --INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId        
 --INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId      
 --where ga.UserId = @UserId      
 SELECT DISTINCT (ug.OperationTypeId) as OperationTypeId,ug.UserGroupId from rvlfOperationType op             
 INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId             
 INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId            
 INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId            
 INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId             
 INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId            
 INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId       
 --and ug.OperationTypeId IN(SELECT * FROM rvlf_fn_ConvertArrayToTable(up.UserPreferedChart,','))         
 where ga.UserId = @UserId and M.ModuleID = 1   
 
  select o.OrgLangSettings from rvlfOrganization o   
 inner join rvlfUser u on u.OrganizationId = o.OrganizationId  
 where u.UserId = @UserId  
 
  END                  
                    
 SET NOCOUNT OFF                  
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlt_sp_AddEditViewUserPreferencesForTest]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlt_sp_AddEditViewUserPreferencesForTest]              
(                   
   @Operation char(4),                  
   @UserId bigint,                  
   @TimezoneId bigint=NULL,                  
   @Distance int = 1,                  
   @DefaultFleetId bigint=NULL,                  
   @RefreshFrequencyId bigint=NULL,                  
   @bigOrganizationId bigint=0,                  
   @bigLandingPageId bigint=null,                  
   @Fuel int=1,                
   @varLang varchar(100) = NULL,              
   @intDefaultDateFormat int =NULL,          
   @UserPreferedChart varchar(20)=NULL,        
   @Hours varchar(10) = NULL,          
   @FromDate DateTime = NULL,          
   @TODate DateTime = NULL,
   @ChartPosition varchar(200) = null                         
)                  
AS                  
/****************************************************************************************************************/                  
-- Name           : rvlt_sp_AddEditViewUserPreferencesForTest 'View',502,0, 0, 0, 0            
-- Description    : To Add or Update the User Preferences or to view the User Preferences based on the user id                  
-- Author         : kapil                 
-- Created Date   : 06-May-201         
         
/****************************************************************************************************************/                  
BEGIN                  
 SET NOCOUNT ON                   
                   
 IF(@DefaultFleetId = 0)                  
 BEGIN                  
                   
  SET @DefaultFleetId = NULL                  
                   
 END           
 IF(@FromDate = '' OR  @TODate = '')          
 BEGIN           
 Select @FromDate = NUll          
 Select @TODate =NUll          
 END                
                   
 -- If Operation is 'Save'                  
 IF(@Operation = 'Save')                  
  BEGIN                  
   -- Check whether the User Preferences already exists for the particular User Id                  
   DECLARE @isExist INT                    
   SET @isExist  = (SELECT COUNT(*) FROM rvlfUserPreferences WHERE UserId = @UserId)                    
                        
   -- If User Preferences exist for an user, then update the preferences using the User Id                  
   IF(@isExist >= 1)                    
    BEGIN                    
     UPDATE rvlfUserPreferences SET TimezoneId = @TimezoneId,Distance = @Distance,                  
       DefaultFleetId = @DefaultFleetId,RefreshFrequencyId = @RefreshFrequencyId,organizationId=@bigOrganizationId,                  
       LandingPageId=@bigLandingPageId,Fuel=@Fuel,lang=@varLang ,DefaultDateFormat=@intDefaultDateFormat,UserPreferedChart=@UserPreferedChart,        
        Hours =@Hours, FromDate  = @FromDate,TODate = @TODate,ChartPosition = @ChartPosition                         
      WHERE UserId = @UserId                    
    END                    
   ELSE                    
    -- If User Preferences does not exists, then insert the preferences into the User Preferences Table                  
    BEGIN                     
       INSERT INTO rvlfUserPreferences (UserId,TimezoneId,Distance,DefaultFleetId,RefreshFrequencyId,organizationId,LandingPageId,Fuel,lang,DefaultDateFormat,UserPreferedChart,Hours,FromDate,ToDate,ChartPosition)                       
       VALUES(@UserId,@TimezoneId,@Distance ,@DefaultFleetId ,@RefreshFrequencyId,@bigOrganizationId,@bigLandingPageId,@Fuel,@varLang,@intDefaultDateFormat,@UserPreferedChart,@Hours,@FromDate,@TODate,@ChartPosition)                      
     END                    
  END                  
 -- If Operation is 'View'                  
 ELSE IF (@Operation = 'View')                   
  BEGIN         
      -- Get the User Preferences based on the User Id                  
   SELECT TimezoneId,Distance,DefaultFleetId,RefreshFrequencyId,organizationId,LandingPageId,Fuel,    
   isnull(lang,'LanguageEn') as lang,isnull(DefaultDateFormat,106) as DefaultDateFormat, isnull(UserPreferedChart,'1,2,3,4,5,302,303,315') as UserPreferedChart,Hours,FromDate,ToDate  FROM rvlfUserPreferences WHERE UserId = @UserId                  
 --  select distinct(ug.OperationTypeId),ug.UserGroupId from rvlfOperationType op         
 --INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId         
 --INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId        
 --INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId        
 --INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId        
 --INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId        
 --INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId      
 --where ga.UserId = @UserId      
 SELECT DISTINCT (ug.OperationTypeId) as OperationTypeId,ug.UserGroupId from rvlfOperationType op             
 INNER JOIN rvlfUserGroupSecurity  ug on ug.OperationTypeId = op.OperationTypeId             
 INNER JOIN rvlfUserGroup u on u.UserGroupId = ug.UserGroupId            
 INNER JOIN rvlfModule m on M.ModuleID = ug.ModuleId            
 INNER JOIN rvlfUser ur on ur.OrganizationId = u.OrganizationId             
 INNER JOIN rvlfUserGroupAssignment ga on ga.UserGroupId = ug.UserGroupId            
 INNER JOIN rvlfUserPreferences up ON ur.UserId = up.UserId       
 --and ug.OperationTypeId IN(SELECT * FROM rvlf_fn_ConvertArrayToTable(up.UserPreferedChart,','))         
 where ga.UserId = @UserId and M.ModuleID = 1
 
 select o.OrgLangSettings from rvlfOrganization o   
 inner join rvlfUser u on u.OrganizationId = o.OrganizationId  
 where u.UserId = @UserId  
 
  END                  
                    
 SET NOCOUNT OFF                  
END 

GO
/****** Object:  StoredProcedure [dbo].[rvlt_sp_AddEditViewWO]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[rvlt_sp_AddEditViewWO]          
(               
   @Operation int,              
   @WONo bigint = NULL,              
   @VehiclePlanId bigint=NULL,              
   @WOTypeId bigint = 1,              
   @VendorId bigint=NULL,              
   @StartDate datetime=NULL,              
   @EDC datetime=0,              
   @WarrantyorContract bigint=null,              
   @WarrantyEnddate datetime=null,            
   @AssignedTo bigint = NULL,          
   @Remarks varchar(max) =NULL,         
   @CreatedBy bigint= Null,
   @CreatedDateTime datetime = Null,
   	@bigQueryingUser bigint = Null,
	 @bigOrganizationId bigint = Null,
	 @vcQuotationFile varchar(max) =NULL
)              
AS              
/****************************************************************************************************************/              
-- Name           : rvlt_sp_AddEditViewWO              
-- Description    : To Add or Update the WO or to view the WO based on the WO id              
-- Author         : Ranjith N
-- Created Date   : 16-Nov-15              
/****************************************************************************************************************/              
BEGIN              
 SET NOCOUNT ON               

DECLARE @HoursToBeAdded INT = 0         
 DECLARE @MinsToBeAdded INT = 0                        
 DECLARE @DefaultDateFormat INT = 0           

    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                       
     @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                      
        
               
 -- If Operation is 'Save'              
 IF(@Operation =1)              
  BEGIN                 
   insert into rvlfWOGeneration ( WONo ,  VehiclePlanId ,  WOTypeId ,  VendorId,  StartDate,  EDC ,  WarrantyorContract , WarrantyEnddate,  AssignedTo , Remarks, [Status],IsDelete,CreatedBy,CreatedDatetime,OrganizationId,QuotationFile) 
   values(@WONo,@VehiclePlanId,@WOTypeId,@VendorId,@StartDate,@EDC,@WarrantyorContract,@WarrantyEnddate,@AssignedTo,@Remarks,'1',0,@CreatedBy,@CreatedDateTime,@bigOrganizationId,@vcQuotationFile)            
  END              
 -- If Operation is 'View'              
 ELSE IF (@Operation =2)               
  BEGIN
  Declare @intWOStatusCurrent int = 0 ,@intWONoCurrent  varchar(50) = NULL       
  Select     @intWOStatusCurrent = [Status],@intWONoCurrent = WONo from rvlfWOGeneration w where    w.WONo = @WONo   and W.IsDelete = 0 and W.OrganizationId=@bigOrganizationId

	select WOGenid,WONo,VehiclePlanId,WOTypeId,W.VendorId,Replace(convert(varchar,StartDate,106),' ','-')  as StartDate,Replace(convert(varchar,EDC,106),' ','-') as EDC ,
	WarrantyorContract,Replace(convert(varchar,WarrantyEndDate,106),' ','-')  as WarrantyEndDate,
	AssignedTo,Remarks,[Status],w.IsDelete,W.CreatedBY,W.CreatedDatetime,TVM.VendorName,
		(Case when  WOTypeId = 1  then 'Preventive Maintenance'	 when  WOTypeId = 2  then 'Regular Maintenance'	 when  WOTypeId = 3  then 'Corrective maintenance'
	when  WOTypeId = 4  then 'Predictive Maintenance'	 when  WOTypeId = 5 then 'Periodic maintenance'	when  WOTypeId = 6  then 'Zero Hours Maintenance'
	when  WOTypeId = 7  then 'Others' end) as WOType,
	(Case when  W.WarrantyorContract = 1  then 'Basic (bumper-to-bumper)'	 when  W.WarrantyorContract = 2  then 'Powertrain'	 when  W.WarrantyorContract = 3  then 'Corrosion'
	when  W.WarrantyorContract = 4  then 'Roadside assistance'	 when  W.WarrantyorContract = 5 then 'Not under warranty'	when  W.WarrantyorContract = 6  then 'Others' end) as WarrantyType,  
    QuotationFile            
	 from rvlfWOGeneration w  
	inner join rvlfTyreVendorMaster TVM on TVM.VendorId = w.VendorId
	where w.WONo = @WONo   and W.IsDelete = 0 and W.OrganizationId=@bigOrganizationId

	select isnull(Remarks,'-') as Remarks,isnull(Username,'-') as RemarksBy,
	Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ApprovedDate)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ApprovedDate))AS TIME),22)   as  RemarksDate 
	from rvlfWOApproval WA
	inner join rvlfuser u on u.UserId = WA.ApprovedBy
	where WONo = @WONo   and IsDelete = 0 and WA.OrganizationId=@bigOrganizationId
		union all
	select isnull(Remarks,'-') as Remarks,isnull(Username,'-') as RemarksBy,
	Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ClosedDate)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ClosedDate))AS TIME),22)  as  RemarksDate 
	from rvlfWOClosure WC	
	inner join rvlfuser u on u.UserId = WC.ClosedBy
	where WC.WONo = @WONo   and IsDelete = 0 and WC.OrganizationId=@bigOrganizationId

	if @intWOStatusCurrent  in (1 )
	Begin
		select  isnull(Remarks,'-') as Remarks,isnull(Username,'-') as RemarksBy,
		Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,WA.CreatedDatetime)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,WA.CreatedDatetime ))AS TIME),22) as  RemarksDate 
		from rvlfWOGeneration WA
		inner join rvlfuser u on u.UserId = WA.AssignedTo
		where WONo = @intWONoCurrent   and WA.IsDelete = 0 and WA.OrganizationId=@bigOrganizationId 
    End
	else if @intWOStatusCurrent  in ( 2)
	Begin
		select top 1 isnull(Remarks,'-') as Remarks,isnull(Username,'-') as RemarksBy,
		Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ApprovedDate)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ApprovedDate))AS TIME),22) as  RemarksDate 
		from rvlfWOApproval WA
		inner join rvlfuser u on u.UserId = WA.AssignedTo
		where WONo = @intWONoCurrent   and IsDelete = 0 and WA.OrganizationId=@bigOrganizationId order by ApprovedDate desc
    End
	else if @intWOStatusCurrent  in (3,4)
	Begin
		select top 1 isnull(WA.Remarks,'-') as Remarks,isnull(Username,'-') as RemarksBy,
		Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ApprovedDate)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ApprovedDate))AS TIME),22) as  RemarksDate 
		from rvlfWOGeneration WG
		inner join rvlfWOApproval WA on WA.WONo = WG.WONo
		inner join rvlfuser u on u.UserId = WG.CreatedBY
		where WG.WONo = @intWONoCurrent   and WG.IsDelete = 0 and WA.OrganizationId=@bigOrganizationId order by ApprovedDate desc
    End
	else if @intWOStatusCurrent  in ( 5)
	Begin
		select isnull(Remarks,'-') as Remarks,isnull(Username,'-') as RemarksBy,
		Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ClosedDate)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ClosedDate))AS TIME),22)  as  RemarksDate 
		from rvlfWOClosure WA
		inner join rvlfuser u on u.UserId = WA.ClosedBy
		where WONo = @intWONoCurrent   and IsDelete = 0 and WA.OrganizationId=@bigOrganizationId order by ClosedDate desc
    End
	else if @intWOStatusCurrent  in (6)
	Begin
		select isnull(WA.Remarks,'-') as Remarks,isnull(Username,'-') as RemarksBy,
		Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ClosedDate)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ClosedDate))AS TIME),22)  as  RemarksDate 
		from rvlfWOClosure WA
		inner join  rvlfWOGeneration WG on WG.WONo = WA.WONo
		inner join rvlfuser u on u.UserId = WG.CreatedBY	
		where WA.WONo = @intWONoCurrent   and WG.IsDelete = 0 and WA.OrganizationId=@bigOrganizationId order by ClosedDate desc
    End
		else
	Begin
		select '-' as Remarks,'-'  as RemarksBy,'-'  as  RemarksDate 
    End
	
	
  END              
   -- If Operation is 'Update'  
   ELSE IF (@Operation =3)               
  BEGIN                    
   update rvlfWOGeneration  set  WONo=@WONo ,   WOTypeId=@WOTypeId ,  VendorId=@VendorId,  StartDate=@StartDate,  EDC =@EDC,
     WarrantyorContract=@WarrantyorContract , WarrantyEnddate=@WarrantyEnddate,  AssignedTo =@AssignedTo, Remarks=@Remarks ,QuotationFile=@vcQuotationFile  
   where WONo = @WONo   and [Status] = 1 and OrganizationId=@bigOrganizationId
  END              
-- If Operation is 'Delete'              
 ELSE IF (@Operation =4)               
  BEGIN                    
	update rvlfWOGeneration set IsDelete = 1   where WONo = @WONo   and [Status] in (1,3) and OrganizationId=@bigOrganizationId
  END                     
  -- If Operation is 'Redo'         
    ELSE IF (@Operation =5)               
  BEGIN                    
   update rvlfWOGeneration  set   WOTypeId=@WOTypeId ,  VendorId=@VendorId,  StartDate=@StartDate,  EDC =@EDC,[Status]=1,
     WarrantyorContract=@WarrantyorContract , WarrantyEnddate=@WarrantyEnddate,  AssignedTo =@AssignedTo, Remarks=@Remarks   
   where WONo = @WONo   and [Status] in( 3,6) and OrganizationId=@bigOrganizationId
  END           
  ELSE IF (@Operation = 6)   
  BEGIN
   declare @usergrp int
    set @usergrp=(SELECT g.UserGroupId FROM rvlfUserGroupAssignment ga     
    INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId    
    WHERE ga.UserId = @bigQueryingUser)    

    SELECT u.UserId,u.UserName,   dbo.rvlf_fn_GetUserGroupsByUserID(u.UserId) AS GroupBelongsTo
    FROM rvlfUser u LEFT OUTER JOIN rvlfUserPreferences p ON u.UserId=p.UserId    
    INNER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId    
    INNER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId    
    INNER JOIN rvlfUserGroupSecurity UGS ON UGS.UserGroupId = g.UserGroupId
    WHERE           
		IsActive =1     AND  IsLocked = 0  AND
		 U.ISDELETE=0 AND 
		  IsHidden <>  (case when @usergrp = 1 then 2 else 1 end)
		AND OperationTypeId = 394 and ModuleId = 29
    ORDER BY UserName ASC     
  END
 SET NOCOUNT OFF              
END   
  
  


GO
/****** Object:  StoredProcedure [dbo].[rvlt_sp_AddEditViewWOApproval]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [dbo].[rvlt_sp_AddEditViewWOApproval]          
(               
   @Operation int =null,    
    @WOGenId bigint = null,                   
   @WONo bigint = null,      
    @ApprovedBy bigint= Null,
	 @ApprovedDate datetime=null,            
	 @StatusType int= Null,
	 @Remarks varchar(max) =NULL ,
	 @Status int = NULL  ,
	 @bigFleetId bigint = NULL,        
    @bigVehicleId bigint = NULL ,
	 @bigQueryingUser bigint = Null ,
	 @AssignedTo bigint = Null ,	 
	  @bigOrganizationId bigint = Null                
   --@VehiclePlanId bigint=NULL,              
   --@WOTypeId bigint = 1,              
   --@VendorId bigint=NULL,              
   --@StartDate datetime=NULL,              
   --@EDC datetime=0,              
   --@WarrantyorContract bigint=null,              
   --@WarrantyEnddate datetime=null,            
   --@AssignedTo bigint = NULL,          
   --@Remarks varchar(max) =NULL,         
   --@CreatedBy bigint= Null,
   --@CreatedDateTime datetime = Null
)              
AS              
/****************************************************************************************************************/              
-- Name           : rvlt_sp_AddEditViewWOApproval     1,30,102,322,'11/30/2015 5:27:56 AM',3,'Ok Fine approved' 
-- Description    : To Add or Update or view the WO Approval
-- Author         : Ranjith N
-- Created Date   : 24-Nov-15              
/****************************************************************************************************************/              
BEGIN              
 SET NOCOUNT ON               
      
DECLARE @HoursToBeAdded INT = 0         
 DECLARE @MinsToBeAdded INT = 0                        
 DECLARE @DefaultDateFormat INT = 0           

    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                       
     @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    
                 
 -- If Operation is 'Approve or Reject or Redo'              
 IF(@Operation =1)              
  BEGIN                 
   insert into rvlfWOApproval( WoGenId ,WONo,ApprovedBy,ApprovedDate,StatusType,Remarks,AssignedTo,OrganizationId)
   values(@WoGenId ,@WONo,@ApprovedBy,@ApprovedDate,@StatusType,@Remarks,@AssignedTo,@bigOrganizationId)            
   update rvlfWOGeneration set [Status ]= @StatusType where WONo=@WONo and OrganizationId=@bigOrganizationId
  END              
 -- If Operation is 'View'              
 ELSE IF (@Operation =2)               
  BEGIN                    
	select WOGenid,WONo,VehiclePlanId,WOTypeId,W.VendorId,Replace(convert(varchar,StartDate,106),' ','-')  as StartDate,Replace(convert(varchar,EDC,106),' ','-') as EDC ,
	WarrantyorContract,Replace(convert(varchar,WarrantyEndDate,106),' ','-')  as WarrantyEndDate,Tv.VendorName,
	AssignedTo,Remarks,[Status],W.IsDelete,W.CreatedBY,W.CreatedDatetime ,
	(Case when  WOTypeId = 1  then 'Preventive Maintenance'	 when  WOTypeId = 2  then 'Regular Maintenance'	 when  WOTypeId = 3  then 'Corrective maintenance'
	when  WOTypeId = 4  then 'Predictive Maintenance'	 when  WOTypeId = 5 then 'Periodic maintenance'	when  WOTypeId = 6  then 'Zero Hours Maintenance'
	when  WOTypeId = 7  then 'Others' end) as WOType,u.UserName as GeneratedBy,
		(Case when  WarrantyorContract = 1  then 'Basic (bumper-to-bumper)'	 when  WarrantyorContract = 2  then 'Powertrain'	 when  WarrantyorContract = 3  then 'Corrosion'
	when  WarrantyorContract = 4  then 'Roadside assistance'	 when  WarrantyorContract = 5 then 'Not under warranty'	when  WarrantyorContract = 6  then 'Others'
	end) as WarrantyTxt,w.QuotationFile	 
	from rvlfWOGeneration w  
	inner join rvlfTyreVendorMaster Tv on Tv.VendorId = w.VendorId
	inner join rvlfuser u on u.UserId = w.CreatedBY	
	where w.WONo = @WONo   and W.IsDelete = 0 and W.OrganizationId=@bigOrganizationId

		select isnull(Remarks,'-') as Remarks,isnull(Username,'-') as RemarksBy,
		Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ApprovedDate)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ApprovedDate))AS TIME),22)  as  RemarksDate 
		from rvlfWOApproval WA
	inner join rvlfuser u on u.UserId = WA.ApprovedBy
	where WONo = @WONo   and IsDelete = 0 and WA.OrganizationId=@bigOrganizationId


  END                 
  -- If Operation is 'bind WO Generation'              
 ELSE IF (@Operation =3)               
  BEGIN                    
	select Distinct WOGenid,WONo,W.VehiclePlanId,
	(Case when  WOTypeId = 1  then 'Preventive Maintenance'	 when  WOTypeId = 2  then 'Regular Maintenance'	 when  WOTypeId = 3  then 'Corrective maintenance'
	when  WOTypeId = 4  then 'Predictive Maintenance'	 when  WOTypeId = 5 then 'Periodic maintenance'	when  WOTypeId = 6  then 'Zero Hours Maintenance'
	when  WOTypeId = 7  then 'Others' end) as WOType,	WOTypeId,w.VendorId,Replace(convert(varchar,StartDate,106),' ','-')  as StartDate,Replace(convert(varchar,EDC,106),' ','-') as EDC ,
	WarrantyorContract,Replace(convert(varchar,WarrantyEndDate,106),' ','-')  as WarrantyEndDate,
	AssignedTo,Remarks,(Case when w.Status = 1 then 'WO Generated'  when w.Status = 2 then 'WO Approved'  when w.Status = 3 then 'WO Redo'  
	when w.Status = 4 then 'WO Rejected'  when w.Status = 5 then 'WO Closed'  when w.Status = 6 then 'WO Reopened'  
      else '-'   end)  as [WOStatus] ,[Status],W.IsDelete,W.CreatedBY,
	  Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,W.CreatedDatetime)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,W.CreatedDatetime))AS TIME),22) as CreatedDatetime,
	  Tv.VendorName,u.UserName,Replace(convert(varchar,w.CreatedDatetime,106),' ','-')  as CreatedDatetime,
	(Case when GETUTCDATE() > w.StartDate  then 1 else 0 end)  as WOApprovalStatus,1 as WOApprovalStatus1,v.VehicleDescription,vp.PlanId,(Case when isnull(W.QuotationFile,0) ='0' then 0 else 1 end)  as QuotationFile
	 from rvlfWOGeneration w 
	inner join rvlfTyreVendorMaster Tv on Tv.VendorId = w.VendorId
	inner join rvlfuser u on u.UserId = w.CreatedBY	
  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = w.VehiclePlanId    
  inner join rvlfMaintenancePlan mp on  mp.PlanId = vp.PlanId
  Inner join rvlfVehicle v    on v.VehicleId = vp.VehicleId
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId         
	 where -- (w.WONo = @WONo or (@WONo is null) or (@WONo = ''))   and 
	  (fv.FleetId = @bigFleetId or (@bigFleetId is null) or (@bigFleetId = ''))   and  
	  (v.VehicleId = @bigVehicleId or (@bigVehicleId is null) or (@bigVehicleId = ''))   and  
	 (w.Status = @Status or (@Status is null) or (@Status = ''))   and  
	 (w.AssignedTo = @bigQueryingUser or (@bigQueryingUser is null) or (@bigQueryingUser = ''))   and  
	 W.IsDelete = 0 and W.OrganizationId=@bigOrganizationId
  END                        
  ELSE IF (@Operation = 4)   
  BEGIN
   declare @usergrp int
    set @usergrp=(SELECT g.UserGroupId FROM rvlfUserGroupAssignment ga     
    INNER JOIN rvlfUserGroup g ON ga.UserGroupId = g.UserGroupId    
    WHERE ga.UserId = @bigQueryingUser)    

    SELECT u.UserId,u.UserName,   dbo.rvlf_fn_GetUserGroupsByUserID(u.UserId) AS GroupBelongsTo
    FROM rvlfUser u LEFT OUTER JOIN rvlfUserPreferences p ON u.UserId=p.UserId    
    INNER JOIN rvlfUserGroupAssignment ga ON ga.UserId = u.UserId    
    INNER JOIN rvlfUserGroup g ON g.UserGroupId = ga.UserGroupId    
    INNER JOIN rvlfUserGroupSecurity UGS ON UGS.UserGroupId = g.UserGroupId
    WHERE           
		IsActive =1     AND  IsLocked = 0  AND
		 U.ISDELETE=0 AND 
		  IsHidden <>  (case when @usergrp = 1 then 2 else 1 end)
		AND OperationTypeId = 395 and ModuleId = 29
    ORDER BY UserName ASC     
  END 
 SET NOCOUNT OFF              
END   
  
  


GO
/****** Object:  StoredProcedure [dbo].[rvlt_sp_AddEditViewWOClosing]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[rvlt_sp_AddEditViewWOClosing]          
(               
   @Operation int =null,    
    @WOGenId bigint = null,                   
   @WONo bigint = null,      
    @ApprovedBy bigint= Null,
	 @ApprovedDate datetime=null,            
	 @StatusType int= Null,
	 @Remarks varchar(max) =NULL ,
	 @Status int = NULL  ,
	 @bigFleetId bigint = NULL,        
    @bigVehicleId bigint = NULL ,
	 @bigQueryingUser bigint = Null,
	 @bigOrganizationId bigint = Null    
   --@VehiclePlanId bigint=NULL,              
   --@WOTypeId bigint = 1,              
   --@VendorId bigint=NULL,              
   --@StartDate datetime=NULL,              
   --@EDC datetime=0,              
   --@WarrantyorContract bigint=null,              
   --@WarrantyEnddate datetime=null,            
   --@AssignedTo bigint = NULL,          
   --@Remarks varchar(max) =NULL,         
   --@CreatedBy bigint= Null,
   --@CreatedDateTime datetime = Null
)              
AS              
/****************************************************************************************************************/              
-- Name           : rvlt_sp_AddEditViewWOClosing     1,30,102,322,'11/30/2015 5:27:56 AM',3,'Ok Fine approved' 
-- Description    : To Add or Update or view the WO Approval
-- Author         : Ranjith N
-- Created Date   : 30-Nov-15              
/****************************************************************************************************************/              
BEGIN              
 SET NOCOUNT ON               

DECLARE @HoursToBeAdded INT = 0         
 DECLARE @MinsToBeAdded INT = 0                        
 DECLARE @DefaultDateFormat INT = 0           

    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                       
     @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                
               
 -- If Operation is 'Close or Reopen'              
 IF(@Operation =1)              
  BEGIN                 
   insert into rvlfWOClosure( WoGenId ,WONo,ClosedBy,ClosedDate,StatusType,Remarks,OrganizationId)
   values(@WoGenId ,@WONo,@ApprovedBy,@ApprovedDate,@StatusType,@Remarks,@bigOrganizationId)            
   update rvlfWOGeneration set [Status ]= @StatusType where WONo=@WONo and OrganizationId=@bigOrganizationId
  END              
 -- If Operation is 'View'              
 ELSE IF (@Operation =2)               
  BEGIN                    
	select WOGenid,WONo,VehiclePlanId,WOTypeId,W.VendorId,Replace(convert(varchar,StartDate,106),' ','-')  as StartDate,Replace(convert(varchar,EDC,106),' ','-') as EDC ,
	WarrantyorContract,Replace(convert(varchar,WarrantyEndDate,106),' ','-')  as WarrantyEndDate,Tv.VendorName,
	AssignedTo,Remarks,[Status],W.IsDelete,W.CreatedBY,W.CreatedDatetime ,
	(Case when  WOTypeId = 1  then 'Preventive Maintenance'	 when  WOTypeId = 2  then 'Regular Maintenance'	 when  WOTypeId = 3  then 'Corrective maintenance'
	when  WOTypeId = 4  then 'Predictive Maintenance'	 when  WOTypeId = 5 then 'Periodic maintenance'	when  WOTypeId = 6  then 'Zero Hours Maintenance'
	when  WOTypeId = 7  then 'Others' end) as WOType,u.UserName as GeneratedBy,
		(Case when  WarrantyorContract = 1  then 'Basic (bumper-to-bumper)'	 when  WarrantyorContract = 2  then 'Powertrain'	 when  WarrantyorContract = 3  then 'Corrosion'
	when  WarrantyorContract = 4  then 'Roadside assistance'	 when  WarrantyorContract = 5 then 'Not under warranty'	when  WarrantyorContract = 6  then 'Others'
	end) as WarrantyTxt,w. QuotationFile      
	from rvlfWOGeneration w  
	inner join rvlfTyreVendorMaster Tv on Tv.VendorId = w.VendorId
	inner join rvlfuser u on u.UserId = w.CreatedBY	
	where w.WONo = @WONo   and W.IsDelete = 0 and W.OrganizationId=@bigOrganizationId

		select isnull(Remarks,'-') as Remarks,isnull(Username,'-') as RemarksBy,
	Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ApprovedDate)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ApprovedDate))AS TIME),22)   as  RemarksDate 
	from rvlfWOApproval WA
	inner join rvlfuser u on u.UserId = WA.ApprovedBy
	where WONo = @WONo   and IsDelete = 0 and WA.OrganizationId=@bigOrganizationId
		union all
	select isnull(Remarks,'-') as Remarks,isnull(Username,'-') as RemarksBy,
	Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ClosedDate)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,ClosedDate))AS TIME),22)  as  RemarksDate 
	from rvlfWOClosure WC	
	inner join rvlfuser u on u.UserId = WC.ClosedBy
	where WC.WONo = @WONo   and IsDelete = 0 and WC.OrganizationId=@bigOrganizationId

  END                 
  -- If Operation is 'bind WO Generation'              
 ELSE IF (@Operation =3)               
  BEGIN                    
	select Distinct w.WOGenid,w.WONo,W.VehiclePlanId,
	(Case when  WOTypeId = 1  then 'Preventive Maintenance'	 when  WOTypeId = 2  then 'Regular Maintenance'	 when  WOTypeId = 3  then 'Corrective maintenance'
	when  WOTypeId = 4  then 'Predictive Maintenance'	 when  WOTypeId = 5 then 'Periodic maintenance'	when  WOTypeId = 6  then 'Zero Hours Maintenance'
	when  WOTypeId = 7  then 'Others' end) as WOType,	WOTypeId,w.VendorId,Replace(convert(varchar,StartDate,106),' ','-')  as StartDate,Replace(convert(varchar,EDC,106),' ','-') as EDC ,
	WarrantyorContract,Replace(convert(varchar,WarrantyEndDate,106),' ','-')  as WarrantyEndDate,
	AssignedTo,W.Remarks,(Case when w.Status = 1 then 'WO Generated'  when w.Status = 2 then 'WO Approved'  when w.Status = 3 then 'WO Redo'  
	when w.Status = 4 then 'WO Rejected'  when w.Status = 5 then 'WO Closed'  when w.Status = 6 then 'WO Reopened'  
      else '-'   end)  as [WOStatus] ,[Status],W.IsDelete,W.CreatedBY,
	  Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,W.CreatedDatetime)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,W.CreatedDatetime))AS TIME),22)  as CreatedDatetime,
	  Tv.VendorName,u.UserName,Replace(convert(varchar,w.CreatedDatetime,106),' ','-')  as CreatedDatetime,
	(Case when GETUTCDATE() > w.EDC  then 1 else 0 end)  as WOClosedStatus,1 as WOApprovalStatus1,v.VehicleDescription,vp.PlanId,
	(Select  top 1  u1.UserName from rvlfWOApproval WA1	inner join rvlfuser u1 on WA1.ApprovedBy = u1.UserId 
	 where WA1.WONo = W.WONo and WA1.OrganizationId=@bigOrganizationId  order by ApprovedDate desc ) as ApprovedBy
	,(Select  top 1  Replace(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,WA1.ApprovedDate)),106),' ','-')+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,WA1.ApprovedDate))AS TIME),22)  
	 from rvlfWOApproval WA1	 
	 where WA1.WONo = W.WONo and WA1.OrganizationId=@bigOrganizationId  order by ApprovedDate desc ) as ApprovedDate,
	 (Case when isnull(W.QuotationFile,0) ='0' then 0 else 1 end)  as QuotationFile	 
	 from rvlfWOGeneration w	
	inner join rvlfTyreVendorMaster Tv on Tv.VendorId = w.VendorId
	inner join rvlfuser u on u.UserId = w.CreatedBY		
  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = w.VehiclePlanId    
  inner join rvlfMaintenancePlan mp on  mp.PlanId = vp.PlanId
  Inner join rvlfVehicle v    on v.VehicleId = vp.VehicleId
  INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId         
	 where -- (w.WONo = @WONo or (@WONo is null) or (@WONo = ''))   and 
	  (fv.FleetId = @bigFleetId or (@bigFleetId is null) or (@bigFleetId = ''))   and  
	  (v.VehicleId = @bigVehicleId or (@bigVehicleId is null) or (@bigVehicleId = ''))   and  
	 (w.Status = @Status or (@Status is null) or (@Status = ''))   and   w.Status in (2,5,6) and
	 (w.WONo in (Select distinct WONo from rvlfWOApproval where AssignedTo = @bigQueryingUser)  or (@bigQueryingUser is null) or (@bigQueryingUser = ''))   and  
	  W.IsDelete = 0 and W.OrganizationId=@bigOrganizationId
  END                         
 SET NOCOUNT OFF              
END   
  

GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_AddGeozone_coordinates]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_AddGeozone_coordinates]
(
	@geozoneNo int,
	@geoName varchar(200),
	@geodesc varchar(2000),
	@number int,
	@latitude varchar(20),
	@longitude varchar(20)
)
AS
BEGIN

 DECLARE @isExist int
 DECLARE @Maxvalue int            
 SET @isExist  = (select count(*)  from rvlfOrganizationGeozone where GeozoneNo = @geozoneNo)          
          
 IF(@isExist >= 1)          
  BEGIN          
   Update rvlfOrganizationGeozone SET GeozoneName = @geoName,Description = @geodesc where GeozoneNo = @geozoneNo          
             
   delete from rvlfGeozoneset where geozoneNo = @geozoneNo             
   -- added by Christopher S for identifying GeoZoneNo on 31-Aug-09      
   SET @Maxvalue = (select @geozoneNo)  
  select @Maxvalue as Maxvalue    
   --INSERT INTO rvlfGeozoneSet Values(@geozoneNo, @number ,@latitude ,@longitude)            
             
  END          
 ELSE          
  BEGIN             
   SET @Maxvalue = (select ISNULL(Max(Geozoneno),0) from rvlfOrganizationGeozone)            
   -- added by Christopher S for identifying GeoZoneNo on 31-Aug-09      
   select @Maxvalue as Maxvalue          
   -- commented by Christopher S on 31-Aug-09      
   --INSERT INTO rvlfGeozoneSet Values(@Maxvalue, @number ,@latitude ,@longitude)            
  END          
            
END


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_EditorDeleteGeozones]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_EditorDeleteGeozones](@geozoneid int,@editType int, @viewType int)                
as                
BEGIN                
        
DECLARE @GeoId INT,@OrgId INT;      
SELECT @GeoId = GeozoneId,@OrgId = OrganizationId FROM rvlfOrganizationGeozone WHERE GeozoneNo = @geozoneid      
        
If(@editType = 1 AND @viewType = 1)                
  BEGIN                 
     SELECT G.GeozoneNo,G.OrganizationId,GeozoneId,GeozoneName,Description,Email,SMS,TimeZone,SeverityId,Direction,Notify,Warning,Critical,GS.Latitude,GS.Longitude,C.CategoryId,                
     CASE WHEN g.Direction= 0 THEN '00' WHEN g.Direction = 1 THEN '10'                 
     WHEN g.Direction = 2 THEN '01' WHEN g.Direction = 3 THEN '11' END as ZoneDirection,          
               
  ISNULL(dbo.rvlf_fn_GetNotificationsList(1, g.GeozoneNo, 1,1,0),'') as EmailList,           
  ISNULL(dbo.rvlf_fn_GetNotificationsList(1,g.GeozoneNo, 0,1,0),'') as SMSList,          
              
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1, g.GeozoneNo, 1,0,1),''),',',', ') as EmailUserNameList,          
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1,  g.GeozoneNo, 0,0,1),''),',',', ') as SMSUserNameList          
        ,G.LandmarkID  ,ISNULL(Radius,0) as Radius  ,G.GeozoneType ,case when G.GeozoneType=3 then 'W41' else 'Z' end as Cmd     
     from rvlfOrganizationGeozone G inner join rvlfGeozoneset GS on G.GeozoneNo = GS.GeozoneNO            
     inner join rvlfCategory C on C.CategoryId = G.CategoryId              
     where GS.GeozoneNo = @geozoneid order by CASE WHEN GeozoneType = 1 THEN Latitude END desc,                
     CASE WHEN GeozoneType = 2 THEN SequenceNo END                 
                 --order by GS.SequenceNo                            
  END              
ELSE IF(@editType = 1 AND @viewType = 0)             
 BEGIN             
   DECLARE @GeoZone int          
         
   IF EXISTS(SELECT GeozoneNo from rvlfVehicleGeozone VG INNER JOIN       
   rvlfVehicle V ON VG.VehicleId = V.VehicleId WHERE V.OrganizationId = @OrgId AND VG.GeozoneNo = @GeoId)      
             
   --SET @GeoZone = (SELECT COUNT(*) from rvlfVehicleGeozone where GeozoneNo = @GeoId )      
   --If(@GeoZone>=1)               
    BEGIN              
     SELECT @GeoZone as VehicleGeoZoneCount, G.GeozoneNo, G.OrganizationId, G.GeozoneId, G.GeozoneName,G.GeozoneType,G.Description,G.Email,G.SMS,G.TimeZone,G.SeverityId,G.Direction,G.Notify,G.Warning,G.Critical,C.CategoryId,          
     CASE WHEN G.Direction= 0 THEN '00' WHEN G.Direction = 1 THEN '10'                 
      WHEN G.Direction = 2 THEN '01' WHEN G.Direction = 3 THEN '11' END as ZoneDirection,          
       ISNULL(dbo.rvlf_fn_GetNotificationsList(1, g.GeozoneNo, 1,1,0),'') as EmailList,           
  ISNULL(dbo.rvlf_fn_GetNotificationsList(1,g.GeozoneNo, 0,1,0),'') as SMSList,          
              
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1, g.GeozoneNo, 1,0,1),''),',',', ') as EmailUserNameList,          
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1,  g.GeozoneNo, 0,0,1),''),',',', ') as SMSUserNameList, GS.Latitude,GS.Longitude            
    ,G.LandmarkID  ,ISNULL(Radius,0) as Radius,case when G.GeozoneType=3 then 'W41' else 'Z' end as Cmd    
     from rvlfOrganizationGeozone G          
     inner join rvlfGeozoneset GS on G.GeozoneNo = GS.GeozoneNO           
     inner join rvlfCategory C on C.CategoryId = G.CategoryId            
     where g.GeozoneNo = @geozoneid              
    END                
      ELSE              
    BEGIN            
     SELECT G.GeozoneNo,G.OrganizationId,GeozoneId,GeozoneName,Description,Email,SMS,TimeZone,SeverityId,Direction,Notify,Warning,Critical,GS.Latitude,GS.Longitude,C.CategoryId,                
     CASE WHEN g.Direction= 0 THEN '00' WHEN g.Direction = 1 THEN '10'                 
      WHEN g.Direction = 2 THEN '01' WHEN g.Direction = 3 THEN '11' END as ZoneDirection,          
       ISNULL(dbo.rvlf_fn_GetNotificationsList(1, g.GeozoneNo, 1,1,0),'') as EmailList,           
  ISNULL(dbo.rvlf_fn_GetNotificationsList(1,g.GeozoneNo, 0,1,0),'') as SMSList,          
              
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1, g.GeozoneNo, 1,0,1),''),',',', ') as EmailUserNameList,          
  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1, g.GeozoneNo, 0,0,1),''),',',', ') as SMSUserNameList          
            ,G.LandmarkID ,ISNULL(Radius,0)  as Radius,G.GeozoneType,case when G.GeozoneType=3 then 'W41' else 'Z' end as Cmd         
      from rvlfOrganizationGeozone G inner join rvlfGeozoneset GS on G.GeozoneNo = GS.GeozoneNO           
      inner join rvlfCategory C on C.CategoryId = G.CategoryId                 
      where GS.GeozoneNo = @geozoneid order by CASE WHEN GeozoneType = 1 THEN Latitude END desc,                
       CASE WHEN GeozoneType = 2 THEN SequenceNo END                 
      --order by GS.SequenceNo                 
      END            
END                  
ELSE IF(@editType = 0 AND @viewType = 0)                
  BEGIN                 
   DECLARE @VehicleGeoZone int  ,@VehicleGeoZoneroute int            
   --SET @VehicleGeoZone = (SELECT COUNT(*) from rvlfVehicleGeozone where GeozoneNo = @GeoId)                  
   SET @VehicleGeoZone = (SELECT GeozoneNo from rvlfVehicleGeozone VG INNER JOIN       
   rvlfVehicle V ON VG.VehicleId = V.VehicleId WHERE V.OrganizationId = @OrgId AND VG.GeozoneNo = @GeoId)      
   --comments for unable to delete geozone recoded for route wiht seprate variable below line 12-feb-16
SET @VehicleGeoZoneroute = (select COUNT(*) from rvlfRouteDetails a inner join rvlfOrganizationGeozone b on a.LndID=b.GeozoneId
where b.GeozoneNo=@geozoneid)   
   If(@VehicleGeoZone>=1 or @VehicleGeoZoneroute>=1)             
    BEGIN              
    SELECT @VehicleGeoZone as VehicleGeoZoneCount,@VehicleGeoZoneroute as VehicleGeoZoneroute               
    END          
    ELSE          
    BEGIN          
   DELETE FROM rvlfNotificationList WHERE NotificationType = 1  AND TypeID = @geozoneid          
   DELETE from rvlfGeozoneset where GeozoneNo = @geozoneid          
   DELETE from rvlfOrganizationGeozone where GeozoneNo = @geozoneid          
       END                 
  END                
END                
           
-- RVLT_SP_EditorDeleteGeozones 1319, 0, 0 

 


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_EditorDeleteLandMarks]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_EditorDeleteLandMarks]
(
	@LandmarkId varchar(10),@type int
)
AS
/******************************************************************************/
--	Name		:	[RVLT_SP_EditorDeleteLandMarks]281,1
--	Description	:	To select or delete the landmarks
--	Author		:	T. Sathish Kumar
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	Sathish		Created Intial Version 
--				:	18-Sep-2009 Jaya Chitra Added the notificaiton listing retrieval
/******************************************************************************/
BEGIN
		-- Type 0 DELETE, Type 1 Edit
		if(@type = 1)
			BEGIN
				SELECT L.*,LC.ImagePath ,
					ISNULL(dbo.rvlf_fn_GetNotificationsList(2, LandmarkID, 1,1,0),'') as EmailList, 
					ISNULL(dbo.rvlf_fn_GetNotificationsList(2, LandmarkID, 0,1,0),'') as SMSList,
    
					REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(2, LandmarkID, 1,0,1),''),',',', ') as EmailUserNameList,
					REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(2, LandmarkID, 0,0,1),''),',',', ') as SMSUserNameList 
				FROM rvlfLandMark L
					LEFT OUTER JOIN rvlfLandmarkCategory LC ON LC.LandmarkCategoryID =L.LandmarkCategoryID 
				
				where LandMarkId = @LandmarkId
			END
		ELSE
			BEGIN
				DELETE FROM rvlfNotificationList WHERE NotificationType=2 and TypeID = @LandmarkId
				Delete from rvlfLandMark where LandMarkId = @LandmarkId
			END
END


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetAlarms]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_GetAlarms]    
(
	@bigQueryingUser bigint = 0        
)
as            
BEGIN  

------- Included by Kumuthini on 16-July-09 ---------------------
	
	DECLARE @HoursToBeAdded INT = 0
	DECLARE @MinsToBeAdded INT = 0
	
	DECLARE @ConversionFactor numeric (10,2) = 1.0
	
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,
		   @ConversionFactor = CASE WHEN up.Distance = 0 THEN 1.6 ELSE 1.0 END 
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser
	
	--------------------------------   
	          
 Select AlarmID,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,DateTimeCreated)) as [DateTime],AlarmType,BoxID,[Description] as Description,IsClosed  
 --CASE  WHEN AcceptedBy IS NULL THEN 0   
 --WHEN AcceptedBy IS Not NULL AND ClosedBy IS NULL THEN 1  
 --WHEN AcceptedBy IS Not NULL AND ClosedBy IS Not NULL THEN 2 END AS IsClosed   
 from rvlfAlarm WHERE ISClosed <> 2           
END


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetAlarmsByID]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_GetAlarmsByID](@alarmID int,@bigQueryingUser bigint = 0)
AS
BEGIN
	------- Included by Kumuthini on 16-July-09 ---------------------
	
	DECLARE @HoursToBeAdded INT = 0
	DECLARE @MinsToBeAdded INT = 0
	
	DECLARE @ConversionFactor numeric (10,2) = 1.0
	
    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,
		   @ConversionFactor = CASE WHEN up.Distance = 0 THEN 1.6 ELSE 1.0 END 
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser
	
	--------------------------------   
	select AlarmId,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,DateTimeCreated)) as DateTimeCreated,BoxId,
	AlarmType,AlarmLevelId,Description,StreetAddress,IsClosed from rvlfAlarm where AlarmID = @alarmID
END
-- RVLT_SP_GetAlarmsByID 1,1


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetAllGeozones]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_GetAllGeozones](@OrgID varchar(10))
as      
BEGIN 
Declare @GeoType varchar(10)='2'
SELECT @GeoType= coalesce(@GeoType + ', ', '') + case when a.OperationID =414 then '1' when a.OperationID=415 then '3' end
FROM (select OperationID from rvlfOrganizationPackage op inner join rvlfPackageOperations po on op.PackageId=po.PackageId
where po.OperationID in (414,415) and OrganizationID=@OrgID and IsActive=1) a
     
	SELECT geo.OrganizationId,geo.GeozoneNo,geo.GeozoneId,geo.GeozoneName,geo.Description,
	   geo.Email,tz.TimeZoneName AS 'TimeZone',geo.GeozoneType,rs.AlarmLevelName as Severity,
	   CASE WHEN EXISTS(SELECT vg.GeozoneNo  FROM rvlfVehicleGeozone vg WHERE vg.GeozoneNo = geo.GeozoneNo)
		THEN 1 ELSE 0 END AssignedStatus,
		ISNULL(dbo.rvlf_fn_GetNotificationsList(1, geo.GeozoneNo, 1,1,0),'') as EmailList, 
		ISNULL(dbo.rvlf_fn_GetNotificationsList(1,geo.GeozoneNo, 0,1,0),'') as SMSList,
    
		REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1, geo.GeozoneNo, 1,0,1),''),',',', ') as EmailUserNameList,
		REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1,  geo.GeozoneNo, 0,0,1),''),',',', ') as SMSUserNameList, 
		geo.CategoryId,c.CategoryName
FROM rvlfOrganizationGeozone geo 
INNER JOIN rvlfTimeZones tz ON geo.TimeZone = tz.TimeZoneID
INNER JOIN rvlfSeverity rs ON rs.AlarmLevelId = geo.SeverityId
INNER JOIN rvlfCategory c ON c.CategoryId = geo.CategoryId 
WHERE  geo.OrganizationId = @OrgID  and geo.GeozoneType in ((select * from rvlf_fn_ConvertArrayToTable(@GeoType,','))) order by Timezone    
END


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetAllGeozones_New]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_GetAllGeozones_New](@OrgID varchar(10),@bigQueryingUser BIGINT)      
as            
BEGIN        
DECLARE @Lang varchar(50) 

DECLARE @Tempvariable table(CountAssign int,GeozoneNo int)

INSERT INTO @Tempvariable
SELECT COUNT(vg.VehicleId),geo.GeozoneNo 
FROM	rvlfOrganizationGeozone geo 
INNER	JOIN rvlfVehicleGeozone VG on geo.GeozoneId = VG.GeozoneNo      
INNER	JOIN rvlfVehicle v on VG.VehicleId=v.VehicleId and v.OrganizationId = geo.OrganizationId where geo.OrganizationId=@OrgID 
GROUP	BY geo.GeozoneNo

Declare @GeoType varchar(10)='2'
SELECT @GeoType= coalesce(@GeoType + ', ', '') + case when a.OperationID =414 then '1' when a.OperationID=415 then '3' end
FROM (select OperationID from rvlfOrganizationPackage op inner join rvlfPackageOperations po on op.PackageId=po.PackageId
where po.OperationID in (414,415) and OrganizationID=6 and IsActive=1) a
                                               
--SELECT @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser         
-- SELECT geo.OrganizationId,geo.GeozoneNo,geo.GeozoneId,geo.GeozoneName,geo.Description,      
--    geo.Email,tz.TimeZoneName AS 'TimeZone',geo.GeozoneType,(case when @Lang='LanguageArNew' then isnull(rs.AlarmLevelName_Ar,rs.AlarmLevelName) when @Lang='LanguageHindi' then isnull(rs.AlarmLevelName_Hin ,rs.AlarmLevelName) ELSE rs.AlarmLevelName END)as
-- Severity, (select count(v.VehicleID) as AssignedVehicles
--   FROM rvlfVehicle v                 
--   INNER JOIN rvlfVehicleAssignment va ON v.VehicleID = va.VehicleId                            
--   INNER JOIN rvlfBoxSettings bs ON bs.BoxId = va.BoxId           
--   INNER JOIN rvlfFirmware F ON F.FwID = bs.FwID              
--   INNER JOIN rvlfVehicleGeozone VG on VG.VehicleId=v.VehicleId 
--   where VG.GeozoneNo = geo.GeozoneId and v.OrganizationId = @OrgID) as AssignedVehicles,
--  CASE WHEN EXISTS(SELECT vg.GeozoneNo  FROM rvlfVehicleGeozone vg WHERE vg.GeozoneNo = geo.GeozoneNo) THEN 1 ELSE 0 END AssignedStatus,      
--  ISNULL(dbo.rvlf_fn_GetNotificationsList(1, geo.GeozoneNo, 1,1,0),'') as EmailList,       
--  ISNULL(dbo.rvlf_fn_GetNotificationsList(1,geo.GeozoneNo, 0,1,0),'') as SMSList,           
--  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1, geo.GeozoneNo, 1,0,1),''),',',', ') as EmailUserNameList,      
--  REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1,  geo.GeozoneNo, 0,0,1),''),',',', ') as SMSUserNameList,       
--  geo.CategoryId,c.CategoryName ,ISNULL(geo.Radius,0) AS Radius,
--  latlng = STUFF((SELECT '~' + cast(Latitude as varchar)+'#' + cast(Longitude as varchar)
--FROM rvlfGeozoneSet b WHERE b.GeozoneNo = geo.GeozoneNo FOR XML PATH('')), 1, 1, ''),
--  Case when GeozoneType=1 then 'Rectangle' when GeozoneType=2 then 'Polygon' when GeozoneType=3 then 'Circular' End as GeozoneTypeName   
--FROM rvlfOrganizationGeozone geo       
--INNER JOIN rvlfTimeZones tz ON geo.TimeZone = tz.TimeZoneID      
--INNER JOIN rvlfSeverity rs ON rs.AlarmLevelId = geo.SeverityId      
--INNER JOIN rvlfCategory c ON c.CategoryId = geo.CategoryId       
--WHERE  geo.OrganizationId = @OrgID  and GeozoneType in ((select * from rvlf_fn_ConvertArrayToTable(@GeoType,',')))
--order by Timezone

SELECT @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigQueryingUser           
	SELECT geo.OrganizationId,geo.GeozoneNo,geo.GeozoneId,geo.GeozoneName,geo.Description,        
	geo.Email,tz.TimeZoneName AS 'TimeZone',geo.GeozoneType,
	(case when @Lang='LanguageArNew' then isnull(rs.AlarmLevelName_Ar,rs.AlarmLevelName) when @Lang='LanguageHindi' then isnull(rs.AlarmLevelName_Hin ,rs.AlarmLevelName) ELSE rs.AlarmLevelName END)
	as Severity,ISNULL(tv.CountAssign,0) as AssignedVehicles,case when ISNULL(tv.CountAssign,0)>0 then 1 else 0 end as AssignedStatus,
	--CASE WHEN EXISTS(SELECT vg.GeozoneNo  FROM rvlfVehicleGeozone vg WHERE vg.GeozoneNo =geo.GeozoneId)        
	--THEN 1 ELSE 0 END AssignedStatus,        
	ISNULL(dbo.rvlf_fn_GetNotificationsList(1, geo.GeozoneNo, 1,1,0),'') as EmailList,         
	ISNULL(dbo.rvlf_fn_GetNotificationsList(1,geo.GeozoneNo, 0,1,0),'') as SMSList,             
	REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1, geo.GeozoneNo, 1,0,1),''),',',', ') as EmailUserNameList,        
	REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(1,  geo.GeozoneNo, 0,0,1),''),',',', ') as SMSUserNameList,         
	geo.CategoryId,c.CategoryName ,ISNULL(geo.Radius,0) AS Radius,
	latlng = STUFF((SELECT '~' + cast(Latitude as varchar)+'#' + cast(Longitude as varchar)
FROM rvlfGeozoneSet b WHERE b.GeozoneNo = geo.GeozoneNo FOR XML PATH('')), 1, 1, ''),
	Case when GeozoneType=1 then 'Rectangle' when GeozoneType=2 then 'Polygon' when GeozoneType=3 then 'Circular' End as GeozoneTypeName
FROM rvlfOrganizationGeozone geo 	
INNER JOIN rvlfTimeZones tz ON geo.TimeZone = tz.TimeZoneID        
INNER JOIN rvlfSeverity rs ON rs.AlarmLevelId = geo.SeverityId  
left JOIN @Tempvariable tv on tv.GeozoneNo=geo.GeozoneNo   
INNER JOIN rvlfCategory c ON c.CategoryId = geo.CategoryId     	
WHERE  geo.OrganizationId = @OrgID and GeozoneType in ((select * from rvlf_fn_ConvertArrayToTable(@GeoType,',')))
order by Timezone       
	          
END 




GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetChildList_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RVLT_SP_GetChildList_PhoneGap]    
(                
@bigQueryingUser bigint = 0
)                  
as                 
/******************************************************************************/                      
-- Name  : RVLT_SP_GetChildList_PhoneGap 5
-- Description : Get Child List for the parent              
-- Author  : N.Ranjith               
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
/******************************************************************************/                                         
Begin                  
   Select * from rvlfStudentMaster s 
   inner join rvlfParentMaster p on p.MobileNo =s.ContactNo
   where p.UserId = @bigQueryingUser
End 

GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetFleetByCustomerID]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_GetFleetByCustomerID]
(
	@orgID varchar(50) = null, -- 0 for the angler admin
	@CustomerID bigint = null 
)    
AS     
--RVLT_SP_GetFleetByCustomerID 86,37
	BEGIN     
   
		SELECT distinct F.* FROM rvlfFleet F
		inner join rvlfFleetVehicles FV on f.FleetId=fv.FleetId
		inner join rvlfMAKDevices MD on fv.VehicleId=md.VehicleId
		WHERE (@orgID IS NULL OR @orgID = 0 OR @orgID = '' OR  F.OrganizationId = @orgID) and  
		 (@CustomerID IS NULL OR @CustomerID = 0 OR @CustomerID = '' OR  md.CustomerId = @CustomerID)   
  
	END
GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetFleetByOrgID]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[RVLT_SP_GetFleetByOrgID]
(
	@orgID varchar(50) = null -- 0 for the angler admin
)    
AS     
	BEGIN     
   
		SELECT * FROM rvlfFleet 
		WHERE (@orgID IS NULL OR @orgID = 0 OR @orgID = '' OR  OrganizationId = @orgID)   
  
	END
	
-- RVLT_SP_GetFleetByOrgID '1'


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLandMarks]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_GetLandMarks]          
 @bigOrganizationID bigint = null, -- 0 for the angler admin          
 @bigCategoryID bigint=null,          
 @bigBranchId bigint = null          
AS          
/******************************************************************************/          
-- Name  : [RVLT_SP_GetLandMarks] 51          
-- Description : To get the landmarks          
-- Author  : T. Sathish Kumar          
-- Company  : Angler Technologies          
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason          
--    : Sathish  Created Intial Version           
--              :   10-Sep-2009 Jaya Chitra Had the Organization Check          
--    : 18-Sep-2009 Jaya Chitra Added the notificaiton listing retrieval          
--              :   06-Feb-2010 Kumuthini   Included the Landmark Type          
--    : 08-Feb-2010 Jaya Chitra Added the category retrieval          
--    : 03-Mar-2011  VN Included the category          
--    : 01-Feb-2012  Vijay Included IsAbleToDelete.      
/******************************************************************************/          
BEGIN          
SELECT m.LandMarkId,m.LandMarkName,m.Description,m.Latitude,m.Longitude,m.StreetAddress,m.Radius,m.Email,          
 m.LandmarkType,           
 case when m.Notify='true' then 'Notify'              
  when m.Warning='true' then 'Warning'          
  when m.Critical='true' then 'Critical' else 'No Alarm' end as Severity,          
            
 ISNULL(dbo.rvlf_fn_GetNotificationsList(2, m.LandmarkID, 1,1,0),'') as EmailList,           
 ISNULL(dbo.rvlf_fn_GetNotificationsList(2, m.LandmarkID, 0,1,0),'') as SMSList,          
              
 REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(2, m.LandmarkID, 1,0,1),''),',',', ') as EmailUserNameList,          
 REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(2, m.LandmarkID, 0,0,1),''),',',', ') as SMSUserNameList,          
 cast(m.Latitude as varchar) + ',' + cast(m.Longitude as varchar) as LatLng,          
 c.LandmarkCategoryID, c.CategoryName, c.Description as CategoryDesc, c.ImagePath,      
   CASE WHEN EXISTS (Select LndID From rvlfRouteDetails WHERE LndID = m.LandmarkID)      
   THEN 0      
   ELSE 1      
   END AS IsAbleToDelete      
from rvlfLandMark m LEFT OUTER JOIN rvlfLandmarkCategory c ON m.LandmarkCategoryID = c.LandmarkCategoryID          
 WHERE (@bigOrganizationID IS NULL OR @bigOrganizationID='' OR @bigOrganizationID = 0 OR m.OrganizationId = @bigOrganizationID)          
  AND(@bigBranchId IS NULL OR @bigBranchId='' OR @bigBranchId=0 OR M.OrganizationId=@bigBranchId)          
  AND (@bigCategoryID IS NULL OR @bigCategoryID='' OR M.LandmarkCategoryID=@bigCategoryID)        
  order by m.LandmarkName      
  
Select ISNULL(COUNT(LandmarkID),0) as LandmarksCreated, NoOfLandmarks as AllowedCount,    
CASE WHEN ISNULL(COUNT(LandmarkID),0) >=(ISNULL(NoOfLandmarks,0)) THEN '0' ELSE '1' END as IsAllowed    
from rvlfOrganization O inner JOIN rvlfLandmark L on O.OrganizationId = L.OrganizationId     
where L.OrganizationId = @bigOrganizationId    
group by O.NoOfLandmarks    
         
END 

GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLat]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- [RVLT_SP_GetLat] '8','2009-07-30','2009-08-05',30,'desc',0
CREATE procedure [dbo].[RVLT_SP_GetLat]                              
(
	@startdate as datetime,
	@enddate datetime,                              
    --@interval as int,
    @MessageType as int = 1,
    @startRowIndex as int = 0,
    @maximumRows as int = 5,
    @totalRows as int OUTPUT,
    @sortColumn as varchar(25) = 'AutoId',
    @orderby varchar(10) = 'ASC',
    @bigQueryingUser bigint = 0
)                              
                              
as                              
Begin    

	------- Included by Kumuthini on 16-July-09 ---------------------
	
	DECLARE @HoursToBeAdded INT = 0
	DECLARE @MinsToBeAdded 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 
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser
	
	--------------------------------
	
	-------------------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))
	----------------------------------------------------------------------------------------------------------
	

    DECLARE @MainQry AS VARCHAR(Max) = ''
    DECLARE @CondQry AS VARCHAR(200) = ''
    
    SET @CondQry = (CASE 
                    WHEN @MessageType = 0 THEN '1 = 1' 
		            WHEN @MessageType = 1 THEN 'GPS.MessageInID IS NOT NULL' 
		            WHEN @MessageType = 2 THEN 'GPS.MessageInID IS NULL' 
		            WHEN @MessageType = 3 THEN 'GPS.MessageInID IS NOT NULL AND (GPS.BoxMsgInTypeID = 11 OR GPS.BoxMsgInTypeID = 27)'
                    END) 
    
   CREATE table #GPSData (AutoId bigint identity(1,1) not null, MessageInID uniqueidentifier,DeviceID int,ValidGPS tinyint,Latitude decimal(14,6),Longitude decimal(14,6),
       Distance varchar(300),Speed varchar(150),Direction varchar(100),Heading smallint,Timestamp DateTime,VehicleDescription varchar(250),Message varchar(50),
       BoxMsgInTypeId tinyint,MessageDetails varchar(250),UserID bigint,Priority tinyint,Acknowledged bit,Address varchar(250))                                
   
   SET @MainQry = @MainQry + 'SELECT * FROM (select distinct(H.MessageInID), VA.BoxID as DeviceID, ValidGPS, cast(H.Latitude as decimal(14,6)) as Latitude, cast(H.Longitude as decimal(14,6)) as Longitude,                
    H.NearestLandMark as Distance, 
    CAST((CAST(Speed as int) * ' + CAST(@ConversionFactor as varchar) + ') as varchar) + CASE WHEN ' + CAST(@ConversionFactor as varchar) + ' = 0.62 THEN '' MPH'' ELSE '' KMPH'' END as Speed, 
    CASE 
				WHEN H.ValidGps > 1 OR H.BoxMsgInTypeId IN (9, 14,15,16,17,24) then ''-''
				WHEN H.Heading between 335 and 360 THEN ''N'' 
				 WHEN H.Heading between 0 and 25 THEN ''N'' 
				WHEN H.Heading between 25 and 65 THEN ''NE'' 
				WHEN H.Heading between 65 and 115 THEN ''E'' 
				WHEN H.Heading between 115 and 155 THEN ''SE'' 
				WHEN H.Heading between 155 and 210 THEN ''S'' 
				WHEN H.Heading between 210 and 245 THEN ''SW'' 
				WHEN H.Heading between 245 and 300 THEN ''W'' 
				WHEN H.Heading between 300 and 335 THEN ''NW'' ELSE ''-'' END as Direction,
    Heading, DateAdd(n,' + CAST(@MinsToBeAdded as varchar) + ',DateAdd(hh,' + CAST(@HoursToBeAdded as varchar) + ',OriginDateTime)) as [Timestamp], 
    VehicleDescription, BoxMsgInTypeName as Message, H.BoxMsgInTypeId as BoxMsgInTypeId ,
   CASE WHEN H.BoxMsgInTypeID in (11 , 2 , 3 , 13 , 9 , 14 , 15 , 16 , 17 , 24 , 18)
				THEN dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId )
				WHEN H.BoxMsgInTypeId IN (5,6) THEN
					dbo.rvlf_fn_GetAlarmDetails(CAST( SUBSTRING(H.CustomProp,
					CHARINDEX(''='',H.CustomProp,1)+1,(CHARINDEX('';'',H.CustomProp,1)
					- CHARINDEX(''='',H.CustomProp,1))-1) as bigint), H.BoxMsgInTypeId,H.BoxId ) 
			ELSE CT.BoxMsgInTypeDesc 
			END as MessageDetails,	
				0 as UserID,0 as Priority,NULL as Acknowledged, case WHEN (H.LandMarkID IS NULL or H.LandMarkID = 0) THEN H.StreetAddress ELSE L.LandmarkName END as Address
from rvlfMsgInHst H LEFT OUTER JOIN rvlfLandmark L on H.LandMarkID = L.LandmarkID INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = H.BoxID         
    INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID          
    INNER JOIN rvlfBoxMsgInType CT on CT.BoxMsgInTypeId = H.BoxMsgInTypeID   
    where OriginDateTime between CONVERT(varchar(35),''' + CAST(@startdate as varchar) + ''',109)  and CONVERT(varchar(35),''' + CAST(@enddate as varchar) + ''',109)    
    and H.BoxMsgInTypeID NOT in (/*19,*/20,35,34,31) 
    UNION ALL    
		select  NULL as MessageInID,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'''' as Distance,'''' as Speed, ''-'' as Direction, 0 as Heading,
		DateAdd(n,' + CAST(@MinsToBeAdded as varchar) + ',DateAdd(hh,' + CAST(@HoursToBeAdded as varchar) + ',SentDateTime)) as [Timestamp], 
		V.VehicleDescription,''Command'' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId ,BoxcmdTypeDesc as MessageDetails,UserID,Priority,Acknowledged,''N/A'' as Address --into #tblFinal    
		from rvlfMsgOutHst OH        
		INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID        
		INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId     
	    WHERE SentDateTime Between CONVERT(varchar(35),''' + CAST(@startdate as varchar) + ''',109) and CONVERT(varchar(35),''' + CAST(@enddate as varchar) + ''',109)
		)as GPS ' 
		
		--WHERE ' + @CondQry
		
		--where VA.VehicleId = ''' + CAST(@VehicleID as varchar) + ''' and OriginDateTime between CONVERT(varchar(35),''' + CAST(@startdate as varchar) + ''',109)  and CONVERT(varchar(35),''' + CAST(@enddate as varchar) + ''',109)    
		--WHERE VA.VehicleID =  ''' + CAST(@VehicleID as varchar) + ''' and SentDateTime Between CONVERT(varchar(35),''' + CAST(@startdate as varchar) + ''',109) and CONVERT(varchar(35),''' + CAST(@enddate as varchar) + ''',109)
    --print(@MainQry)
		  
	INSERT INTO #GPSData EXEC(@MainQry)
	
-- PAGING

DECLARE @first_id int, @startRow int
DECLARE @SQL AS varchar(200) = ''
CREATE Table #Temp(AutoId bigint not null)

SET @startRowIndex =  @startRowIndex + 1

IF @startRowIndex = 0 
   SET @startRowIndex = 1
   
IF @maximumRows = 0 
   SET @maximumRows = 5

SET ROWCOUNT @startRowIndex

SET @SQL = 'SELECT AutoId FROM #GPSData ORDER BY ' + @sortColumn + ' ' + @orderby

INSERT INTO #Temp EXEC(@SQL)

SELECT @first_id = AutoId FROM #Temp

DROP TABLE #Temp

SET ROWCOUNT @maximumRows

SET @SQL = 'SELECT * FROM #GPSData WHERE AutoId >= ' + CAST(@first_id AS VARCHAR(10)) + ' ORDER BY ' + @sortColumn + ' ' + @orderby
EXEC(@SQL)
 
SET ROWCOUNT 0

-- Get the total rows 

SET @totalRows = (SELECT COUNT(AutoId) FROM #GPSData)	

SELECT COUNT(AutoId) AS "Count" FROM #GPSData

IF(@totalRows = 0)
 BEGIN
   SELECT * FROM #GPSData
 END

--DROP TABLE @GPSData

End   

--exec RVLT_SP_GetLat @startdate='2009-01-05 01:30:00', @enddate='2009-09-15 14:30:00', @totalRows = 0

--select * from rvlfBoxMsgInType 

--exec RVLT_SP_GetLat @enddate='2009-09-15 14:30:00',@VehicleId=N'5',@orderby=N'desc',@startdate='2009-01-05 01:30:00',@interval=300,@bigQueryingUser=3,@totalRows=0,@sortColumn='MessageInID',@MessageType=0

--select * from rvlfMsgInHst where BoxId = 999222 and OriginDateTime >='2009-08-05 04:12:31.000' order by OriginDateTime desc


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RVLT_SP_GetLatLng]
(@vehicleId varchar(50),@startdate as datetime,@enddate datetime,
@interval as int,@orderby varchar(10))

as
Begin
DECLARE @query varchar(2000)
SET @query = ''
SET @query = ' select RG.Id,RG.VehicleId,DeviceId,Latitude, Longitude,Address,CAST(CAST(Speed as int) as varchar) + '' KMPH'' as Speed, Heading,
Timestamp,VehicleDescription from RVLT_Tbl_GPSData RG INNER JOIN rvlfVehicle RV on RV.VehicleId = RG.VehicleId where RG.VehicleId = ''' + @VehicleID + ''' and 
timestamp between '''+ CAST(@startdate as varchar) + ''' and ''' + CAST(@enddate as varchar) + ''' 
and datediff(ss, convert(datetime,'''+ CAST(@startdate as varchar) + '''), convert(datetime,timestamp))%' + cast(@interval as varchar)+' = 0
order by Timestamp '+ @orderby +''
--print @query
exec(@query)

End
-- exec [RVLT_SP_GetLatLng] 'V1','01/23/2009 14:00:00','01/23/2009 18:55:00',120,'asc'


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng_ByID]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RVLT_SP_GetLatLng_ByID]
(@checkedID varchar(1000))
as
Begin
Declare @query varchar(5000)
SET @query = ''
SET @query = 'select * from RVLT_Tbl_GPSData where Id in ('+ @checkedID +')'
-- print @query
exec(@query)
-- where timestamp between @startdate and @enddate and datediff(ss, convert(datetime,@startdate), convert(datetime,timestamp))%@interval = 0
End
-- exec [RVLT_SP_GetLatLng_ByID] '61,117'


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng_ByID1]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RVLT_SP_GetLatLng_ByID1]   
(
	@checkedID varchar(1000),
	@bigQueryingUser bigint = null
)
as
/******************************************************************************/
--	Name		:	RVLT_SP_GetLatLng_ByID1 '''E52BCEE9-1850-DF11-A755-001A4DA9D524''',44
--	Description	:	To gets the information for map it
--	Author		:	T. Sathish Kumar
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	18-Dec-2009	MJJC	Changed to show the information based on the user preferences.
--              :   09-Jan-2009 LK		Added the Landmark and Message Details
--				:	11-Jan-2010 MJJC	Returns message details from the fucntion and then status for icons
--				:	25-Jan-2010 MJJC	To update the alarm details function parameters
--				:	30-Jan-2010 MJJC	To check the sensor off with duration for ignition status
--				:	02-Feb-2010 MJJC	Checked the speed and GPS for returning heading.
--				:	26-Apr-2010 MJJC	Done the related change for shoing speed with violation
--				:	26-July-2010 VN	 To get the speed with duration without speed
/******************************************************************************/
Begin
	DECLARE @HoursToBeAdded INT = 0
	DECLARE @MinsToBeAdded INT = 0
	DECLARE @Distance varchar(20)
	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
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser
    SET @ConversionFactor = ISNULL(@ConversionFactor,1.0)
    SET @HoursToBeAdded  = ISNULL(@HoursToBeAdded,0)
	SET @MinsToBeAdded  = ISNULL(@MinsToBeAdded,0)
	SET @Distance  = ISNULL(@Distance,'KMPH')
Declare @query varchar(5000)
SET @query = ''
SET @query = 'SELECT h.BoxId, DateAdd(n,'+Cast(@MinsToBeAdded as varchar(10))+',DateAdd(hh,'+ cast(@HoursToBeAdded as varchar(10))
	+',h.OriginDateTime)) AS DateTimeReceived, h.NearestLandmark, h.Latitude, h.Longitude, '
	+'h.MessageInID, CASE WHEN H.Speed = 0 OR H.ValidGps > 0 THEN -1 ELSE Heading END as Heading,CASE WHEN H.BoxMsgInTypeID = 51 THEN '''' ELSE CAST(CAST(h.Speed  * '+CAST( @ConversionFactor as varchar(13))+' as int) as varchar(30)) END +'' ''+'''+@Distance+''' as Speed, Replace(ISNULL(h.StreetAddress,''Address is not resolved''),'''''''',''\'''''')'
	+ ' AS StreetAddress, CASE WHEN (L.LandMarkID IS NULL OR H.LandMarkID = 0) THEN ''-'' ELSE L.LandmarkName END AS Landmark,' 
			+'CASE WHEN H.BoxMsgInTypeID=51 THEN ''Speed Violated for  ''+ '' (''+
			   dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+'')'' ELSE dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInId, H.OriginDateTime )'
			+ ' END as MessageDetails,'
    + '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 H.BoxMsgInTypeId = 3 THEN 0
				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 '
	+ 'FROM rvlfMsgInHst h '
	+ 'INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId '
	+ 'LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID '
	+ 'LEFT OUTER join rvlfTripDetails t ON h.MessageInID = t.StartMessageInID '
	+ 'LEFT OUTER JOIN rvlfTripDetails d ON h.MessageInID = d.EndMessageInID '
	+ 'WHERE h.MessageInId in  ('+ @checkedID +')'
 print @query
exec(@query)
End


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng_Paging]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- [RVLT_SP_GetLatLng2] '8','2009-07-30','2009-08-05',30,'desc',0
CREATE procedure [dbo].[RVLT_SP_GetLatLng_Paging]                              
(
	@vehicleId varchar(50),
	@startdate as datetime,
	@enddate datetime,                              
    @interval as int = 30,
    @startRowIndex as int = 1,
    @maximumRows as int = 5,
--    @totalRows as int OUTPUT,
    @sortColumn as varchar(25) = 'AutoId',
    @orderby varchar(10) = null,
    @bigQueryingUser bigint = 0
)                              
                              
as                              
Begin    

	------- Included by Kumuthini on 16-July-09 ---------------------
	
	DECLARE @HoursToBeAdded INT = 0
	DECLARE @MinsToBeAdded 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 
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser
	
	--------------------------------
	
	-------------------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))
	----------------------------------------------------------------------------------------------------------
  
   CREATE Table #GPSData(AutoId bigint identity(1,1) not null, MessageInID uniqueidentifier,DeviceID int,ValidGPS tinyint,Latitude decimal(14,6),Longitude decimal(14,6),
       Distance varchar(300),Speed varchar(150),Heading smallint,Timestamp DateTime,VehicleDescription varchar(250),Message varchar(50),
       BoxMsgInTypeId tinyint,MessageDetails varchar(250),UserID bigint,Priority tinyint,Acknowledged bit,Address varchar(250))                                
   
    INSERT INTO #GPSData       
	select distinct(H.MessageInID), VA.BoxID as DeviceID, ValidGPS, cast(H.Latitude as decimal(14,6)) as Latitude, cast(H.Longitude as decimal(14,6)) as Longitude,                
    H.NearestLandMark as Distance, 
    CAST((CAST(Speed as int) * @ConversionFactor) as varchar) + CASE WHEN  @ConversionFactor = 0.62 THEN ' miles/hr' ELSE ' km/hr' END as Speed, 
    Heading, DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [Timestamp], 
    VehicleDescription, BoxMsgInTypeName as Message, H.BoxMsgInTypeId as BoxMsgInTypeId ,
   CASE WHEN H.BoxMsgInTypeID in (11 , 2 , 3 , 13 , 9 , 14 , 15 , 16 , 17 , 24 , 18)
				THEN dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId ,H.MessageInId ,H.OriginDateTime)
				WHEN H.BoxMsgInTypeId IN (5,6) THEN
					dbo.rvlf_fn_GetAlarmDetails(CAST( SUBSTRING(H.CustomProp,
					CHARINDEX('=',H.CustomProp,1)+1,(CHARINDEX(';',H.CustomProp,1)
					- CHARINDEX('=',H.CustomProp,1))-1) as bigint), H.BoxMsgInTypeId,H.BoxId,H.MessageInId ,H.OriginDateTime)
			ELSE CT.BoxMsgInTypeDesc 
			END as MessageDetails,	
				0 as UserID,0 as Priority,NULL as Acknowledged, case WHEN (H.LandMarkID IS NULL or H.LandMarkID = 0) THEN H.StreetAddress ELSE L.LandmarkName END as Address
from rvlfMsgInHst H LEFT OUTER JOIN rvlfLandmark L on H.LandMarkID = L.LandmarkID INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = H.BoxID         
    INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID          
    INNER JOIN rvlfBoxMsgInType CT on CT.BoxMsgInTypeId = H.BoxMsgInTypeID   
    where VA.VehicleId = @VehicleID and OriginDateTime between CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109)    
    and H.BoxMsgInTypeID NOT in (/*19,*/20,35,34,31) -- and datediff(ss, convert(datetime,'''+ CAST(@startdate as varchar) + '''), convert(datetime,OriginDateTime))%' + cast(@interval as varchar)+' = 0     
    UNION ALL    
		select  NULL as MessageInID,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,'' as Speed, 0 as Heading,
		DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [Timestamp], 
		V.VehicleDescription,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId ,BoxcmdTypeDesc as MessageDetails,UserID,Priority,Acknowledged,'N/A' as Address --into #tblFinal    
		from rvlfMsgOutHst OH        
		INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID        
		INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId     
		WHERE VA.VehicleID = @VehicleID and SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)    
		order by Timestamp desc --) as d   
	
-- PAGING

DECLARE @first_id int, @startRow int
DECLARE @SQL AS varchar(200) = ''
CREATE Table #Temp(AutoId bigint not null)

SET @startRowIndex =  @startRowIndex + 1

IF @startRowIndex = 0 
   SET @startRowIndex = 1

SET ROWCOUNT @startRowIndex

SET @SQL = 'SELECT AutoId FROM #GPSData ORDER BY ' + @sortColumn
INSERT INTO #Temp EXEC(@SQL)

SELECT @first_id = AutoId FROM #Temp

DROP TABLE #Temp

SET ROWCOUNT @maximumRows

SET @SQL = 'SELECT * FROM #GPSData WHERE AutoId >= ' + CAST(@first_id AS VARCHAR(10)) + ' ORDER BY ' + @sortColumn
EXEC(@SQL)
 
SET ROWCOUNT 0

-- Get the total rows 

--SET @totalRows = (SELECT COUNT(AutoId) FROM #GPSData)	

DROP TABLE #GPSData

End


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng1]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RVLT_SP_GetLatLng1]        
(@vehicleId varchar(50),@startdate as datetime,@enddate datetime,        
@interval as int,@orderby varchar(10))        
        
as        
Begin        
DECLARE @query varchar(2000)        
      
CREATE Table #tempDis(recTime datetime, LndId bigint,LndMark varchar(100),Id bigint,Latitude varchar(20),      
      Longitude varchar(20),Dist decimal(14,4),radius decimal(14,4))      
  
CREATE INDEX IDX_RVLT_LOCATION on #tempDis(recTime, Dist)  
  
INSERT INTO #tempDis      
select distinct(G.Timestamp),L.LandMarkId,L.LandMarkName,G.OrgID,G.Latitude,G.longitude,MIN(DEGREES(ACOS((SIN(RADIANS(L.Latitude)) *      
              SIN(RADIANS(G.Latitude)) +      
              COS(RADIANS(L.Latitude)) *      
              COS(RADIANS(G.Latitude)) *      
              COS(RADIANS(L.Longitude - G.Longitude)))))) * 69.09 * 1.609344,L.Radius        
From rvlfLandMarK L inner join rvlt_tbl_gpsdata G on L.OrganizationId = G.OrgId       
group by g.Timestamp,L.LandMarkId,L.LandMarkName,G.OrgID,G.Latitude,G.longitude,L.Radius      
      
      
CREATE Table #LandMark(OrgId int,LndId int,RecTime DateTime,Latitude decimal(14,10),Longitude decimal(14,10),Address varchar(1000))      
  
CREATE INDEX IDX_RVLT_LandMark on #LandMark(Latitude, Longitude)  
  
INSERT INTO #LandMark      
SELECT OrgId,LndId,Rectime,G1.Latitude,G1.Longitude ,      
CASE WHEN (Radius/1000) > (SELECT MIN(G2.dist) FROM #tempdis As G2 WHERE G1.Rectime = G2.Rectime) THEN Lndmark ELSE Address END as Addr      
FROM #tempdis AS G1 INNER JOIN rvlt_tbl_gpsdata D on D.latitude = G1.Latitude and D.Longitude = G1.Longitude       
WHERE dist = (SELECT MIN(G2.dist)      
FROM #tempdis As G2 WHERE G1.Rectime = G2.Rectime)       
group by OrgId,LndId,Rectime,G1.Latitude,G1.Longitude,G1.radius,G1.lndmark,D.address,G1.dist      
      
SET @query = ''        
SET @query = ' select RG.Id,RG.VehicleId,DeviceId,RG.Latitude,RG. Longitude,L.Address,RG.Distance,CAST(CAST(Speed as int) as varchar) + '' km/hr'' as Speed, Heading,        
Timestamp,VehicleDescription from RVLT_Tbl_GPSData RG INNER JOIN rvlfVehicle RV on RV.VehicleId = RG.VehicleId       
INNER JOIN #LandMark L on RG.Latitude = L.Latitude and RG.Longitude = L.Longitude       
where RG.VehicleId = ''' + @VehicleID + ''' and         
timestamp between '''+ CAST(@startdate as varchar) + ''' and ''' + CAST(@enddate as varchar) + '''         
and datediff(ss, convert(datetime,'''+ CAST(@startdate as varchar) + '''), convert(datetime,timestamp))%' + cast(@interval as varchar)+' = 0        
order by Timestamp '+ @orderby +''        
--print @query        
exec(@query)        
drop table #tempdis       
drop table  #LandMark      
End        
-- exec [RVLT_SP_GetLatLng1] 'V1','01/23/2009 14:00:00','01/23/2009 18:55:00',30,'asc'


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng2]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RVLT_SP_GetLatLng2]    
(                  
 @vehicleId varchar(50)=null,                  
 @startdate as datetime,                  
 @enddate datetime,                  
 @interval as int=2000,                  
 @orderby varchar(10)='desc',                  
 @bigQueryingUser bigint = 0,                  
 @bitIsMDTMsg bit=0 ,                
 @bitIsMessage bit = 0,          
 @bigLastHours int = null                   
)
as
/******************************************************************************/                  
--2013-01-30 11:12:17.890              
-- Name  : RVLT_SP_GetLatLng2 2538,'2016-08-31 08:00:00 AM','2016-08-31 12:00:00 PM',2000,'desc',502              
-- Description : To get the messages that needs to be shown in the grid                  
-- Author  : T. Sathish Kumar                  
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
--    : 11-Dec-2009 MJJC Included message & Command restrictions                  
--    : 29-Dec-2009 MJJC Restricted the response display of the commands sent by Angler Admin                  
--    : 11-Jan-2010 MJJC To get the message details from the function                  
--    : 25-Jan-2010 MJJC To update the alarm details function parameters                  
--    : 28-Jan-2010 MJJC To have a field for status for exporting.                  
--    : 29-Jan-2010 MJJC To return the message details for Send geozone IDs from its description                  
--    : 06-Feb-2010 MJJC Checked whether the communication details is null or not.                  
--    : 26-Apr-2010 MJJC Done the related change for shoing speed with violation                  
--    : 16-Jun-2010 MJJC Included the function for the map it.                  
--    : 26-July-2010 VN  To display the speed with duration msg without speed.                  
--    : 30-July-2010 LK     Changed the current location indication logic                  
--    : 08-Oct-2010 TSK     Fine tuned the Proc to optimize                  
--    : 08-Dec-2010 LK     Made Vehicle fuel fill message visible for only AnglerAdmin                  
--    : 30-Dec-2010 VN  To display the sensor 1,2 in the message details                  
--    : 17-Feb-2011 VN  To display the violaion speed 2 values.                  
--    : 09-mar-2011 VN  To restrict the ibutton message details displyed in the history                  
--    : 15-mAR-2011 VN  To restrict the speed in the vehicle fuel drain message -90 based on karthik instruction.                  
--    : 26-Apr-2011 LK      Included the 'Aborted' Status for OTA                  
--    : 25-Jul-2011 TSK     Included the DefaultAlarm column to filter in History Grid                  
--    : 04-Aug-2011 Ranjith Date format included                  
--    : 09-Dec-2011 Sakthi  Get the ignition status for idling                  
--    : 20-Dec-2011 Sakthi to get the ignition status for sleep mode                  
--    : 01-Sep-2012 Sakthi - Include the garmin status                
--    : 27-Apr-2013 Sakthi - Include the code for mobile application    
--    : 27-May-2014 Gopal - Include the Road speed limit column    
--    : 07-Apr-2015 Sakthi - Include restricted geozone columns
/******************************************************************************/      

Begin                  
   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 = 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                  
                      
    print @HoursToBeAdded                  
    print @MinsToBeAdded                  
                      
 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)                
    -----------------------------------------------------------------------                
                --print @startDate  
                --print @endDate  
 DECLARE @intTotalRecords int                  
 SELECT @intTotalRecords = COUNT(H.MessageInID) 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                    
  --LEFT OUTER join rvlfTripDetails t ON h.MessageInID = t.StartMessageInID                  
  --LEFT OUTER JOIN rvlfTripDetails d ON h.MessageInID = d.EndMessageInID                  
    where OriginDateTime between                   
    CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) and  VA.VehicleId = @VehicleID              
    and                   
  CT.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s                   
   WHERE s.ModuleId = 26 and s.UserGroupId IN                   
   (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))                  
    and H.ValidGps=0                 
                    
    IF @intTotalRecords < @interval OR @interval = 30                  
  BEGIN                  
     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,              
      (case WHEN BoxMsgInTypeId = 114 and customprop like '%ImgHeader:%' and CHARINDEX('ImgHeader:1', customprop) <> 0 THEN                  
      (case when (dbo.rvlf_fn_GetCameraHex(BoxId,CAST(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Image ID:',';') as int),          
      CONVERT(varchar(35),@startdate,109),CONVERT(varchar(35),@enddate,109))) is null               
      then 'Null'              
      else               
      dbo.rvlf_fn_GetCameraHex(BoxId,CAST(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Image ID:',';') as int),CONVERT(varchar(35),@startdate,109), CONVERT(varchar(35),@enddate,109))               
      END)              
      else 'Null' end                 
    )as CamData              
    ,(case WHEN BoxMsgInTypeId = 114 and CHARINDEX('ImgHeader:1', customprop) <> 0 THEN                   
    (SELECT top 1 (case when count(ImageID) = TotalPackets then 0 else 1 end)  FROM rvlfCameraImages where boxid = BoxId and imageid =CAST(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Image ID:',';') as int) and Receiveddate between CONVERT(varchar(35),





@startdate,109)  and CONVERT(varchar(35),@enddate,109) GROUP by ImageID,TotalPackets) else 0 end) as ImgStatus,              
    (case WHEN BoxMsgInTypeId = 114 and  CustomProp like '%SendSMSQuery%' THEN 1 else 0 end) as SMSStatus,                    
             (case WHEN BoxMsgInTypeId in (100,114) and CustomProp like '%Finger%' THEN 1 else 0 end) as FingerPrintStatus,              
    (case WHEN BoxMsgInTypeId = 114 and customprop like '%PacketType:%' THEN                
      dbo.rvlf_fn_GetAlarmDetails_New(customprop,BoxMsgInTypeID, BoxId, MessageInID, DateTimeReceived,@Lang)               
    else null end) as ImagePacketType              
        from (                  
   select distinct(H.MessageInID),H.CustomProp,H.BoxId, VA.BoxID as DeviceID, 
   (CASE WHEN cast(ISNULL(H.Latitude,0) as decimal(14,6)) = 0 THEN 1 ELSE ValidGps END) AS ValidGPS, 
   cast(ISNULL(H.Latitude,0) as decimal(14,6)) as Latitude, cast(ISNULL(H.Longitude,0) 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 =51 THEN NULL ELSE CAST(CAST(Speed  * @ConversionFactor as INT) AS VARCHAR)+ CASE WHEN CustomProp LIKE '%speed1=%' THEN ' --> '+ CAST(CAST((CAST(SUBSTRING(CustomProp,CHARINDEX('speed1=',CustomProp,0)+7,          
   --(LEN(CustomProp))) AS INT)* @ConversionFactor) AS INT) AS VARCHAR) ELSE ''  END  END  as Speed,                   
   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 '-'      
   WHEN H.BoxMsgInTypeId IN (2,3,12) 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_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime), -- DateTimeReceived              
--   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [Timestamp],                   
--   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,DateTimeReceived)) as DateTimeReceived,                  
   v.VehicleDescription,      OriginDateTime,         
   --BoxMsgInTypeDesc as Message,               
   case WHEN H.BoxMsgInTypeId = 114 and CHARINDEX('ImgHeader:1', H.customprop) <> 0  THEN  'Camera Image' else (              
   case when H.BoxMsgInTypeId = 114 and H.customprop like '%CameraSettings:%' and CHARINDEX('CameraSettings:1', H.customprop) <> 0 Then 'Camera Settings'               
   when H.BoxMsgInTypeId = 114 and H.customprop like '%CameraSettingsAdvanced:%' and CHARINDEX('CameraSettingsAdvanced:1', H.customprop) <> 0 Then 'Camera Settings Advanced'               
   when H.BoxMsgInTypeId = 114 and H.customprop like '%GeozoneInOutWithDuration:%' and CHARINDEX('GeozoneInOutWithDuration:1', H.customprop) <> 0 Then 'Geozone In Out With Duration'               
   --when H.BoxMsgInTypeId = 114 and H.customprop like '%SendSMSQuery:%' and SUBSTRING(H.customprop, CHARINDEX('SendSMSQuery:', H.customprop)+13,1) = '1' Then 'Send SMS Query To Server'               
   --WHEN H.BoxMsgInTypeId = 114 and H.customprop like '%FingerPrintCommand:%' and SUBSTRING(H.customprop, CHARINDEX('FingerPrintCommand:', H.customprop)+19,1) ='1' Then 'Finger Print'               
   WHEN H.BoxMsgInTypeId = 114 and H.customprop like '%SendSMSQuery:%'  Then 'Send SMS Query To Server'                     
   WHEN H.BoxMsgInTypeId = 114 and H.customprop like '%FingerPrintCommand:%' Then 'Finger Print'                             
   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'              
   when H.BoxMsgInTypeId = 114 and CHARINDEX('21;GeozoneSpeedViolation',H.CustomProp,0) <> 0  THEN 'Geozone Speed Violation'              
   When H.BoxMsgInTypeId = 114 and H.customprop like '%IButtonCommand:%' and CHARINDEX('IButtonCommand:1', H.CustomProp) <> 0 Then 'Send iButton Param'            when H.BoxMsgInTypeId = 114 and CHARINDEX('35;InvalidFixDuration=',H.CustomProp,0) <> 0  THEN 'Invalid Fix'
   else (CASE WHEN  @Lang='LanguageArNew' THEN ISNULL(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc)  else BoxMsgInTypeDesc  END) end) end as Message,       
   H.BoxMsgInTypeId as BoxMsgInTypeId ,                  
   TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,OriginDateTime),                
   --Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)),@DefaultDateFormat) + ' ' + Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime))as Time),22)  as [TimestampDisp],              




 


     
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [TimestampSort],                                 
     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(h.CustomProp,'Interval=',';')+' Min'           
          ELSE '' END                  
          WHEN H.BoxMsgInTypeId=104 THEN 'Live Track Parameters : ' + CASE WHEN H.CustomProp LIKE '%Frequency=%' THEN dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Frequency=',';') +' Sec for '+                  
          dbo.rvlf_fn_GetParamValueWithIndex(h.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 - '+ dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Error Code=',';')            
       WHEN H.BoxMsgInTypeId=113 THEN                  
       dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Band Name=',';')  +' ['+                  
       dbo.rvlf_fn_GetTimeFromSeconds(CAST(dbo.rvlf_fn_GetParamValueWithIndex(h.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 CHARINDEX('ImgHeader:1', H.customprop) <> 0  THEN  'Camera Image' --'Camera Image'               
    WHEN H.BoxMsgInTypeId = 114 and H.customprop like '%CameraSettings:%' and CHARINDEX('CameraSettings:1', H.customprop) <> 0 Then 'Camera Settings'                   
    When H.BoxMsgInTypeId = 114 and H.customprop like '%IButtonCommand:%' and CHARINDEX('IButtonCommand:1', H.CustomProp) <> 0 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 CHARINDEX('GeozoneInOutWithDuration:1', H.customprop) <> 0 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(SUBSTRING(CustomProp,CHARINDEX(';GeozoneId:',CustomProp,0)+11,(CHARINDEX(';SpeedThreshold:',CustomProp,0) - (CHARINDEX(';GeozoneId:',CustomProp,0)+11))) AS INT)),'Deleted')+              
  '; Speed Limit: '+SUBSTRING(H.CustomProp,CHARINDEX('SpeedThreshold:',H.CustomProp,0)+15,(LEN(H.CustomProp)-(CHARINDEX('SpeedThreshold:',H.CustomProp,0)+14)))+' 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 (dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Duration:',';') 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(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Duration:',';') AS INT))+')'               
      else            
       case when CAST(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'ExtDuration:',';')  AS INT)=1 then            
       ' Extended Time Violation (' else                                          
      ' Time Violation (' end            
      +dbo.rvlf_fn_GetTimeFromSeconds(CAST(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Duration:',';') 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 : '+ dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'AlarmMsg=',';')  
    when H.BoxMsgInTypeId = 114 and CHARINDEX('35;InvalidFixDuration=',H.CustomProp,0) <> 0  THEN REPLACE(h.CustomProp,'35;In','In')            
     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 = '+ 
      dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SensorInfo1=',';') 
      ELSE '' END+ CASE WHEN H.customprop LIKE '%SensorInfo2%' THEN +' ; S2 = '+  dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SensorInfo2=',';')  ELSE '' END ELSE ''  END                   
     as MessageDetails,         
      0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,                                       
       --case WHEN (H.LandMarkID IS NULL or H.LandMarkID = 0) THEN ISNULL              
       --(H.StreetAddress,'               
       --Address is not resolved') ELSE                   
       --ISNULL(L.LandmarkName, ISNULL(H.StreetAddress,'Address is not resolved'))                  
       --END as Address,              
                     
       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,                
                 
       @Distance as Units,                  
       --END as Address,@Distance as Unitsmeters,                  
      CASE                   
      WHEN H.ValidGps > 0 OR H.BoxMsgInTypeId IN (9,14,15,16,17,24) OR Speed = 0 then '-'                  
      WHEN H.BoxMsgInTypeId IN (96) then '-'                  
      WHEN H.Heading between 335 and 360 THEN 'N'                  
       WHEN H.Heading between 0 and 25 THEN 'N'                  
      WHEN H.Heading between 25 and 65 THEN 'NE'                  
      WHEN H.Heading between 65 and 115 THEN 'E'                  
      WHEN H.Heading between 115 and 155 THEN 'SE'                  
      WHEN H.Heading between 155 and 210 THEN 'S'                  
      WHEN H.Heading between 210 and 245 THEN 'SW'                  
      WHEN H.Heading between 245 and 300 THEN 'W'                  
      WHEN H.Heading between 300 and 335 THEN 'NW' END as Direction ,                        
                       
      +'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,                  
      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      
          CASE WHEN CAST(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Idling:',';') 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'                  
           CASE WHEN (dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SENSOR_STATUS=',';')) = '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,L.LandmarkName as LandmarkName, L.Latitude as LandmarkLatitude,                   
        L.Longitude as LandmarkLongitude, L.Radius as LandmarkRadius,                          
          replace(L.StreetAddress,@NewLine,' ') As LandMarkAddress,              
          L.LandmarkID,'' as LandImage,     
          --isnull(LC.ImagePath,'') as LandImage,                
         CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,                
         CASE WHEN H.BoxMsgInTypeId IN(77,98,109,110,111) THEN 'Incoming'                             
           ELSE NULL END AS MDTMsgType,          
           (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                  
,H.RoadSpeedLimit,v.vehicleid
   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 
    --LEFT OUTER JOIN rvlfLandmarkCategory LC ON L.LandmarkCategoryID = LC.LandmarkCategoryID                  
    INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID                  
   where  OriginDateTime between                  
   CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) and  VA.VehicleId = @VehicleID             
   and                   
   -- (H.BoxMsgInTypeId = 11 and L.OrganizationId = 51 OR 1 = (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser)) AND -- Hided Sensor Alarm for Suguna                  
   --H.BoxMsgInTypeId <>19 and--blocked the ipupdates for Gitex                  
   (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 H.BOXMSGINTYPEID NOT IN(102,103)                  
    AND CommInfo1 IS NOT NULL                  
  AND (@bitIsMDTMsg=0 OR H.BoxMsgInTypeId IN(77,98,109,110,111)) and h.CustomProp not like '%18;GPRS%'                   
   UNION ALL                  
   /***************** Changed the Speed as NULL by Jaya Chitra on 25-Aug-2009******************/                  
    select  NULL as MessageInID,null as Customprop,              
    null as BoxId,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,NULL as Speed, 0 as Heading,                  
    [Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),                
   SentDateTime = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),                
    --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [Timestamp],                  
    --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as SentDateTime,                   
    V.VehicleDescription,null as OriginDateTime,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId ,                  
     TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime),                
   -- convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)),@DefaultDateFormat) + ' ' + CONVERT(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime))as time),22) as [TimestampDisp], 

    DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [TimestampSort],                  
    CASE WHEN OH.BoxCmdOutTypeId = 39 OR OH.BoxCmdOutTypeId = 4 THEN dbo.rvlf_fn_GetCmdMsgDetails(OH.CustomProp + ',', OH.BoxCmdOutTypeId, VA.BoxID)                   
         ELSE BoxcmdTypeDesc END as MessageDetails                  
    ,OH.UserId,Priority,                  
    /**************** Changed the Acknowledgement to be return based on the value ************/                  
    CASE WHEN Acknowledged = 1 THEN 'True'                   
      WHEN Acknowledged = 0 THEN 'False'                   
      WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Update Failed'                  
      WHEN  Acknowledged = 4 THEN 'CRC Incorrect'                  
      WHEN  Acknowledged = 5 THEN 'No Communication'                  
      WHEN  Acknowledged = 6 THEN 'Aborted'                  
      WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'                  
      ELSE 'Nothing' END AS Acknowledged,                  
    CASE WHEN Acknowledged = 1 THEN 'Acknowledged'                   
      WHEN Acknowledged = 0 THEN 'Not Acknowledged'                   
      WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Upgrade Failed'                  
      WHEN  Acknowledged = 4 THEN 'CRC Incorrect'                  
      WHEN  Acknowledged = 5 THEN 'No Communication'                  
      WHEN  Acknowledged = 6 THEN 'Aborted'                  
      WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'      
      ELSE '' END AS AckStatus,                  
    'N/A' as Address,@Distance as Units,'' as Direction ,/*null as mapitFunction,*/'setValue('' '')' as jsFunction,                  
    NULL as IgnitionStatus, NULL as StreetAddress, NULL as Landmark,NULL as LandmarkName,                   
    NULL as LandmarkLatitude, NULL as LandmarkLongitude, NULL as LandmarkRadius,                  
    NULL As LandMarkAddress, NULL as LandmarkID,Null as LandImage,NULL as IsDefaultAlarm,                  
    CASE WHEN oH.BoxCmdOutTypeId IN(39,44,45,46,47) THEN 'Outgoing'                  
           ELSE NULL END AS MDTMsgType, null as isMapIT ,0 as Roadspeedlimit ,va.vehicleid               
    from rvlfMsgOutHst OH                  
    INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID                  
    INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId                  
    WHERE  SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)                  
     AND VA.VehicleID = @VehicleID  and --OH.BoxCmdOutTypeId <> 22                       
     CT.OperationTypeId IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s                   
     WHERE s.ModuleId = 22 and s.UserGroupId IN                   
     (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))                   
     AND (@bitIsMDTMsg=0 OR OH.BoxCmdOutTypeId IN(39,44,45,46,47))) as a order by Timestamp desc, MessageInID desc                  
                     
   -- Get the Latest value for Device                  
   select B.BoxId,LastLatitude,LastLongitude,                  
    CASE WHEN H.BoxMsgInTypeId =51 OR H.BoxMsgInTypeId =90  THEN ''
     WHEN ISNULL(H.Speed,0) = 0 THEN '-'   ELSE CAST(CAST(LastSpeed  * @ConversionFactor as int) as varchar(10)) END as LastSpeed,                  
    CASE WHEN LastSpeed = 0 OR LastCommunicatedDateTime<> LastStatusDateTime                   
    THEN -1 ELSE B.Heading END as Heading,                  
    Replace(ISNULL( LastStreetAddress, 'Address is not resolved'),'''','\''')  as LastStreetAddress,                  
    DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,LastValidDateTime)) as LastStatusDateTime,                  
    B.NearestLandmark, V.VehicleId,V.VehicleDescription,                  
    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                   
       CASE WHEN CAST(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Idling:',';') 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'    
         CASE WHEN (dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SENSOR_STATUS=',';')) = 'ON'                         
         THEN 1 ELSE 0 End End                  
      ELSE 2 END as IgnitionStatus,                  
    @Distance as Units,                  
    CASE WHEN H.BoxMsgInTypeId = 51 THEN                
       (case when @Lang='LanguageArNew' THEN N'تخرق السرعة لل ' when @Lang='LanguageHindi' THEN N'स्पीड के लिए उल्लंघन'  ELSE 'Speed Violated for ' END)                   
      --+CAST(CAST(Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @Distance                   
   +'(' + dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'                  
    ELSE                   
     dbo.rvlf_fn_GetAlarmDetails_New(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)--CT.BoxMsgInTypeDesc                   
    END                   
    as MessageDetails,                   
    ISNULL(CASE WHEN (L.LandMarkID IS NULL OR H.LandMarkID = 0) THEN '-' ELSE isnull(L.LandmarkName,'-') END,'-') AS Landmark,                  
    L.LandmarkName as LandmarkName, L.Latitude as LandmarkLatitude, L.Longitude as LandmarkLongitude, L.Radius as LandmarkRadius,               
    replace(L.StreetAddress,@NewLine,' ') As LandMarkAddress ,H.RoadSpeedLimit              
   from rvlfBoxId B INNER JOIN rvlfVehicleAssignment VA on B.BoxId = VA.BoxId                  
    INNER JOIN rvlfMsgInHst H ON  H.BoxId=VA.BoxId AND H.OriginDateTime=B.LastValidDateTime AND H.Latitude=B.LastLatitude AND H.Longitude=B.LastLongitude                   
    INNER JOIN rvlfVehicle V on V.VehicleId = VA.VehicleId                  
    --LEFT OUTER join rvlfTripDetails t ON h.MessageInID = t.StartMessageInID                  
    --LEFT OUTER JOIN rvlfTripDetails d ON h.MessageInID = d.EndMessageInID                  
    INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                  
    LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID                   
                      
   where VA.VehicleId = @vehicleId                    
    --AND H.BOXMSGINTYPEID NOT IN(102,103)                  
    --AND (DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,LastStatusDateTime))                  
    --BETWEEN CONVERT(DateTime,@startdate,109) and CONVERT(DateTime,@enddate,109))          
         
 --Get Geozone details            
 Select distinct 
 --CAST(SUBSTRING(H.CustomProp,CHARINDEX('GeozoneId=',H.CustomProp,0)+10,(CHARINDEX(';',H.CustomProp,0) - (CHARINDEX('GeozoneId=',H.CustomProp,0)+10))) AS INT) as GeozoneNo            
  dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'GeozoneId=',';') as GeozoneNo    
 ,G.GeozoneName,G.GeozoneType,latlng = STUFF((SELECT '~' + cast(Latitude as varchar)+'#' + cast(Longitude as varchar)            
	FROM rvlfGeozoneSet b WHERE b.GeozoneNo = GS.GeozoneNo FOR XML PATH('')), 1, 1, ''),@bigOrganizationID,G.OrganizationId,
	(SELECT IsRestricted FROM rvlfGeozoneRestricted WHERE VehicleId=@VehicleID AND GeozoneNo=G.GeozoneNo) AS IsRestricted,
	ISNULL(G.Radius,0) AS CircleRadius, G.OrganizationId 
       --H.CustomProp          
 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                                             
    INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID              
    --inner join rvlfOrganizationGeozone G on G.GeozoneId=CAST(SUBSTRING(H.CustomProp,CHARINDEX('GeozoneId=',H.CustomProp,0)+10,(CHARINDEX(';',H.CustomProp,0) - (CHARINDEX('GeozoneId=',H.CustomProp,0)+10))) AS INT)            
    inner join rvlfOrganizationGeozone G on G.GeozoneId=CAST(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'GeozoneId=',';') AS INT)            
    and v.OrganizationId=G.OrganizationId          
    inner join rvlfGeozoneSet GS on GS.GeozoneNo=G.GeozoneNo            
   where  OriginDateTime between             
   CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) AND    VA.VehicleId = @VehicleID and        
   CHARINDEX('GeozoneId=',H.CustomProp,0) <> 0 and H.BoxMsgInTypeId=5 --and G.OrganizationId=@bigOrganizationID                
 END  
 ELSE                  
  BEGIN            
  SELECT 'Exceeds Threshold' as ResultValue                  
  END                  
End                                

GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng2_Ador]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RVLT_SP_GetLatLng2_Ador]    
(                  
 @vehicleId varchar(50)=null,                  
 @startdate as datetime =null,
 @enddate datetime =null,
 @interval as int=2000,                  
 @orderby varchar(10)='desc',                  
 @bigQueryingUser bigint = 292,                  
 @bitIsMDTMsg bit=0 ,                
 @bitIsMessage bit = 0,          
 @bigLastHours int = null ,                  
 @controller varchar(50)=null                    
)
as
/******************************************************************************/                  
--2013-01-30 11:12:17.890              
-- Name  : RVLT_SP_GetLatLng2_Ador  27,'2017-12-15 8:10:00 aM','2017-12-15 11:30:00 pM',2000,'desc',453 ,0,0,null,'TR-A6' 
-- Name  : RVLT_SP_GetLatLng2_Ador 803,'2018-02-15 08:00:00 AM','2018-02-15 10:00:00 PM',2000,'desc', 453             
-- Description : To get the messages that needs to be shown in the grid                  
-- Author  : T. Sathish Kumar                  
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
/******************************************************************************/      

Begin                  
	DECLARE @Lang varchar(50),  @LangSetting varchar(20)                               
	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 
	DECLARE @OperationTypeID table (OperationTypeID bigint) 
    DECLARE @controllerType tinyint= (select VehicleTypeId from rvlfVehicle where VehicleId=@vehicleId)
	               
    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)  ,
			@Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings                
    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    
	inner join rvlfOrganization o on u.OrganizationId = o.OrganizationId                               
                      
	--Get the operation id of priviledged user---   	
	INSERT INTO @OperationTypeID  
	SELECT OperationTypeID FROM rvlfUserGroupSecurity s                   
     WHERE s.ModuleId in(22,26) and s.UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser)                   
                      
	-------------------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)  	            
    -----------------------------------------------------------------------                
     
IF(@controllerType=1) 
BEGIN                            
   SELECT *,[Timestamp] as DateTimeReceived,ROW_NUMBER() over (order by timestamp) as AutoID  
   FROM( 
		Select DISTINCT(H.MessageInID),H.CustomProp,H.BoxId, md.BoxID as DeviceID, 
			0 AS ValidGPS, 0 as Latitude, 0 as Longitude,H.NearestLandMark as Distance,'-'  as Speed,0 as Heading, 
			[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
			--DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
			MD.EquipmentName as VehicleDescription, H.OriginDateTime,BoxMsgInTypeDesc as [Message],H.BoxMsgInTypeId as BoxMsgInTypeId , 
			H.OriginDateTime AS RoadsAPITime,  
			TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,H.OriginDateTime),   
			DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,H.OriginDateTime)) as [TimestampSort],                                 
			Case when H.BoxMsgInTypeId = 114 and CHARINDEX('18;GPRS',H.CustomProp,0) <> 0  THEN 'Send Health Status'      
			when h.BoxMsgInTypeId in (4,7,13,24) then ct.BoxMsgInTypeName +' '+isnull(cast(H.CmdId as varchar),'')       	
			ELSE ct.BoxMsgInTypeName --dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)
			END  as MessageDetails, 0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,
			H.StreetAddress AS Address, @Distance as Units,
			Replace(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''')  as StreetAddress,
			CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,          
			MD.VehicleId ,vt.VehicleTypeName,isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo,
			(isnull(cast('TEST' as varchar(50)),'-')) +' ['+(isnull(cast(H.controllerID as varchar(2)),'-'))+']' AS controllerID,
		 ----(isnull(cast(cm.ControllerName as varchar(50)),'-')) +' ['+(isnull(cast(H.controllerID as varchar(2)),'-'))+']' AS controllerID,
		 --(isnull(cast(H.controllerID as varchar(2)),'-')) AS controllerID ,
		 isnull(p.RefID,'-') as RefID,isnull(p.CmdId,'-') as CmdId,h.DCSIM,
		isnull([Seconday_Current_Limit(IDC)],'-') as Param1,isnull(Secondary_Voltage,'-') as Param2
		,isnull(Spark_Rate,'-') as Param3,isnull(Operating_Charge_Ratio,'-') as Param4
		,isnull(Optinal_Input_Power,'-') as Param5,isnull(Corona_Power,'-') as Param6,isnull(VDC_peak,'-') as Param7
		,isnull(VDC_Through,'-') as Param8,isnull(IAC_PRI,'-') as Param9,isnull(Operating_IDC_Limit,'-') as Param10
		,isnull(Total_Accumulated_Spark,'-') as Param11,isnull(Mains_Frequency,'-') as Param12,
		isnull(Total_Operating_Time,'-') as Param13,isnull(Operating_Corona_Energy,'-') as Param14
		,isnull(Input_Energy,'-') as Param15,isnull(Secondary_current_Limit,'-') as Param16
		,isnull(Sec_Current_Drop_AfterSpark,'-') as Param17,isnull(T_Recovery_cyc,'-') as Param18
		,isnull(T_Fast_Ramp_cyc,'-') as Param19,isnull(Charge_Ratio,'-') as Param20
		,isnull(Recharge_HW,'-') as Param21,isnull(BC_IDC_Min,'-') as Param22
		,isnull(RAP_IDC_Limit,'-') as Param23,isnull(BC_CR_Maximum,'-') as Param24
		,isnull(Load_Status1_IDC_Limit,'-') as Param25,isnull(LS_1_V_Limit,'-') as Param26
		,isnull(LS_1_IDC_Setbk,'-') as Param27,isnull(RAP_TM1_Pause,'-') as Param28
		,isnull(RAP_TM1_Run,'-') as Param29,isnull(RAP_TM2_Pause,'-') as Param30
		,isnull(RAP_TM2_Run,'-') as Param31,isnull(RAP_TM3_Pause,'-') as Param32
		,isnull(RAP_TM3_Run,'-') as Param33,
		isnull((case when RAP_MOT1_ON_OFF=0 then 'OFF' when RAP_MOT1_ON_OFF=1 then 'ON' else '-'end ),'-') as Param34
		,isnull((case when RAP_MOT2_ON_OFF=0 then 'OFF' when RAP_MOT2_ON_OFF=1 then 'ON' else '-'end ),'-') as Param35,
		isnull((case when RAP_MOT3_ON_OFF=0 then 'OFF' when RAP_MOT3_ON_OFF=1 then 'ON' else '-'end ),'-') as Param36
		,isnull((case when RAP_CONT_ON_OFF=0 then 'OFF' when RAP_CONT_ON_OFF=1 then 'ON' else '-'end ),'-') as Param37,
		isnull((case when Back_Corona_ON_OFF=0 then 'OFF' when Back_Corona_ON_OFF=1 then 'ON' else '-'end ),'-') as Param38
		,isnull((case when p.HT_ON_OFF=1 then 'OFF' when p.HT_ON_OFF=0 then 'ON' else '-'end ),'-') as Param39
		,isnull(Sec_Curr_drop_after_dbleSpark,'-') as Param40
		,isnull(MAX_Spark_Rate,'-') as Param41,isnull(TQuench_CYC,'-') as Param42
		,isnull(Back_Corona_MEAS,'-') as Param43,isnull(BC_IDC_Step,'-') as Param44
		,isnull(BC_Hold_Time,'-') as Param45,isnull([LS-1_CR],'-') as Param46
		,isnull(RECHARGE_FIRING,'-') as Param47,
		ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Temperature: #','°C$'),'') AS CurrTemp,
		ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Humidity: #','%$'),'') AS Humidity,
		ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Pressure: #','hPa$'),'') AS Pressure,isnull(h.Alarm,0) as Alarm,
		case when H.BoxMsgInTypeId in (24,7) then 1 else 0 end as Showdetails,0 AS ControllerPositionId,'' AS ControllerName
		--,CM.ControllerPositionId,CM.ControllerName
		FROM rvlfMsgInHst H
		LEFT JOIN rvlfMsgInHstParam_PIII P on h.MessageInID=p.Messageinid
		--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                     
		INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId    
		--INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
		INNER JOIN rvlfMAKDevices MD on MD.BoxId=H.BoxId   
		--inner join adrControllerMaster CM on h.boxid=CM.EquipmentId and h.ControllerID= CM.ControllerPositionId	and dcsim is null
		LEFT JOIN rvlfVehicleType vt on MD.SubTypeId=vt.VehicleTypeId	              
		WHERE  H.OriginDateTime BETWEEN CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109) 
		and  MD.VehicleId = @VehicleID and MD.IsDelete=0 --and cm.IsDeleted=0 and
		--(@controller is null or @controller='' or @controller='ALL' or cm.ControllerName =@controller)
		--and CT.OperationTypeID IN (select OperationTypeID from @OperationTypeID) AND CommInfo1 IS NOT NULL   and H.BoxMsgInTypeId in (1,4,13,15,14)               
   
UNION ALL                  
   /************-------------------------------***** Get Commands details---------------------------------------******************/                  
    SELECT NULL as MessageInID,null as Customprop,oh.BoxId,MD.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,
	NULL as Speed, 0 as Heading,[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),        
	--SentDateTime = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime), 
    MD.EquipmentName as VehicleDescription,'' as origindatetime,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId,
	SentDateTime AS RoadsAPITime,                      
    TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime), 
       DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [TimestampSort],
    --CASE WHEN OH.BoxCmdOutTypeId = 39 OR OH.BoxCmdOutTypeId = 4 THEN dbo.rvlf_fn_GetCmdMsgDetails(OH.CustomProp + ',', OH.BoxCmdOutTypeId, VA.BoxID)ELSE BoxcmdTypeDesc END as MessageDetails,
	BoxcmdTypeDesc as MessageDetails,
	OH.UserId,Priority, 
    /**************** Changed the Acknowledgement to be return based on the value ************/                  
    CASE WHEN Acknowledged = 1 THEN 'True' WHEN Acknowledged = 0 THEN 'False' WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Update Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect' WHEN  Acknowledged = 5 THEN 'No Communication'                  
      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'                  
      ELSE 'Nothing' END AS Acknowledged,                  
    CASE WHEN Acknowledged = 1 THEN 'Acknowledged' WHEN Acknowledged = 0 THEN 'Not Acknowledged' WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Upgrade Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect'   WHEN  Acknowledged = 5 THEN 'No Communication'  
      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'      
      ELSE '' END AS AckStatus,                  
    'N/A' as Address,@Distance as Units,--'' as Direction ,/*null as mapitFunction,*/'setValue('' '')' as jsFunction, NULL as IgnitionStatus,
	NULL as StreetAddress, NULL as IsDefaultAlarm,--null as isMapIT ,
	MD.vehicleid,vt.VehicleTypeName , isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo ,
	NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
	NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,null,NULL,NULL,null,0,0
	 ,null,null
    FROM rvlfMsgOutHst OH                  
    --INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID 
	--INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID                  
    INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId  
	INNER JOIN rvlfMAKDevices MD on MD.BoxId=oH.BoxId 
	--inner join adrControllerMaster CM on OH.boxid=CM.EquipmentId and OH.ControllerID= CM.ControllerPositionId	
	LEFT JOIN rvlfVehicleType vt on MD.SubTypeId=vt.VehicleTypeId                
    WHERE  SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)                  
    AND MD.VehicleID = @VehicleID and CT.OperationTypeId IN (select OperationTypeID from @OperationTypeID)
) as a ORDER BY Timestamp desc, MessageInID DESC 
END
ELSE IF(@controllerType=2) 
BEGIN                            
   SELECT *,[Timestamp] as DateTimeReceived,ROW_NUMBER() over (order by timestamp) as AutoID                     
   FROM( 
		Select DISTINCT(H.MessageInID),H.CustomProp,H.BoxId, MD.BoxID as DeviceID, 
			0 AS ValidGPS, 
			0.0 as Latitude, 0.0 as Longitude,   
			H.NearestLandMark as Distance,'-'  as Speed,0 as Heading, 
			[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
			--DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
 			MD.EquipmentName as VehicleDescription,    H.OriginDateTime,BoxMsgInTypeDesc as [Message],H.BoxMsgInTypeId as BoxMsgInTypeId , 
			H.OriginDateTime AS RoadsAPITime,    
			TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,H.OriginDateTime),   
			DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,H.OriginDateTime)) as [TimestampSort],                                 
			Case when H.BoxMsgInTypeId = 114 and CHARINDEX('18;GPRS',H.CustomProp,0) <> 0  THEN 'Send Health Status'      
			when h.BoxMsgInTypeId in (4,7,13,24) then ct.BoxMsgInTypeName +' '+isnull(cast(H.CmdId as varchar),'')       	
			ELSE ct.BoxMsgInTypeName --dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)
			END as MessageDetails, 0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,
			H.StreetAddress AS Address, @Distance as Units,	 
			Replace(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''')  as StreetAddress,
			CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,          
			MD.vehicleid ,vt.VehicleTypeName,isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo,			
			(isnull(cast('TEST' as varchar(50)),'-')) +' ['+(isnull(cast(H.controllerID as varchar(2)),'-'))+']' AS controllerID,
			 --(isnull(cast(cm.ControllerName as varchar(50)),'-')) +' ['+(isnull(cast(H.controllerID as varchar(2)),'-'))+']' AS controllerID,
			 --(isnull(cast(H.controllerID as varchar(2)),'-')) AS controllerID,
	ISNULL(P.RefID,'-') AS RefID,ISNULL(P.CmdId,'-') AS CmdId,H.DCSIM,
	ISNULL(P.Primary_Voltage_Value,'-') AS Param1,ISNULL(P.Primary_Current_Value,'-') AS Param2
	,ISNULL(P.Primary_Power_Value,'-') AS Param3,ISNULL(P.Secondary_Voltage_Value,'-') AS Param4,
	ISNULL(P.Secondary_Current_Value,'-') AS Param5,ISNULL(P.Spark_Per_Minute,'-') AS Param6
	,ISNULL(P.Arcs_Per_Minute,'-') AS Param7,ISNULL(P.Under_Voltage_TripMode,'-') AS Param8,
	ISNULL(P.Program_no_of_Rapper,'-') AS Param9,ISNULL(P.Primary_Voltage_limit,'-') AS Param10
	,ISNULL(P.Primary_Current_Limit,'-') AS Param11,ISNULL(P.Secondary_Voltage_Limit,'-') AS Param12,
	ISNULL(P.Secondary_Current_Limit,'-') AS Param13,ISNULL(P.Under_Voltage_Set_Point,'-') AS Param14,
	ISNULL(P.Secondary_Current_Peak_Limit,'-') AS Param15,ISNULL(P.Ramp,'-') AS Param16,ISNULL(P.Pedestal,'-') AS Param17,
	ISNULL(P.Quench_Time,'-') AS Param18,ISNULL(P.Spark_Rate,'-') AS Param19,ISNULL(P.IE_Charge_Halfcycle,'-') AS Param20,
	ISNULL(P.IE_Discharge_Cycle,'-') AS Param21,ISNULL(P.IE_Background_Power,'-') AS Param22	,
	ISNULL(P.IE_Optimise_Timer,'-') AS Param23,ISNULL(P.Power_Down_Rapping,'-') AS Param24,
	ISNULL(P.Rapper1_Interval_Timer,'-') AS Param25,ISNULL(P.Rapper1_On_timer,'-') AS Param26,
	ISNULL(P.Rapper2_Interval_timer,'-') AS Param27,ISNULL(P.Rapper2_On_Timer,'-') AS Param28,
	ISNULL(P.Rapper3_Interval_Timer,'-') AS Param29,ISNULL(P.Rapper3_On_Timer,'-') AS Param30,
	ISNULL(P.Rapper4_Interval_Timer,'-') AS Param31,ISNULL(P.Rapper4_On_Timer,'-') AS Param32,ISNULL(P.Phase_Back,'-') AS Param33,
	null as Param34,null as Param35,null as Param36,null as Param37,null as Param38,null as Param39,null as Param40,null as Param41,
	null as Param42,null as Param43,null as Param44,null as Param45,null as Param46,null as Param47,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Temperature: #','°C$'),'') AS CurrTemp,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Humidity: #','%$'),'') AS Humidity,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Pressure: #','hPa$'),'') AS Pressure ,isnull(h.Alarm,0) as Alarm,
	case when H.BoxMsgInTypeId in (24,7) then 1 else 0 end as Showdetails,0 AS ControllerPositionId,'' AS ControllerName
	--,CM.ControllerPositionId,CM.ControllerName
	FROM rvlfMsgInHst H                   
	left JOIN rvlfMsgInHstParam_PR P on h.MessageInID=p.Messageinid
	--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                     
	INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                      
	--INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
	INNER JOIN rvlfMAKDevices MD on MD.BoxId=H.BoxId 
 	--inner join adrControllerMaster CM on h.boxid=CM.EquipmentId and h.ControllerID= CM.ControllerPositionId	and h.DCSIM=cm.DCSIMId
	left join rvlfAlarm a on h.MessageInID=a.MessageInID  
	LEFT JOIN rvlfVehicleType vt on MD.SubTypeId=vt.VehicleTypeId	              
	WHERE  H.OriginDateTime BETWEEN CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109) 
	and  MD.VehicleId = @VehicleID and MD.IsDelete=0 --and  cm.IsDeleted=0 and
	--(@controller is null or @controller='' or @controller='ALL' or  cm.ControllerName=@controller)
	--and CT.OperationTypeID IN (select OperationTypeID from @OperationTypeID) AND CommInfo1 IS NOT NULL  and H.BoxMsgInTypeId in (1,7,24,15,14)                
   
UNION ALL              
   /************-------------------------------***** Get Commands details---------------------------------------******************/                  
    SELECT NULL as MessageInID,null as Customprop,oh.BoxId ,MD.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,
	NULL as Speed, 0 as Heading,[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),        
	--SentDateTime = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime), 
    Md.EquipmentName as  VehicleDescription,'' as origindatetime,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId,
	--CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 14) AS RoadsAPITime,   
	                  SentDateTime AS RoadsAPITime,
    TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime), 
       DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [TimestampSort],
    --CASE WHEN OH.BoxCmdOutTypeId = 39 OR OH.BoxCmdOutTypeId = 4 THEN dbo.rvlf_fn_GetCmdMsgDetails(OH.CustomProp + ',', OH.BoxCmdOutTypeId, VA.BoxID) ELSE BoxcmdTypeDesc END as MessageDetails,
	BoxcmdTypeDesc as MessageDetails,
	 OH.UserId,Priority, 
    /**************** Changed the Acknowledgement to be return based on the value ************/                  
    CASE WHEN Acknowledged = 1 THEN 'True' WHEN Acknowledged = 0 THEN 'False' WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Update Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect' WHEN  Acknowledged = 5 THEN 'No Communication'                  
      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'                  
      ELSE 'Nothing' END AS Acknowledged,                  
    CASE WHEN Acknowledged = 1 THEN 'Acknowledged' WHEN Acknowledged = 0 THEN 'Not Acknowledged' WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Upgrade Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect'   WHEN  Acknowledged = 5 THEN 'No Communication'  
      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'      
      ELSE '' END AS AckStatus,                 
    'N/A' as Address,@Distance as Units,--'' as Direction ,/*null as mapitFunction,*/'setValue('' '')' as jsFunction, NULL as IgnitionStatus,
	NULL as StreetAddress, NULL as IsDefaultAlarm--,null as isMapIT
	 ,MD.VehicleId,vt.VehicleTypeName , isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo  
	,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
	,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,NULL,NULL,null,0,0,null,null           
    FROM rvlfMsgOutHst OH                  
    --INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID 
	--INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID                  
    INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId  
	INNER JOIN rvlfMAKDevices MD on MD.BoxId=oH.BoxId
	--inner join adrControllerMaster CM on OH.boxid=CM.EquipmentId and OH.ControllerID= CM.ControllerPositionId	   
	LEFT JOIN rvlfVehicleType vt on MD.SubTypeId=vt.VehicleTypeId                
    WHERE  SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)                  
    AND MD.VehicleID = @VehicleID and CT.OperationTypeId IN (select OperationTypeID from @OperationTypeID)
) as a ORDER BY Timestamp desc, MessageInID DESC 
End              
End 
GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng2_Ador_bkp]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RVLT_SP_GetLatLng2_Ador_bkp]    
(                  
 @vehicleId varchar(50)=null,                  
 @startdate as datetime =null,
 @enddate datetime =null,
 @interval as int=2000,                  
 @orderby varchar(10)='desc',                  
 @bigQueryingUser bigint = 292,                  
 @bitIsMDTMsg bit=0 ,                
 @bitIsMessage bit = 0,          
 @bigLastHours int = null ,                  
 @controllerID int=null                    
)
as
/******************************************************************************/                  
--2013-01-30 11:12:17.890              
-- Name  : RVLT_SP_GetLatLng2_Ador 805,'2017-11-29 10:00:00 AM','2017-11-29 11:00:00 PM',2000,'desc',453              
-- Name  : RVLT_SP_GetLatLng2_Ador 216,'2017-07-24 08:00:00 AM','2017-07-24 10:00:00 PM',2000,'desc',              
-- Description : To get the messages that needs to be shown in the grid                  
-- Author  : T. Sathish Kumar                  
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
/******************************************************************************/      

Begin                  
	DECLARE @Lang varchar(50),  @LangSetting varchar(20)                               
	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 
	DECLARE @OperationTypeID table (OperationTypeID bigint) 
    DECLARE @controllerType tinyint= (select VehicleTypeId from rvlfVehicle where VehicleId=@vehicleId)
	               
    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)  ,
			@Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings                
    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    
	inner join rvlfOrganization o on u.OrganizationId = o.OrganizationId                               
                      
	--Get the operation id of priviledged user---   	
	INSERT INTO @OperationTypeID  
	SELECT OperationTypeID FROM rvlfUserGroupSecurity s                   
     WHERE s.ModuleId in(22,26) and s.UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser)                   
                      
	-------------------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)  	            
    -----------------------------------------------------------------------                
     
IF(@controllerType=1) 
BEGIN                            
   SELECT *,ROW_NUMBER() over (order by timestamp) as AutoID  
   FROM( 
		Select DISTINCT(H.MessageInID),H.CustomProp,H.BoxId, VA.BoxID as DeviceID, 
			(CASE WHEN cast(ISNULL(H.Latitude,0) as decimal(14,6)) = 0 THEN 1 ELSE ValidGps END) AS ValidGPS, 
			cast(ISNULL(H.Latitude,0) as decimal(14,6)) as Latitude, cast(ISNULL(H.Longitude,0) as decimal(14,6)) as Longitude,   
			H.NearestLandMark as Distance,'-'  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,H.OriginDateTime),                
			DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
			v.VehicleDescription,    H.OriginDateTime,BoxMsgInTypeDesc as [Message],H.BoxMsgInTypeId as BoxMsgInTypeId , 
			CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,H.OriginDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD					(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,H.OriginDateTime)), 14) AS RoadsAPITime,  
			TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,H.OriginDateTime),   
			DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,H.OriginDateTime)) as [TimestampSort],                                 
			Case when H.BoxMsgInTypeId = 114 and CHARINDEX('18;GPRS',H.CustomProp,0) <> 0  THEN 'Send Health Status'      
			when h.BoxMsgInTypeId in (4,7,13,24) then ct.BoxMsgInTypeName +' '+isnull(cast(H.CmdId as varchar),'')       	
			ELSE dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)
			END  as MessageDetails, 0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,
			H.StreetAddress AS Address, @Distance as Units,
			Replace(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''')  as StreetAddress,
			CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,          
			v.vehicleid ,vt.VehicleTypeName,isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo,
		 (isnull(cast(H.controllerID as varchar(2)),'-')) AS controllerID ,isnull(p.RefID,'-') as RefID,isnull(p.CmdId,'-') as CmdId,h.DCSIM,
		isnull([Seconday_Current_Limit(IDC)],'-') as Param1,isnull(Secondary_Voltage,'-') as Param2
		,isnull(Spark_Rate,'-') as Param3,isnull(Operating_Charge_Ratio,'-') as Param4
		,isnull(Optinal_Input_Power,'-') as Param5,isnull(Corona_Power,'-') as Param6,isnull(VDC_peak,'-') as Param7
		,isnull(VDC_Through,'-') as Param8,isnull(IAC_PRI,'-') as Param9,isnull(Operating_IDC_Limit,'-') as Param10
		,isnull(Mains_Frequency,'-') as Param11,isnull(Total_Accumulated_Spark,'-') as Param12,
		isnull(Total_Operating_Time,'-') as Param13,isnull(Operating_Corona_Energy,'-') as Param14
		,isnull(Input_Energy,'-') as Param15,isnull(Secondary_current_Limit,'-') as Param16
		,isnull(Sec_Current_Drop_AfterSpark,'-') as Param17,isnull(T_Recovery_cyc,'-') as Param18
		,isnull(T_Fast_Ramp_cyc,'-') as Param19,isnull(Charge_Ratio,'-') as Param20
		,isnull(Recharge_HW,'-') as Param21,isnull(BC_IDC_Min,'-') as Param22
		,isnull(RAP_IDC_Limit,'-') as Param23,isnull(BC_CR_Maximum,'-') as Param24
		,isnull(Load_Status1_IDC_Limit,'-') as Param25,isnull(LS_1_V_Limit,'-') as Param26
		,isnull(LS_1_IDC_Setbk,'-') as Param27,isnull(RAP_TM1_Pause,'-') as Param28
		,isnull(RAP_TM1_Run,'-') as Param29,isnull(RAP_TM2_Pause,'-') as Param30
		,isnull(RAP_TM2_Run,'-') as Param31,isnull(RAP_TM3_Pause,'-') as Param32
		,isnull(RAP_TM3_Run,'-') as Param33,
		isnull((case when RAP_MOT1_ON_OFF=0 then 'OFF' when RAP_MOT1_ON_OFF=1 then 'ON' else '-'end ),'-') as Param34
		,isnull((case when RAP_MOT2_ON_OFF=0 then 'OFF' when RAP_MOT2_ON_OFF=1 then 'ON' else '-'end ),'-') as Param35,
		isnull((case when RAP_MOT3_ON_OFF=0 then 'OFF' when RAP_MOT3_ON_OFF=1 then 'ON' else '-'end ),'-') as Param36
		,isnull((case when RAP_CONT_ON_OFF=0 then 'OFF' when RAP_CONT_ON_OFF=1 then 'ON' else '-'end ),'-') as Param37,
		isnull((case when Back_Corona_ON_OFF=0 then 'OFF' when Back_Corona_ON_OFF=1 then 'ON' else '-'end ),'-') as Param38
		,isnull((case when HT_ON_OFF=0 then 'OFF' when HT_ON_OFF=1 then 'ON' else '-'end ),'-') as Param39
		,isnull(Sec_Curr_drop_after_dbleSpark,'-') as Param40
		,isnull(MAX_Spark_Rate,'-') as Param41,isnull(TQuench_CYC,'-') as Param42
		,isnull(Back_Corona_MEAS,'-') as Param43,isnull(BC_IDC_Step,'-') as Param44
		,isnull(BC_Hold_Time,'-') as Param45,isnull([LS-1_CR],'-') as Param46
		,isnull(RECHARGE_FIRING,'-') as Param47,
		ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Temperature: #','°C$'),'') AS CurrTemp,
		ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Humidity: #','%$'),'') AS Humidity,
		ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Pressure: #','hPa$'),'') AS Pressure,isnull(h.Alarm,0) as Alarm,
		case when H.BoxMsgInTypeId in (24,7) then 1 else 0 end as Showdetails--,CM.ControllerPositionId,CM.ControllerName
		FROM rvlfMsgInHst H
		LEFT JOIN rvlfMsgInHstParam_PIII P on h.MessageInID=p.Messageinid
		INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                     
		INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId    
		INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
		INNER JOIN rvlfMAKDevices MD on MD.BoxId=H.BoxId   
		--inner join adrControllerMaster CM on h.boxid=CM.EquipmentId and h.ControllerID= CM.ControllerPositionId	
		LEFT JOIN rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId	              
		WHERE  H.OriginDateTime BETWEEN CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109) 
		and  VA.VehicleId = @VehicleID and MD.IsDelete=0 and 
		(@controllerID is null or @controllerID=0 or p.controllerID=@controllerID)
		and CT.OperationTypeID IN (select OperationTypeID from @OperationTypeID) AND CommInfo1 IS NOT NULL   and H.BoxMsgInTypeId in (4,13,15,14)               
   
UNION ALL                  
   /************-------------------------------***** Get Commands details---------------------------------------******************/                  
    SELECT NULL as MessageInID,null as Customprop,null as BoxId,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,
	NULL as Speed, 0 as Heading,[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),        
	SentDateTime = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime), 
    V.VehicleDescription,'' as origindatetime,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId,
	CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 14) AS RoadsAPITime,                      
    TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime), 
       DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [TimestampSort],
    CASE WHEN OH.BoxCmdOutTypeId = 39 OR OH.BoxCmdOutTypeId = 4 THEN dbo.rvlf_fn_GetCmdMsgDetails(OH.CustomProp + ',', OH.BoxCmdOutTypeId, VA.BoxID)                        ELSE BoxcmdTypeDesc END as MessageDetails,
	OH.UserId,Priority, 
    /**************** Changed the Acknowledgement to be return based on the value ************/                  
    CASE WHEN Acknowledged = 1 THEN 'True' WHEN Acknowledged = 0 THEN 'False' WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Update Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect' WHEN  Acknowledged = 5 THEN 'No Communication'                  
      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'                  
      ELSE 'Nothing' END AS Acknowledged,                  
    CASE WHEN Acknowledged = 1 THEN 'Acknowledged' WHEN Acknowledged = 0 THEN 'Not Acknowledged' WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Upgrade Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect'   WHEN  Acknowledged = 5 THEN 'No Communication'  
      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'      
      ELSE '' END AS AckStatus,                  
    'N/A' as Address,@Distance as Units,--'' as Direction ,/*null as mapitFunction,*/'setValue('' '')' as jsFunction, NULL as IgnitionStatus,
	NULL as StreetAddress, NULL as IsDefaultAlarm,--null as isMapIT ,
	va.vehicleid,vt.VehicleTypeName , isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo ,
	NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
	NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,null,NULL,NULL,null,0,0
	--,null,null
    FROM rvlfMsgOutHst OH                  
    INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID 
	INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID                  
    INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId  
	INNER JOIN rvlfMAKDevices MD on MD.BoxId=oH.BoxId 
	--inner join adrControllerMaster CM on OH.boxid=CM.EquipmentId and OH.ControllerID= CM.ControllerPositionId	
	LEFT JOIN rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId                
    WHERE  SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)                  
    AND VA.VehicleID = @VehicleID and CT.OperationTypeId IN (select OperationTypeID from @OperationTypeID)
) as a ORDER BY Timestamp desc, MessageInID DESC 
END
ELSE IF(@controllerType=2) 
BEGIN                            
   SELECT *,ROW_NUMBER() over (order by timestamp) as AutoID                     
   FROM( 
		Select DISTINCT(H.MessageInID),H.CustomProp,H.BoxId, VA.BoxID as DeviceID, 
			(CASE WHEN cast(ISNULL(H.Latitude,0) as decimal(14,6)) = 0 THEN 1 ELSE ValidGps END) AS ValidGPS, 
			cast(ISNULL(H.Latitude,0) as decimal(14,6)) as Latitude, cast(ISNULL(H.Longitude,0) as decimal(14,6)) as Longitude,   
			H.NearestLandMark as Distance,'-'  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,H.OriginDateTime),                
			DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
			v.VehicleDescription,    H.OriginDateTime,BoxMsgInTypeDesc as [Message],H.BoxMsgInTypeId as BoxMsgInTypeId , 
			CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,H.OriginDateTime)), 103) + ' '  + convert(VARCHAR(8), 
			DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,H.OriginDateTime)), 14) AS RoadsAPITime,    
			TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,H.OriginDateTime),   
			DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,H.OriginDateTime)) as [TimestampSort],                                 
			Case when H.BoxMsgInTypeId = 114 and CHARINDEX('18;GPRS',H.CustomProp,0) <> 0  THEN 'Send Health Status'      
			when h.BoxMsgInTypeId in (4,7,13,24) then ct.BoxMsgInTypeName +' '+isnull(cast(H.CmdId as varchar),'')       	
			ELSE dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)
			END as MessageDetails, 0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,
			H.StreetAddress AS Address, @Distance as Units,	 
			Replace(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''')  as StreetAddress,
			CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,          
			v.vehicleid ,vt.VehicleTypeName,isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo
	, (isnull(cast(H.controllerID as varchar(2)),'-')) AS controllerID,ISNULL(P.RefID,'-') AS RefID,ISNULL(P.CmdId,'-') AS CmdId,H.DCSIM,
	ISNULL(P.Primary_Voltage_Value,'-') AS Param1,ISNULL(P.Primary_Current_Value,'-') AS Param2
	,ISNULL(P.Primary_Power_Value,'-') AS Param3,ISNULL(P.Secondary_Voltage_Value,'-') AS Param4,
	ISNULL(P.Secondary_Current_Value,'-') AS Param5,ISNULL(P.Spark_Per_Minute,'-') AS Param6
	,ISNULL(P.Arcs_Per_Minute,'-') AS Param7,ISNULL(P.Under_Voltage_TripMode,'-') AS Param8,
	ISNULL(P.Program_no_of_Rapper,'-') AS Param9,ISNULL(P.Primary_Voltage_limit,'-') AS Param10
	,ISNULL(P.Primary_Current_Limit,'-') AS Param11,ISNULL(P.Secondary_Voltage_Limit,'-') AS Param12,
	ISNULL(P.Secondary_Current_Limit,'-') AS Param13,ISNULL(P.Under_Voltage_Set_Point,'-') AS Param14,
	ISNULL(P.Secondary_Current_Peak_Limit,'-') AS Param15,ISNULL(P.Ramp,'-') AS Param16,ISNULL(P.Pedestal,'-') AS Param17,
	ISNULL(P.Quench_Time,'-') AS Param18,ISNULL(P.Spark_Rate,'-') AS Param19,ISNULL(P.IE_Charge_Halfcycle,'-') AS Param20,
	ISNULL(P.IE_Discharge_Cycle,'-') AS Param21,ISNULL(P.IE_Background_Power,'-') AS Param22	,
	ISNULL(P.IE_Optimise_Timer,'-') AS Param23,ISNULL(P.Power_Down_Rapping,'-') AS Param24,
	ISNULL(P.Rapper1_Interval_Timer,'-') AS Param25,ISNULL(P.Rapper1_On_timer,'-') AS Param26,
	ISNULL(P.Rapper2_Interval_timer,'-') AS Param27,ISNULL(P.Rapper2_On_Timer,'-') AS Param28,
	ISNULL(P.Rapper3_Interval_Timer,'-') AS Param29,ISNULL(P.Rapper3_On_Timer,'-') AS Param30,
	ISNULL(P.Rapper4_Interval_Timer,'-') AS Param31,ISNULL(P.Rapper4_On_Timer,'-') AS Param32,ISNULL(P.Phase_Back,'-') AS Param33,
	null as Param34,null as Param35,null as Param36,null as Param37,null as Param38,null as Param39,null as Param40,null as Param41,
	null as Param42,null as Param43,null as Param44,null as Param45,null as Param46,null as Param47,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Temperature: #','°C$'),'') AS CurrTemp,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Humidity: #','%$'),'') AS Humidity,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Pressure: #','hPa$'),'') AS Pressure ,isnull(h.Alarm,0) as Alarm,
	case when H.BoxMsgInTypeId in (24,7) then 1 else 0 end as Showdetails--,CM.ControllerPositionId,CM.ControllerName
	FROM rvlfMsgInHst H                   
	left JOIN rvlfMsgInHstParam_PR P on h.MessageInID=p.Messageinid
	INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                     
	INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                      
	INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
	INNER JOIN rvlfMAKDevices MD on MD.BoxId=H.BoxId 
--	inner join adrControllerMaster CM on h.boxid=CM.EquipmentId and h.ControllerID= CM.ControllerPositionId	and h.DCSIM=cm.DCSIMId
	left join rvlfAlarm a on h.MessageInID=a.MessageInID  
	LEFT JOIN rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId	              
	WHERE  H.OriginDateTime BETWEEN CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109) 
	and  VA.VehicleId = @VehicleID and MD.IsDelete=0 and 
	(@controllerID is null or @controllerID=0 or p.controllerID=@controllerID)
	and CT.OperationTypeID IN (select OperationTypeID from @OperationTypeID) AND CommInfo1 IS NOT NULL  and H.BoxMsgInTypeId in (7,24,15,14)                
   
UNION ALL              
   /************-------------------------------***** Get Commands details---------------------------------------******************/                  
    SELECT NULL as MessageInID,null as Customprop,null as BoxId,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,
	NULL as Speed, 0 as Heading,[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),        
	SentDateTime = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime), 
    V.VehicleDescription,'' as origindatetime,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId,
	CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 14) AS RoadsAPITime,                      
    TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime), 
       DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [TimestampSort],
    CASE WHEN OH.BoxCmdOutTypeId = 39 OR OH.BoxCmdOutTypeId = 4 THEN dbo.rvlf_fn_GetCmdMsgDetails(OH.CustomProp + ',', OH.BoxCmdOutTypeId, VA.BoxID)                        ELSE BoxcmdTypeDesc END as MessageDetails,
	 OH.UserId,Priority, 
    /**************** Changed the Acknowledgement to be return based on the value ************/                  
    CASE WHEN Acknowledged = 1 THEN 'True' WHEN Acknowledged = 0 THEN 'False' WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Update Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect' WHEN  Acknowledged = 5 THEN 'No Communication'                  
      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'                  
      ELSE 'Nothing' END AS Acknowledged,                  
    CASE WHEN Acknowledged = 1 THEN 'Acknowledged' WHEN Acknowledged = 0 THEN 'Not Acknowledged' WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Upgrade Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect'   WHEN  Acknowledged = 5 THEN 'No Communication'  
      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'      
      ELSE '' END AS AckStatus,                 
    'N/A' as Address,@Distance as Units,--'' as Direction ,/*null as mapitFunction,*/'setValue('' '')' as jsFunction, NULL as IgnitionStatus,
	NULL as StreetAddress, NULL as IsDefaultAlarm--,null as isMapIT
	 ,va.vehicleid,vt.VehicleTypeName , isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo  
	,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
	,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,NULL,NULL,null,0,0--,null,null           
    FROM rvlfMsgOutHst OH                  
    INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID 
	INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID                  
    INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId  
	INNER JOIN rvlfMAKDevices MD on MD.BoxId=oH.BoxId
	--inner join adrControllerMaster CM on OH.boxid=CM.EquipmentId and OH.ControllerID= CM.ControllerPositionId	   
	LEFT JOIN rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId                
    WHERE  SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)                  
    AND VA.VehicleID = @VehicleID and CT.OperationTypeId IN (select OperationTypeID from @OperationTypeID)
) as a ORDER BY Timestamp desc, MessageInID DESC 
End              
End 
GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng2_Optimzd]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[RVLT_SP_GetLatLng2_Optimzd]    
(                  
 @vehicleId varchar(50)=null,                  
 @startdate as datetime =null,
 @enddate datetime =null,
 @interval as int=2000,                  
 @orderby varchar(10)='desc',                  
 @bigQueryingUser bigint = NULL,                  
 @bitIsMDTMsg bit=0 ,                
 @bitIsMessage bit = 0,          
 @bigLastHours int = null                   
)
as
/******************************************************************************/                  
--2013-01-30 11:12:17.890              
-- Name  : RVLT_SP_GetLatLng2 27,'2016-12-25 08:00:00 AM','2016-06-25 08:00:00 PM',2000,'desc',14              
-- Name  : RVLT_SP_GetLatLng2_Optimzd 188,'2017-07-18 04:00:00 PM','2017-07-18 10:00:00 PM',2000,'desc',14              
-- Description : To get the messages that needs to be shown in the grid                  
-- Author  : T. Sathish Kumar                  
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
/******************************************************************************/      

Begin                  
	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     
               
                 
	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)  ,
			@Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings                
    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    
	inner join rvlfOrganization o on u.OrganizationId = o.OrganizationId                               
                      
	DECLARE @userIds table (userId bigint)                  
                   
	DECLARE @bigVehOrganizationID  bigint =@bigOrganizationID--(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)  	            
    -----------------------------------------------------------------------                
                --print @startDate  
                --print @endDate  
 DECLARE @intTotalRecords int                  
 SELECT @intTotalRecords = COUNT(H.MessageInID) from rvlfMsgInHst H                   
  INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                  
  INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                                   
    where H.ValidGps=0 and OriginDateTime between CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) and  VA.VehicleId = @VehicleID              
    and CT.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s                   
   WHERE s.ModuleId = 26 and s.UserGroupId =@intUserGroupId
   )                  

declare @DeviceTypeID int=0
select @DeviceTypeID=VehicleTypeId from rvlfVehicle where VehicleId=@vehicleId
     
    IF @intTotalRecords < @interval OR @interval = 30                  
  BEGIN     
	if(@DeviceTypeID=1)
		begin
			 select *,ROW_NUMBER() over (order by timestamp) as AutoID            
				from (                  
		   select distinct(H.MessageInID),H.BoxId,VA.BoxID as DeviceID,H.BoxMsgInTypeId,H.CommInfo1,H.CommInfo2,H.CustomProp,H.StreetAddress,H.SequenceNum,H.IsArmed,H.IsProcessed,H.IsArchived,H.ControllerID,H.Alarm,H.Batt_Volt,H.Batt_Current,H.Batt_LstRreplacement,H.Chrg_Alternator,H.Coolant_Temp,H.EngineSpeed,dbo.rvlf_fn_GetHHMMSSFromSec(H.Engine_RunTime) as Engine_RunTime
	   ,H.FuelLevel,H.Tot_Watts,H.Tot_VA,H.Tot_VAr,H.Gen_KWh,H.Gen_KVAh,H.Gen_KVArh,H.Gen_Freq,H.Gen_AvgPF,H.Gen_L1_PF,H.Gen_L1_VAr,H.Gen_L1_VA,H.Gen_L1_Watts,H.Gen_L1_Current,H.Gen_L2_PF,H.Gen_L2_VAr,H.Gen_L2_VA,H.Gen_L2_Watts,H.Gen_L2_Current,H.Gen_L3_PF,H.Gen_L3_VAr,H.Gen_L3_VA,H.Gen_L3_Watts,H.Gen_L3_Current,H.Gen_LNVolt,H.Gen_LLVolt,H.NumofStarts,H.Oil_Temp,H.Oil_Pressure,H.GateWayID,H.ComMode, MD.EquipmentSrNo,
			[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime),                
			DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime), 
			TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,OriginDateTime),
		   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [TimestampSort],v.vehicleid,vt.VehicleTypeName as CustomerName,vt.VehicleTypeId,MD.ContactNo,0 as isMapIT,CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,H.StreetAddress as Address, @Distance as Units, 
		   'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,(CASE WHEN cast(ISNULL(H.Latitude,0) as decimal(14,6)) = 0 THEN 1 ELSE ValidGps END) AS ValidGPS, 
		   cast(ISNULL(H.Latitude,0) as decimal(14,6)) as Latitude, cast(ISNULL(H.Longitude,0) as decimal(14,6)) as Longitude, 0  as Speed, CASE WHEN H.Speed = 0 OR H.ValidGps > 0 THEN -1 ELSE CAST(Heading as varchar(3))  END as Heading, v.VehicleDescription, OriginDateTime, BoxMsgInTypeDesc as [Message],'' as MessageDetails,0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,NULL as S1_Tot_Watts,NULL as S1_Tot_VA,NULL as S1_Tot_VAr,NULL as S1_KWh,NULL as S1_KVAh,NULL as S1_KVArh,NULL as S1_Freq,NULL as S1_AvgPF,NULL as S1_L1_PF,NULL as S1_L1_VAr,NULL as S1_L1_VA,NULL as S1_L1_Watts,NULL as S1_L1_Current,NULL as S1_L2_PF,NULL as S1_L2_VAr,NULL as S1_L2_VA,NULL as S1_L2_Watts,NULL as S1_L2_Current,NULL as S1_L3_PF,NULL as S1_L3_VAr,NULL as S1_L3_VA,NULL as S1_L3_Watts,NULL as S1_L3_Current,NULL as S2_Tot_Watts,NULL as S2_Tot_VA,NULL as S2_Tot_VAr,NULL as S2_KWh,NULL as S2_KVAh,NULL as S2_KVArh,NULL as S2_Freq,NULL as S2_AvgPF,NULL as S2_L1_PF,NULL as S2_L1_VAr,NULL as S2_L1_VA,NULL as S2_L1_Watts,NULL as S2_L1_Current,NULL as S2_L2_PF,NULL as S2_L2_VAr,NULL as S2_L2_VA,NULL as S2_L2_Watts,NULL as S2_L2_Current,NULL as S2_L3_PF,NULL as S2_L3_VAr,NULL as S2_L3_VA,NULL as S2_L3_Watts,NULL as S2_L3_Current,NULL as Main_Gen_LNVolt, H.GEN_L1_N_VOLT,H.GEN_L2_N_VOLT,H.GEN_L3_N_VOLT,H.GEN_L1_L2_VOLT,H.GEN_L2_L3_VOLT,H.GEN_L1_L3_VOLT,NULL As S1_L1_N_Voltage,NULL As S1_L2_N_Voltage,NULL As S1_L3_N_Voltage,NULL As S1_L1_L2_Voltage,NULL As S1_L2_L3_Voltage,NULL As S1_L3_L1_Voltage,NULL As S2_L1_N_Voltage,NULL As S2_L2_N_Voltage,NULL As S2_L3_N_Voltage,NULL As S2_L1_L2_Voltage,NULL As S2_L2_L3_Voltage,NULL As S2_L3_L1_Voltage,null as S1_LN_Volt,null as S1_LL_Volt,null as S2_LN_Volt,null as S2_LL_Volt
		   from rvlfMsgInHst_Techno H                   
			INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                  
			INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                  
			INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
			inner join rvlfMAKDevices MD on MD.BoxId=H.BoxId   
			left join rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId
	              
		   where  OriginDateTime between                  
		   CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) and  VA.VehicleId = @VehicleID             
		   and MD.IsDelete=0 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 H.BOXMSGINTYPEID NOT IN(102,103)         
			AND CommInfo1 IS NOT NULL                  
		  AND (@bitIsMDTMsg=0 OR H.BoxMsgInTypeId IN(77,98,109,110,111)) and h.CustomProp not like '%18;GPRS%') as a order by Timestamp desc, MessageInID desc                  
       end
	 else if(@DeviceTypeID=2)
		begin
			 select *,ROW_NUMBER() over (order by timestamp) as AutoID            
				from (                  
		   select distinct(H.MessageInID),H.BoxId,VA.BoxID as DeviceID,H.BoxMsgInTypeId,H.CommInfo1,H.CommInfo2,H.CustomProp,H.StreetAddress,H.SequenceNum,H.IsArmed,H.IsProcessed,H.IsArchived,H.ControllerID,H.Alarm,NULL as Batt_Volt,'' as Batt_Current,'' as Batt_LstRreplacement,'' as Chrg_Alternator,NULL as Coolant_Temp,NULL as EngineSpeed,NULL as Engine_RunTime,NULL as FuelLevel,NULL as Tot_Watts,NULL as Tot_VA,NULL as Tot_VAr,NULL as Gen_KWh,NULL as Gen_KVAh,NULL as Gen_KVArh,NULL as Gen_Freq,NULL as Gen_AvgPF,NULL as Gen_L1_PF,NULL as Gen_L1_VAr,NULL as Gen_L1_VA,NULL as Gen_L1_Watts,NULL as Gen_L1_Current,NULL as Gen_L2_PF,NULL as Gen_L2_VAr,NULL as Gen_L2_VA,NULL as Gen_L2_Watts,NULL as Gen_L2_Current,NULL as Gen_L3_PF,NULL as Gen_L3_VAr,NULL as Gen_L3_VA,NULL as Gen_L3_Watts,NULL as Gen_L3_Current,NULL as Gen_LNVolt,NULL as Gen_LLVolt,NULL as NumofStarts,NULL as Oil_Temp,NULL as Oil_Pressure,H.GateWayID,H.ComMode, MD.EquipmentSrNo,
			[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime),                
			DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime), 
			TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,OriginDateTime),
		   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [TimestampSort],v.vehicleid,vt.VehicleTypeName as CustomerName,vt.VehicleTypeId,MD.ContactNo,0 as isMapIT,CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,H.StreetAddress as Address, @Distance as Units, 
		   'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,(CASE WHEN cast(ISNULL(H.Latitude,0) as decimal(14,6)) = 0 THEN 1 ELSE ValidGps END) AS ValidGPS, 
		   cast(ISNULL(H.Latitude,0) as decimal(14,6)) as Latitude, cast(ISNULL(H.Longitude,0) as decimal(14,6)) as Longitude, 0  as Speed, CASE WHEN H.Speed = 0 OR H.ValidGps > 0 THEN -1 ELSE CAST(Heading as varchar(3))  END as Heading, v.VehicleDescription, OriginDateTime, BoxMsgInTypeDesc as [Message],'' as MessageDetails,0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,H.S1_Tot_Watts,H.S1_Tot_VA,H.S1_Tot_VAr,H.S1_KWh,H.S1_KVAh,H.S1_KVArh,H.S1_Freq,H.S1_AvgPF,H.S1_L1_PF,H.S1_L1_VAr,H.S1_L1_VA,H.S1_L1_Watts,H.S1_L1_Current,H.S1_L2_PF,H.S1_L2_VAr,H.S1_L2_VA,H.S1_L2_Watts,H.S1_L2_Current,H.S1_L3_PF,H.S1_L3_VAr,H.S1_L3_VA,H.S1_L3_Watts,H.S1_L3_Current,H.S2_Tot_Watts,H.S2_Tot_VA,H.S2_Tot_VAr,H.S2_KWh,H.S2_KVAh,H.S2_KVArh,H.S2_Freq,H.S2_AvgPF,H.S2_L1_PF,H.S2_L1_VAr,H.S2_L1_VA,H.S2_L1_Watts,H.S2_L1_Current,H.S2_L2_PF,H.S2_L2_VAr,H.S2_L2_VA,H.S2_L2_Watts,H.S2_L2_Current,H.S2_L3_PF,H.S2_L3_VAr,H.S2_L3_VA,H.S2_L3_Watts,H.S2_L3_Current,H.Main_Gen_LNVolt,H.S1_L1_N_Voltage,H.S1_L2_N_Voltage,H.S1_L3_N_Voltage,H.S1_L1_L2_Voltage,H.S1_L2_L3_Voltage,H.S1_L3_L1_Voltage,H.S2_L1_N_Voltage,H.S2_L2_N_Voltage,H.S2_L3_N_Voltage,H.S2_L1_L2_Voltage,H.S2_L2_L3_Voltage,H.S2_L3_L1_Voltage,NULL as GEN_L1_N_VOLT,NULL as GEN_L2_N_VOLT,NULL as GEN_L3_N_VOLT,NULL as GEN_L1_L2_VOLT,NULL as GEN_L2_L3_VOLT,NULL as GEN_L1_L3_VOLT,isnull(H.S1_LN_Volt,'0') as S1_LN_Volt,isnull(S1_LL_Volt,'0') as S1_LL_Volt,isnull(S2_LN_Volt,'0') as S2_LN_Volt,isnull(S2_LL_Volt,'0') as S2_LL_Volt  from rvlfMsgInHst_Techno_355 H                   
			INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                  
			INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                  
			INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
			inner join rvlfMAKDevices MD on MD.BoxId=H.BoxId   
			left join rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId
	              
		   where  OriginDateTime between                  
		   CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) and  VA.VehicleId = @VehicleID             
		   and MD.IsDelete=0 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 H.BOXMSGINTYPEID NOT IN(102,103)         
			AND CommInfo1 IS NOT NULL                  
		  AND (@bitIsMDTMsg=0 OR H.BoxMsgInTypeId IN(77,98,109,110,111)) and h.CustomProp not like '%18;GPRS%') as a order by Timestamp desc, MessageInID desc  
		end
		
   -- --------------Get the Latest value for Device ------------------------------------------------------------------                 
   select B.BoxId,LastLatitude,LastLongitude,                  
    CASE WHEN H.BoxMsgInTypeId =51 OR H.BoxMsgInTypeId =90  THEN ''
     WHEN ISNULL(H.Speed,0) = 0 THEN '-'   ELSE CAST(CAST(LastSpeed  * @ConversionFactor as int) as varchar(10)) END as LastSpeed,                  
    CASE WHEN LastSpeed = 0 OR LastCommunicatedDateTime<> LastStatusDateTime                   
    THEN -1 ELSE B.Heading END as Heading,                  
    Replace(ISNULL( LastStreetAddress, 'Address is not resolved'),'''','\''')  as LastStreetAddress,                  
    DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,LastValidDateTime)) as LastStatusDateTime,                  
    B.NearestLandmark, V.VehicleId,V.VehicleDescription,                  
    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(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Idling:',';') 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 (dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SENSOR_STATUS=',';')) = 'ON'                         
         THEN 1 ELSE 0 End End                  
      ELSE 2 END as IgnitionStatus,                  
    @Distance as Units,                  
   -- CASE WHEN H.BoxMsgInTypeId = 51 THEN                
   --    (case when @Lang='LanguageArNew' THEN N'*.1B 'D319) DD ' when @Lang='LanguageHindi' THEN N'8	M	*	@	!	 	G	 2	?		 		2	M	2			(	'  ELSE 'Speed Violated for ' END)                   
   --   --+CAST(CAST(Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @Distance                   
   --+'(' + dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'                  
   -- ELSE                   
     dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)--CT.BoxMsgInTypeDesc                   
    --END
	+ 
  ISNULL(' (T: ' + dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Temperature: #','$') + ', ' +  
  'H: ' + dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Humidity: #','$') + ', ' +  
  'P: ' + dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Pressure: #','$') + ', ' +  
  'W: ' + dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Wind Speed: #','$') 
		+ dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Wind Direction: #','$') + ')', '') as MessageDetails,                   
    ISNULL(CASE WHEN (L.LandMarkID IS NULL OR H.LandMarkID = 0) THEN '-' ELSE isnull(L.LandmarkName,'-') END,'-') AS Landmark,                  
    L.LandmarkName as LandmarkName, L.Latitude as LandmarkLatitude, L.Longitude as LandmarkLongitude, L.Radius as LandmarkRadius,               
    replace(L.StreetAddress,@NewLine,' ') As LandMarkAddress ,H.RoadSpeedLimit              
    from rvlfBoxId B INNER JOIN rvlfVehicleAssignment VA on B.BoxId = VA.BoxId                  
    INNER JOIN rvlfMsgInHst H ON  H.BoxId=VA.BoxId AND H.OriginDateTime=B.LastValidDateTime AND H.Latitude=B.LastLatitude AND H.Longitude=B.LastLongitude                   
    INNER JOIN rvlfVehicle V on V.VehicleId = VA.VehicleId                  
    --LEFT OUTER join rvlfTripDetails t ON h.MessageInID = t.StartMessageInID                  
    --LEFT OUTER JOIN rvlfTripDetails d ON h.MessageInID = d.EndMessageInID                  
    INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                  
    LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID                      
    where VA.VehicleId = @vehicleId                    
    --AND H.BOXMSGINTYPEID NOT IN(102,103)                  
    --AND (DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,LastStatusDateTime))                  
    --BETWEEN CONVERT(DateTime,@startdate,109) and CONVERT(DateTime,@enddate,109))          
         
 --Get Geozone details            
 Select distinct dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'GeozoneId=',';') as GeozoneNo    
 ,G.GeozoneName,G.GeozoneType,latlng = STUFF((SELECT '~' + cast(Latitude as varchar)+'#' + cast(Longitude as varchar)            
	FROM rvlfGeozoneSet b WHERE b.GeozoneNo = GS.GeozoneNo FOR XML PATH('')), 1, 1, ''),@bigOrganizationID,G.OrganizationId,
	(SELECT IsRestricted FROM rvlfGeozoneRestricted WHERE VehicleId=@VehicleID AND GeozoneNo=G.GeozoneNo) AS IsRestricted,
	ISNULL(G.Radius,0) AS CircleRadius, G.OrganizationId 
       --H.CustomProp          
 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                                             
    INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID              
    --inner join rvlfOrganizationGeozone G on G.GeozoneId=CAST(SUBSTRING(H.CustomProp,CHARINDEX('GeozoneId=',H.CustomProp,0)+10,(CHARINDEX(';',H.CustomProp,0) - (CHARINDEX('GeozoneId=',H.CustomProp,0)+10))) AS INT)            
    inner join rvlfOrganizationGeozone G on G.GeozoneId=CAST(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'GeozoneId=',';') AS INT)            
    and v.OrganizationId=G.OrganizationId          
    inner join rvlfGeozoneSet GS on GS.GeozoneNo=G.GeozoneNo            
   where  OriginDateTime between             
   CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) AND    VA.VehicleId = @VehicleID and        
   CHARINDEX('GeozoneId=',H.CustomProp,0) <> 0 and H.BoxMsgInTypeId=5 --and G.OrganizationId=@bigOrganizationID
 END  
 ELSE                  
  BEGIN            
  SELECT 'Exceeds Threshold' as ResultValue                  
END                  
End                                


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng2_Optimzd_backup_20210531]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create procedure [dbo].[RVLT_SP_GetLatLng2_Optimzd_backup_20210531] 
(                  
 @vehicleId varchar(50)=null,                  
 @startdate as datetime =null,
 @enddate datetime =null,
 @interval as int=2000,                  
 @orderby varchar(10)='desc',                  
 @bigQueryingUser bigint = 292,                  
 @bitIsMDTMsg bit=0 ,                
 @bitIsMessage bit = 0,          
 @bigLastHours int = null                   
)
as
/******************************************************************************/                  
--2013-01-30 11:12:17.890              
-- Name  : RVLT_SP_GetLatLng2 27,'2016-12-25 08:00:00 AM','2016-06-25 08:00:00 PM',2000,'desc',14              
-- Name  : RVLT_SP_GetLatLng2_Optimzd 188,'2017-07-18 04:00:00 PM','2017-07-18 10:00:00 PM',2000,'desc',14              
-- Description : To get the messages that needs to be shown in the grid                  
-- Author  : T. Sathish Kumar                  
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
/******************************************************************************/      

Begin                  
	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     
               
                 
	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)  ,
			@Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings                
    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    
	inner join rvlfOrganization o on u.OrganizationId = o.OrganizationId                               
                      
	DECLARE @userIds table (userId bigint)                  
                   
	DECLARE @bigVehOrganizationID  bigint =@bigOrganizationID--(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)  	            
    -----------------------------------------------------------------------                
                --print @startDate  
                --print @endDate  
 DECLARE @intTotalRecords int                  
 SELECT @intTotalRecords = COUNT(H.MessageInID) 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                    
  --LEFT OUTER join rvlfTripDetails t ON h.MessageInID = t.StartMessageInID                  
  --LEFT OUTER JOIN rvlfTripDetails d ON h.MessageInID = d.EndMessageInID                  
    where H.ValidGps=0 and OriginDateTime between CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) and  VA.VehicleId = @VehicleID              
    and CT.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s                   
   WHERE s.ModuleId = 26 and s.UserGroupId =@intUserGroupId
   --(SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser)
   )                  
                    
    IF @intTotalRecords < @interval OR @interval = 30                  
  BEGIN     
  select '88'
     select *, 
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Controller_ID=',';'),'-') as Controller_ID,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Controller_Status=',';'),'-') as Controller_Status,	 
	-- isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'IDC=',';'),'-') as IDC,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Secodary_Current(mA)=',';'),'-') as IDC,
	 --isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'VDC=',';'),'-') 
	  isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Secondary_Voltage(KV)=',';'),'-') as VDC,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Actual_Spark_Rate(per_min)=',';'),'-') as SparkRate,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Operating_Charge_Ratio=',';'),'-') as OPChrgRatio,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Opacity_Input_Power=',';'),'-') as Opacity,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Corona_Power(kw)=',';'),'-') as Corona,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'VDC_Peak(kv)=',';'),'-') as VDCPeak,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'VDC_Through(kv)=',';'),'-') as VDCThrough,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'IAC_PRI=',';'),'-') as IAC,
	 --pricicon R
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'DCSIM=',';'),'-') as DCSIM,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Primary_Voltage(VAC)=',';'),
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Primary_Voltage_Limit(VAC)=',';'),'-')) as Primary_Voltage,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Primary_Current(AAC)=',';'),
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Primary_Current_Limit(AAC)=',';'),'-'))	 
	 as Primary_Current,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Primary_Power(kw)=',';'),'-') as Primary_Power,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Secondary_Voltage(KV)=',';'),
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Secondary_Voltage_Limit(KV)=',';'),'-')) as Secondary_Voltage,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Secondary_Voltage2=',';'),'-') as Secondary_Voltage2,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Secodary_Current(mA)=',';'),
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Secondary_Current_Limit(mA)=',';'),'-')) as Secondary_Current,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'SPM=',';'),'-') as Spark_Min,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'APM=',';'),'-') as Arc_Min,

	 --pricicon R setting
	-- isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Secondary_Voltage=',';'),'-') as Secondary_Voltage,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Under_Volt_Set_Point(VAC_or_KV)=',';'),'-') as Under_VoltSet_Point,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Ramp(sec)=',';'),'-') as Ramp,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'PhaseBack(%)=',';'),'-') as PhaseBack,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Pedestal(cycles)=',';'),'-') as Pedestal,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'QuenchTime(cycles)=',';'),'-') as QuenchTime,
	-- isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Actual_Spark_Rate(per_min)=',';'),'-') as Spark_Rate,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'IE_Charge_Half_Cycle=',';'),'-') as IE_ChargeHalfCycle,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'IE_Discharge_Cycle=',';'),'-') as IE_Dischargecycle,
	 isnull(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'IE_Background_Power(%)=',';'),'-') as IE_Background_Power,
	 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)+' '+ SubString(Convert(varchar,[TimeStamp],9),12,9) + SUBSTRING(Convert(varchar,[TimeStamp],9), 25, 2) + '~#~'
	   + CAST(Heading as varchar(3))+ '~#~'+ISNULL(cast(a.Distance as varchar(5)),'')+'~#~'+ cast(isNull(IgnitionStatus,0) as CHAR(1)) +        
       '~#~'+Landmark +'~#~'+ replace(MessageDetails,@NewLine,'') 
      +'~#~'+CAST(MessageInID AS varchar(40))+'~&~'', this.checked, this.id);'  as mapitFunction,                   
                 
      (case WHEN BoxMsgInTypeId = 114 and  customprop like '%ImgHeader:%' --and  CHARINDEX('ImgHeader:1', customprop) <> 0 
	  THEN                  
      
	  --(case when (dbo.rvlf_fn_GetCameraHex(BoxId,CAST(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Image ID:',';') as int),          
   --   CONVERT(varchar(35),@startdate,109),CONVERT(varchar(35),@enddate,109))) is null               
   --   then 'Null'              
   --   else               
     isnull( dbo.rvlf_fn_GetCameraHex(BoxId,CAST(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Image ID:',';') as int),CONVERT(varchar(35),@startdate,109), CONVERT(varchar(35),@enddate,109)) ,'Null')              
      --END)              
      else 'Null' end                 
    )as CamData       
	       
    ,(case WHEN BoxMsgInTypeId = 114 and customprop like 'ImgHeader:1%' --CHARINDEX('ImgHeader:1', customprop) <> 0 
	THEN                   
    (SELECT top 1 (case when count(ImageID) = TotalPackets then 0 else 1 end)  FROM rvlfCameraImages 
	where boxid = BoxId and imageid =CAST(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Image ID:',';') as int) 
	and Receiveddate between CONVERT(varchar(35),@startdate,109)  
	and CONVERT(varchar(35),@enddate,109) GROUP by ImageID,TotalPackets) else 0 end) as ImgStatus,    
	          
    (case WHEN BoxMsgInTypeId = 114 and  CustomProp like '%SendSMSQuery%' THEN 1 else 0 end) as SMSStatus,                    
    (case WHEN BoxMsgInTypeId in (100,114) and CustomProp like '%Finger%' THEN 1 else 0 end) as FingerPrintStatus,              
    (case WHEN BoxMsgInTypeId = 114 and customprop like '%PacketType:%' THEN                
      dbo.rvlf_fn_GetAlarmDetails_Optimzd(customprop,BoxMsgInTypeID, BoxId, MessageInID, DateTimeReceived,@Lang)               
    else null end) as ImagePacketType              
        from (                  
   select distinct(H.MessageInID),H.CustomProp,H.BoxId, VA.BoxID as DeviceID, 
   (CASE WHEN cast(ISNULL(H.Latitude,0) as decimal(14,6)) = 0 THEN 1 ELSE ValidGps END) AS ValidGPS, 
   cast(ISNULL(H.Latitude,0) as decimal(14,6)) as Latitude, cast(ISNULL(H.Longitude,0) as decimal(14,6)) as Longitude,   
   H.NearestLandMark as Distance,                   
                     
   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 '-'      
   WHEN H.BoxMsgInTypeId IN (2,3,12) 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_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime),                
--   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [Timestamp],                   
--   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,DateTimeReceived)) as DateTimeReceived,                  
   v.VehicleDescription,    OriginDateTime  ,         
   --BoxMsgInTypeDesc as Message,               
   case when H.BoxMsgInTypeId = 114 and H.customprop like '%SendSMSQuery:%'  Then 'Send SMS Query To Server'                     
   WHEN H.BoxMsgInTypeId = 114 and H.customprop like '%FingerPrintCommand:%' Then 'Finger Print'                             
   when H.BoxMsgInTypeId = 114 and H.customprop like '18;GPRS%' THEN 'Send Health Status'
   When H.BoxMsgInTypeId = 114 and H.customprop like '%IButtonCommand:1%'  Then 'Send iButton Param'  
   when H.BoxMsgInTypeId = 114 and CHARINDEX('35;InvalidFixDuration=',H.CustomProp,0) <> 0  THEN 'Invalid Fix'   
   else (CASE WHEN  @Lang='LanguageArNew' THEN ISNULL(BoxMsgInTypeDesc_Ar,BoxMsgInTypeDesc) WHEN  @Lang='LanguageHindi' THEN isnull(BoxMsgInTypeDesc_Hin,BoxMsgInTypeDesc)  else BoxMsgInTypeDesc  END) end as [Message],       
   H.BoxMsgInTypeId as BoxMsgInTypeId , 
    CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,OriginDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,OriginDateTime)), 14) AS RoadsAPITime,                 
   TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,OriginDateTime),                
   --Convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)),@DefaultDateFormat) + ' ' + Convert(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime))as Time),22)  as [TimestampDisp],     
   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [TimestampSort],   
                                 
     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 and CustomProp LIKE '%Interval=%' THEN 'Keep Alive Interval : '+ 
		  dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Interval=',';')+' Min'      	     
       WHEN H.BoxMsgInTypeId = 95 THEN Replace(REPLACE(H.CustomProp,'Default Dial Number=','Dial Number : '), 'Default Dial Number2=','Dial Number2 : ')           
           WHEN H.BoxMsgInTypeId = 114 and H.customprop like '%SendSMSQuery:%'  THEN                                            
		dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@lang )              
  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('38;FuelTankLength',H.CustomProp,0) <> 0  THEN 'Send Ultrasonic Fuel Sensing Parameters'    
  ELSE                  
     dbo.rvlf_fn_GetAlarmDetails_Optimzd(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 = '+ 
  dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SensorInfo1=',';') 
  ELSE '' END+ CASE WHEN H.customprop LIKE '%SensorInfo2%' THEN +' ; S2 = '+  dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SensorInfo2=',';') 
  ELSE '' END ELSE ''  END + 
  ISNULL(' (T: ' + dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Temperature: #','$') + ', ' +  
  'H: ' + dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Humidity: #','$') + ', ' +  
  'P: ' + dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Pressure: #','$') + ', ' +  
  'W: ' + dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Wind Speed: #','$') 
		+ dbo.rvlf_fn_GetParamValueWithIndex(WeatherInfo, 'Wind Direction: #','$') + ')', '') as MessageDetails,
  0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,                     
  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,                 
       @Distance as Units,                         
      CASE 
      WHEN H.ValidGps > 0 OR H.BoxMsgInTypeId IN (9,14,15,16,17,24) OR Speed = 0 then '-'                  
      WHEN H.BoxMsgInTypeId IN (96) then '-'                  
      WHEN H.Heading between 335 and 360 THEN 'N'                  
       WHEN H.Heading between 0 and 25 THEN 'N'                  
      WHEN H.Heading between 25 and 65 THEN 'NE'                  
      WHEN H.Heading between 65 and 115 THEN 'E'  
      WHEN H.Heading between 115 and 155 THEN 'SE'                  
      WHEN H.Heading between 155 and 210 THEN 'S'                  
      WHEN H.Heading between 210 and 245 THEN 'SW'                  
      WHEN H.Heading between 245 and 300 THEN 'W'                  
      WHEN H.Heading between 300 and 335 THEN 'NW' END as Direction ,                                               
      +'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,                  
      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(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Idling:',';') 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 (dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SENSOR_STATUS=',';')) = '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,L.LandmarkName as LandmarkName, L.Latitude as LandmarkLatitude,                   
        L.Longitude as LandmarkLongitude, L.Radius as LandmarkRadius,
          replace(L.StreetAddress,@NewLine,' ') As LandMarkAddress,              
          L.LandmarkID,'' as LandImage,     
          --isnull(LC.ImagePath,'') as LandImage,                
         CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,                
         CASE WHEN H.BoxMsgInTypeId IN(77,98,109,110,111) THEN 'Incoming'       
           ELSE NULL END AS MDTMsgType,          
           (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                  
,H.RoadSpeedLimit,v.vehicleid,
CASE WHEN CHARINDEX('Temperature Sensor-1 Value',CustomProp,1) > 0 AND CHARINDEX('Temperature Sensor-1 Value=Disconnected',CustomProp,1) = 0 THEN 1 ELSE 0 END AS IsTemp1,
CASE WHEN CHARINDEX('Temperature Sensor-2 Value',CustomProp,1) > 0 AND CHARINDEX('Temperature Sensor-2 Value=Disconnected',CustomProp,1) = 0 THEN 1 ELSE 0 END AS IsTemp2,
CASE WHEN CHARINDEX('Temperature Sensor-3 Value',CustomProp,1) > 0 AND CHARINDEX('Temperature Sensor-3 Value=Disconnected',CustomProp,1) = 0 THEN 1 ELSE 0 END AS IsTemp3,
CASE WHEN CHARINDEX('Temperature Sensor-4 Value',CustomProp,1) > 0 AND CHARINDEX('Temperature Sensor-4 Value=Disconnected',CustomProp,1) = 0THEN 1 ELSE 0 END AS IsTemp4,
CASE WHEN CHARINDEX('Temperature Sensor-1 Value',CustomProp,1) = 0 OR CHARINDEX('Temperature Sensor-1 Value=Disconnected',CustomProp,1) > 0 THEN NULL ELSE 
CAST(REPLACE(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Temperature Sensor-1 Value=',';'),' degree Celsius','') AS DECIMAL(6,2)) END AS T1,   
CASE WHEN CHARINDEX('Temperature Sensor-2 Value',CustomProp,1) = 0 OR CHARINDEX('Temperature Sensor-2 Value=Disconnected',CustomProp,1) > 0 THEN NULL ELSE 
CAST(REPLACE(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Temperature Sensor-2 Value=',';'),' degree Celsius','') AS DECIMAL(6,2)) END AS T2,
CASE WHEN CHARINDEX('Temperature Sensor-3 Value',CustomProp,1) = 0 OR CHARINDEX('Temperature Sensor-3 Value=Disconnected',CustomProp,1) > 0 THEN NULL ELSE 
CAST(REPLACE(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Temperature Sensor-3 Value=',';'),' degree Celsius','') AS DECIMAL(6,2)) END AS T3,
CASE WHEN CHARINDEX('Temperature Sensor-4 Value',CustomProp,1) = 0 OR CHARINDEX('Temperature Sensor-4 Value=Disconnected',CustomProp,1) > 0 THEN NULL ELSE 
CAST(REPLACE(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Temperature Sensor-4 Value=',';'),' degree Celsius','') AS DECIMAL(6,2)) END AS T4
   ,vt.VehicleTypeName as CustomerName,vt.VehicleTypeId,MD.ContactNo,            
      dbo.rvlf_fn_GetHHMMSSFromSec((select [dbo].[rvlf_fn_GetParamValue] (h.CustomProp,'Engine_Runtime'))) as UnitRun,
      0 as IsSnapshotRcvd,
	  MD.EquipmentSrNo
   from rvlfMsgInHst H                   
    INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                  
   -- INNER JOIN rvlfBoxId bx ON bx.BoxId=h.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 
    --LEFT OUTER JOIN rvlfLandmarkCategory LC ON L.LandmarkCategoryID = LC.LandmarkCategoryID                  
    INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
    inner join rvlfMAKDevices MD on MD.BoxId=H.BoxId   
	left join rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId
	              
   where  OriginDateTime between                  
   CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) and  VA.VehicleId = @VehicleID             
   and MD.IsDelete=0 and                   
   -- (H.BoxMsgInTypeId = 11 and L.OrganizationId = 51 OR 1 = (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser)) AND -- Hided Sensor Alarm for Suguna                  
   --H.BoxMsgInTypeId <>19 and--blocked the ipupdates for Gitex                  
   (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 H.BOXMSGINTYPEID NOT IN(102,103)         
    AND CommInfo1 IS NOT NULL                  
  AND (@bitIsMDTMsg=0 OR H.BoxMsgInTypeId IN(77,98,109,110,111)) and h.CustomProp not like '%18;GPRS%'                   
   UNION ALL                  
   /***************** Changed the Speed as NULL by Jaya Chitra on 25-Aug-2009******************/                  
    select  NULL as MessageInID,null as Customprop,              
    null as BoxId,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,NULL as Speed, 0 as Heading,                  
    [Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),                
   SentDateTime = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),                
    --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [Timestamp],                  
    --DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as SentDateTime,                   
    V.VehicleDescription,'' as origindatetime,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId ,
	CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 14) AS RoadsAPITime,                      
     TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime),                
   -- convert(varchar,DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)),@DefaultDateFormat) + ' ' + CONVERT(varchar,cast(DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime))as time),22) as [TimestampDisp], 

    DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [TimestampSort],                  
    CASE WHEN OH.BoxCmdOutTypeId = 39 OR OH.BoxCmdOutTypeId = 4 THEN dbo.rvlf_fn_GetCmdMsgDetails(OH.CustomProp + ',', OH.BoxCmdOutTypeId, VA.BoxID)                   
         ELSE BoxcmdTypeDesc END as MessageDetails                  
    ,OH.UserId,Priority,                  
    /**************** Changed the Acknowledgement to be return based on the value ************/                  
    CASE WHEN Acknowledged = 1 THEN 'True'      
      WHEN Acknowledged = 0 THEN 'False'                   
      WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Update Failed'                  
      WHEN  Acknowledged = 4 THEN 'CRC Incorrect'                  
      WHEN  Acknowledged = 5 THEN 'No Communication'                  
      WHEN  Acknowledged = 6 THEN 'Aborted'                  
      WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'                  
      ELSE 'Nothing' END AS Acknowledged,                  
    CASE WHEN Acknowledged = 1 THEN 'Acknowledged'                   
      WHEN Acknowledged = 0 THEN 'Not Acknowledged'                   
      WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Upgrade Failed'                  
      WHEN  Acknowledged = 4 THEN 'CRC Incorrect'                  
      WHEN  Acknowledged = 5 THEN 'No Communication'                  
      WHEN  Acknowledged = 6 THEN 'Aborted'                  
      WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'      
      ELSE '' END AS AckStatus,                  
    'N/A' as Address,@Distance as Units,'' as Direction ,/*null as mapitFunction,*/'setValue('' '')' as jsFunction,                  
    NULL as IgnitionStatus, NULL as StreetAddress, NULL as Landmark,NULL as LandmarkName,                   
    NULL as LandmarkLatitude, NULL as LandmarkLongitude, NULL as LandmarkRadius,                  
    NULL As LandMarkAddress, NULL as LandmarkID,Null as LandImage,NULL as IsDefaultAlarm,                  
    CASE WHEN oH.BoxCmdOutTypeId IN(39,44,45,46,47) THEN 'Outgoing'                  
           ELSE NULL END AS MDTMsgType, null as isMapIT ,0 as Roadspeedlimit ,va.vehicleid,
		   NULL AS IsTemp1,NULL AS IsTemp2,NULL AS IsTemp3,NULL AS IsTemp4,NULL AS T1,NULL AS T2,NULL AS T3,NULL AS T4 ,
		  vt.VehicleTypeName as CustomerName, vt.VehicleTypeId,MD.ContactNo,            
      null,null,
	  MD.EquipmentSrNo                
    from rvlfMsgOutHst OH                  
    INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID                  
    INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId  
	  inner join rvlfMAKDevices MD on MD.BoxId=oH.BoxId   
	left join rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId                
    WHERE  SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)                  
     AND VA.VehicleID = @VehicleID  and --OH.BoxCmdOutTypeId <> 22                       
     CT.OperationTypeId IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s                   
     WHERE s.ModuleId = 22 and s.UserGroupId IN                   
     (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))                   
     AND (@bitIsMDTMsg=0 OR OH.BoxCmdOutTypeId IN(39,44,45,46,47))) as a order by Timestamp desc, MessageInID desc                  
                     
   -- --------------Get the Latest value for Device ------------------------------------------------------------------                 
   select B.BoxId,LastLatitude,LastLongitude,                  
    CASE WHEN H.BoxMsgInTypeId =51 OR H.BoxMsgInTypeId =90  THEN ''
     WHEN ISNULL(H.Speed,0) = 0 THEN '-'   ELSE CAST(CAST(LastSpeed  * @ConversionFactor as int) as varchar(10)) END as LastSpeed,                  
    CASE WHEN LastSpeed = 0 OR LastCommunicatedDateTime<> LastStatusDateTime                   
    THEN -1 ELSE B.Heading END as Heading,                  
    Replace(ISNULL( LastStreetAddress, 'Address is not resolved'),'''','\''')  as LastStreetAddress,                  
    DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,LastValidDateTime)) as LastStatusDateTime,                  
    B.NearestLandmark, V.VehicleId,V.VehicleDescription,                  
    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(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Idling:',';') 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 (dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SENSOR_STATUS=',';')) = 'ON'                         
         THEN 1 ELSE 0 End End                  
      ELSE 2 END as IgnitionStatus,                  
    @Distance as Units,                  
   -- CASE WHEN H.BoxMsgInTypeId = 51 THEN                
   --    (case when @Lang='LanguageArNew' THEN N'*.1B 'D319) DD ' when @Lang='LanguageHindi' THEN N'8	M	*	@	!	 	G	 2	?		 		2	M	2			(	'  ELSE 'Speed Violated for ' END)                   
   --   --+CAST(CAST(Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @Distance                   
   --+'(' + dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'                  
   -- ELSE                   
     dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)--CT.BoxMsgInTypeDesc                   
    --END
	+ 
  ISNULL(' (T: ' + dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Temperature: #','$') + ', ' +  
  'H: ' + dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Humidity: #','$') + ', ' +  
  'P: ' + dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Pressure: #','$') + ', ' +  
  'W: ' + dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Wind Speed: #','$') 
		+ dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Wind Direction: #','$') + ')', '') as MessageDetails,                   
    ISNULL(CASE WHEN (L.LandMarkID IS NULL OR H.LandMarkID = 0) THEN '-' ELSE isnull(L.LandmarkName,'-') END,'-') AS Landmark,                  
    L.LandmarkName as LandmarkName, L.Latitude as LandmarkLatitude, L.Longitude as LandmarkLongitude, L.Radius as LandmarkRadius,               
    replace(L.StreetAddress,@NewLine,' ') As LandMarkAddress ,H.RoadSpeedLimit              
    from rvlfBoxId B INNER JOIN rvlfVehicleAssignment VA on B.BoxId = VA.BoxId                  
    INNER JOIN rvlfMsgInHst H ON  H.BoxId=VA.BoxId AND H.OriginDateTime=B.LastValidDateTime AND H.Latitude=B.LastLatitude AND H.Longitude=B.LastLongitude                   
    INNER JOIN rvlfVehicle V on V.VehicleId = VA.VehicleId                  
    --LEFT OUTER join rvlfTripDetails t ON h.MessageInID = t.StartMessageInID                  
    --LEFT OUTER JOIN rvlfTripDetails d ON h.MessageInID = d.EndMessageInID                  
    INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                  
    LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID                      
    where VA.VehicleId = @vehicleId                    
    --AND H.BOXMSGINTYPEID NOT IN(102,103)                  
    --AND (DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,LastStatusDateTime))                  
    --BETWEEN CONVERT(DateTime,@startdate,109) and CONVERT(DateTime,@enddate,109))          
         
 --Get Geozone details            
 Select distinct dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'GeozoneId=',';') as GeozoneNo    
 ,G.GeozoneName,G.GeozoneType,latlng = STUFF((SELECT '~' + cast(Latitude as varchar)+'#' + cast(Longitude as varchar)            
	FROM rvlfGeozoneSet b WHERE b.GeozoneNo = GS.GeozoneNo FOR XML PATH('')), 1, 1, ''),@bigOrganizationID,G.OrganizationId,
	(SELECT IsRestricted FROM rvlfGeozoneRestricted WHERE VehicleId=@VehicleID AND GeozoneNo=G.GeozoneNo) AS IsRestricted,
	ISNULL(G.Radius,0) AS CircleRadius, G.OrganizationId 
       --H.CustomProp          
 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                                             
    INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID              
    --inner join rvlfOrganizationGeozone G on G.GeozoneId=CAST(SUBSTRING(H.CustomProp,CHARINDEX('GeozoneId=',H.CustomProp,0)+10,(CHARINDEX(';',H.CustomProp,0) - (CHARINDEX('GeozoneId=',H.CustomProp,0)+10))) AS INT)            
    inner join rvlfOrganizationGeozone G on G.GeozoneId=CAST(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'GeozoneId=',';') AS INT)            
    and v.OrganizationId=G.OrganizationId          
    inner join rvlfGeozoneSet GS on GS.GeozoneNo=G.GeozoneNo            
   where  OriginDateTime between             
   CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) AND    VA.VehicleId = @VehicleID and        
   CHARINDEX('GeozoneId=',H.CustomProp,0) <> 0 and H.BoxMsgInTypeId=5 --and G.OrganizationId=@bigOrganizationID
 END  
 ELSE                  
  BEGIN            
  SELECT 'Exceeds Threshold' as ResultValue                  
END                  
End                                


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng2_Optimzd_backupwithscaling]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create procedure [dbo].[RVLT_SP_GetLatLng2_Optimzd_backupwithscaling]    
(                  
 @vehicleId varchar(50)=null,                  
 @startdate as datetime =null,
 @enddate datetime =null,
 @interval as int=2000,                  
 @orderby varchar(10)='desc',                  
 @bigQueryingUser bigint = NULL,                  
 @bitIsMDTMsg bit=0 ,                
 @bitIsMessage bit = 0,          
 @bigLastHours int = null                   
)
as
/******************************************************************************/                  
--2013-01-30 11:12:17.890              
-- Name  : RVLT_SP_GetLatLng2 27,'2016-12-25 08:00:00 AM','2016-06-25 08:00:00 PM',2000,'desc',14              
-- Name  : RVLT_SP_GetLatLng2_Optimzd 188,'2017-07-18 04:00:00 PM','2017-07-18 10:00:00 PM',2000,'desc',14              
-- Description : To get the messages that needs to be shown in the grid                  
-- Author  : T. Sathish Kumar                  
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
/******************************************************************************/      

Begin                  
	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     
               
                 
	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)  ,
			@Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings                
    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    
	inner join rvlfOrganization o on u.OrganizationId = o.OrganizationId                               
                      
	DECLARE @userIds table (userId bigint)                  
                   
	DECLARE @bigVehOrganizationID  bigint =@bigOrganizationID--(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)  	            
    -----------------------------------------------------------------------                
                --print @startDate  
                --print @endDate  
 DECLARE @intTotalRecords int                  
 SELECT @intTotalRecords = COUNT(H.MessageInID) from rvlfMsgInHst H                   
  INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                  
  INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                                   
    where H.ValidGps=0 and OriginDateTime between CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) and  VA.VehicleId = @VehicleID              
    and CT.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s                   
   WHERE s.ModuleId = 26 and s.UserGroupId =@intUserGroupId
   )                  

declare @DeviceTypeID int=0
select @DeviceTypeID=VehicleTypeId from rvlfVehicle where VehicleId=@vehicleId
     
    IF @intTotalRecords < @interval OR @interval = 30                  
  BEGIN     
	if(@DeviceTypeID=1)
		begin
			 select *,ROW_NUMBER() over (order by timestamp) as AutoID            
				from (                  
		   select distinct(H.MessageInID),H.BoxId,VA.BoxID as DeviceID,H.BoxMsgInTypeId,H.CommInfo1,H.CommInfo2,H.CustomProp,H.StreetAddress,H.SequenceNum,H.IsArmed,H.IsProcessed,H.IsArchived,H.ControllerID,H.Alarm,H.Batt_Volt,
		   (isnull(H.Batt_Current,0)*0.1) as Batt_Current,H.Batt_LstRreplacement,
		   (isnull(H.Chrg_Alternator,0)*0.1) as Chrg_Alternator,
		   H.Coolant_Temp,H.EngineSpeed,
		   (RIGHT('0' + CAST(isnull(H.Engine_RunTime,0) / 3600 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST((isnull(H.Engine_RunTime,0) / 60) % 60 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST(isnull(H.Engine_RunTime,0) % 60 AS VARCHAR),2)) as Engine_RunTime
		   ,H.FuelLevel,H.Tot_Watts,H.Tot_VA,H.Tot_VAr,H.Gen_KWh,H.Gen_KVAh,H.Gen_KVArh,
		   (isnull(H.Gen_Freq,0)*0.1) as Gen_Freq,
		   (isnull(H.Gen_AvgPF,0)*0.01) as Gen_AvgPF,
		   H.Gen_L1_PF,H.Gen_L1_VAr,H.Gen_L1_VA,H.Gen_L1_Watts,H.Gen_L1_Current,H.Gen_L2_PF,H.Gen_L2_VAr,H.Gen_L2_VA,H.Gen_L2_Watts,H.Gen_L2_Current,H.Gen_L3_PF,H.Gen_L3_VAr,H.Gen_L3_VA,H.Gen_L3_Watts,H.Gen_L3_Current,H.Gen_LNVolt,H.Gen_LLVolt,H.NumofStarts,H.Oil_Temp,H.Oil_Pressure,H.GateWayID,H.ComMode, MD.EquipmentSrNo,
			[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime),                
			DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime), 
			TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,OriginDateTime),
		   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [TimestampSort],v.vehicleid,vt.VehicleTypeName as CustomerName,vt.VehicleTypeId,MD.ContactNo,0 as isMapIT,CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,H.StreetAddress as Address, @Distance as Units, 
		   'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,(CASE WHEN cast(ISNULL(H.Latitude,0) as decimal(14,6)) = 0 THEN 1 ELSE ValidGps END) AS ValidGPS, 
		   cast(ISNULL(H.Latitude,0) as decimal(14,6)) as Latitude, cast(ISNULL(H.Longitude,0) as decimal(14,6)) as Longitude, 0  as Speed, CASE WHEN H.Speed = 0 OR H.ValidGps > 0 THEN -1 ELSE CAST(Heading as varchar(3))  END as Heading, v.VehicleDescription, OriginDateTime, BoxMsgInTypeDesc as [Message],'' as MessageDetails,0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,NULL as S1_Tot_Watts,NULL as S1_Tot_VA,NULL as S1_Tot_VAr,NULL as S1_KWh,NULL as S1_KVAh,NULL as S1_KVArh,NULL as S1_Freq,NULL as S1_AvgPF,NULL as S1_L1_PF,NULL as S1_L1_VAr,NULL as S1_L1_VA,NULL as S1_L1_Watts,NULL as S1_L1_Current,NULL as S1_L2_PF,NULL as S1_L2_VAr,NULL as S1_L2_VA,NULL as S1_L2_Watts,NULL as S1_L2_Current,NULL as S1_L3_PF,NULL as S1_L3_VAr,NULL as S1_L3_VA,NULL as S1_L3_Watts,NULL as S1_L3_Current,NULL as S2_Tot_Watts,NULL as S2_Tot_VA,NULL as S2_Tot_VAr,NULL as S2_KWh,NULL as S2_KVAh,NULL as S2_KVArh,NULL as S2_Freq,NULL as S2_AvgPF,NULL as S2_L1_PF,NULL as S2_L1_VAr,NULL as S2_L1_VA,NULL as S2_L1_Watts,NULL as S2_L1_Current,NULL as S2_L2_PF,NULL as S2_L2_VAr,NULL as S2_L2_VA,NULL as S2_L2_Watts,NULL as S2_L2_Current,NULL as S2_L3_PF,NULL as S2_L3_VAr,NULL as S2_L3_VA,NULL as S2_L3_Watts,NULL as S2_L3_Current,NULL as Main_Gen_LNVolt, 
		   (isnull(H.GEN_L1_N_VOLT,0) * 0.1) as GEN_L1_N_VOLT,
		   (isnull(H.GEN_L2_N_VOLT,0) * 0.1) as GEN_L2_N_VOLT,
		   (isnull(H.GEN_L3_N_VOLT,0) * 0.1) as GEN_L3_N_VOLT,
		   (isnull(H.GEN_L1_L2_VOLT,0) * 0.1) as GEN_L1_L2_VOLT,
		   (isnull(H.GEN_L2_L3_VOLT,0) * 0.1) as GEN_L2_L3_VOLT,
		   (isnull(H.GEN_L1_L3_VOLT,0) * 0.1) as GEN_L1_L3_VOLT,
		   NULL As S1_L1_N_Voltage,NULL As S1_L2_N_Voltage,NULL As S1_L3_N_Voltage,NULL As S1_L1_L2_Voltage,NULL As S1_L2_L3_Voltage,NULL As S1_L3_L1_Voltage,NULL As S2_L1_N_Voltage,NULL As S2_L2_N_Voltage,NULL As S2_L3_N_Voltage,NULL As S2_L1_L2_Voltage,NULL As S2_L2_L3_Voltage,NULL As S2_L3_L1_Voltage
		   from rvlfMsgInHst_Techno H                   
			INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                  
			INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                  
			INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
			inner join rvlfMAKDevices MD on MD.BoxId=H.BoxId   
			left join rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId
	              
		   where  OriginDateTime between                  
		   CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) and  VA.VehicleId = @VehicleID             
		   and MD.IsDelete=0 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 H.BOXMSGINTYPEID NOT IN(102,103)         
			AND CommInfo1 IS NOT NULL                  
		  AND (@bitIsMDTMsg=0 OR H.BoxMsgInTypeId IN(77,98,109,110,111)) and h.CustomProp not like '%18;GPRS%') as a order by Timestamp desc, MessageInID desc                  
       end
	 else if(@DeviceTypeID=2)
		begin
			 select *,ROW_NUMBER() over (order by timestamp) as AutoID            
				from (                  
		   select distinct(H.MessageInID),H.BoxId,VA.BoxID as DeviceID,H.BoxMsgInTypeId,H.CommInfo1,H.CommInfo2,H.CustomProp,H.StreetAddress,H.SequenceNum,H.IsArmed,H.IsProcessed,H.IsArchived,H.ControllerID,H.Alarm,NULL as Batt_Volt,'' as Batt_Current,'' as Batt_LstRreplacement,'' as Chrg_Alternator,NULL as Coolant_Temp,NULL as EngineSpeed,NULL as Engine_RunTime,NULL as FuelLevel,NULL as Tot_Watts,NULL as Tot_VA,NULL as Tot_VAr,NULL as Gen_KWh,NULL as Gen_KVAh,NULL as Gen_KVArh,NULL as Gen_Freq,NULL as Gen_AvgPF,NULL as Gen_L1_PF,NULL as Gen_L1_VAr,NULL as Gen_L1_VA,NULL as Gen_L1_Watts,NULL as Gen_L1_Current,NULL as Gen_L2_PF,NULL as Gen_L2_VAr,NULL as Gen_L2_VA,NULL as Gen_L2_Watts,NULL as Gen_L2_Current,NULL as Gen_L3_PF,NULL as Gen_L3_VAr,NULL as Gen_L3_VA,NULL as Gen_L3_Watts,NULL as Gen_L3_Current,NULL as Gen_LNVolt,NULL as Gen_LLVolt,NULL as NumofStarts,NULL as Oil_Temp,NULL as Oil_Pressure,H.GateWayID,H.ComMode, MD.EquipmentSrNo,
			[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime),                
			DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime), 
			TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,OriginDateTime),
		   DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [TimestampSort],v.vehicleid,vt.VehicleTypeName as CustomerName,vt.VehicleTypeId,MD.ContactNo,0 as isMapIT,CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,H.StreetAddress as Address, @Distance as Units, 
		   'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,(CASE WHEN cast(ISNULL(H.Latitude,0) as decimal(14,6)) = 0 THEN 1 ELSE ValidGps END) AS ValidGPS, 
		   cast(ISNULL(H.Latitude,0) as decimal(14,6)) as Latitude, cast(ISNULL(H.Longitude,0) as decimal(14,6)) as Longitude, 0  as Speed, CASE WHEN H.Speed = 0 OR H.ValidGps > 0 THEN -1 ELSE CAST(Heading as varchar(3))  END as Heading, v.VehicleDescription, OriginDateTime, BoxMsgInTypeDesc as [Message],'' as MessageDetails,0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,H.S1_Tot_Watts,H.S1_Tot_VA,H.S1_Tot_VAr,H.S1_KWh,H.S1_KVAh,H.S1_KVArh,H.S1_Freq,H.S1_AvgPF,H.S1_L1_PF,H.S1_L1_VAr,H.S1_L1_VA,
		   (isnull(H.S1_L1_Watts,0) *0.1) as S1_L1_Watts,
		   (isnull(H.S1_L1_Current,0) * 0.1) as S1_L1_Current,
		   H.S1_L2_PF,H.S1_L2_VAr,H.S1_L2_VA,
		   (isnull(H.S1_L2_Watts,0) *0.1) as S1_L2_Watts,
		   (isnull(H.S1_L2_Current,0) * 0.1) as S1_L2_Current,
		   H.S1_L3_PF,H.S1_L3_VAr,H.S1_L3_VA,
		   (isnull(H.S1_L3_Watts,0) *0.1) as S1_L3_Watts,
		   (isnull(H.S1_L3_Current,0) * 0.1) as S1_L3_Current,
		   H.S2_Tot_Watts,
		   H.S2_Tot_VA,H.S2_Tot_VAr,H.S2_KWh,H.S2_KVAh,H.S2_KVArh,H.S2_Freq,H.S2_AvgPF,H.S2_L1_PF,H.S2_L1_VAr,H.S2_L1_VA,
		   (isnull(H.S2_L1_Watts,0) * 0.1) as S2_L1_Watts,
		   (isnull(H.S2_L1_Current,0) * 0.1) as S2_L1_Current,
		   H.S2_L2_PF,H.S2_L2_VAr,H.S2_L2_VA,
		   (isnull(H.S2_L2_Watts,0) * 0.1) as S2_L2_Watts,
		   (isnull(H.S2_L2_Current,0) * 0.1) as S2_L2_Current,
		   H.S2_L3_PF,H.S2_L3_VAr,H.S2_L3_VA,
		   (isnull(H.S2_L3_Watts,0) * 0.1) as S2_L3_Watts,
		   (isnull(H.S2_L3_Current,0) * 0.1) as S2_L3_Current,
		   H.Main_Gen_LNVolt,
		   (isnull(H.S1_L1_N_Voltage,0) * 0.1) as S1_L1_N_Voltage,
		   (isnull(H.S1_L2_N_Voltage,0) * 0.1) as S1_L2_N_Voltage,
		   (isnull(H.S1_L3_N_Voltage,0) * 0.1) as S1_L3_N_Voltage,
		   (isnull(H.S1_L1_L2_Voltage,0) * 0.1) as S1_L1_L2_Voltage,
		   (isnull(H.S1_L2_L3_Voltage,0) * 0.1) as S1_L2_L3_Voltage,
		   (isnull(H.S1_L3_L1_Voltage,0) * 0.1) as S1_L3_L1_Voltage,
		   (isnull(H.S2_L1_N_Voltage,0) * 0.1) as S2_L1_N_Voltage,
		   (isnull(H.S2_L2_N_Voltage,0) * 0.1) as S2_L2_N_Voltage,
		   (isnull(H.S2_L3_N_Voltage,0) * 0.1) as S2_L3_N_Voltage,
		   (isnull(H.S2_L1_L2_Voltage,0) * 0.1) as S2_L1_L2_Voltage,
		   (isnull(H.S2_L2_L3_Voltage,0) * 0.1) as S2_L2_L3_Voltage,
		   (isnull(H.S2_L3_L1_Voltage,0) * 0.1) as S2_L3_L1_Voltage
		   ,NULL as GEN_L1_N_VOLT,NULL as GEN_L2_N_VOLT,NULL as GEN_L3_N_VOLT,NULL as GEN_L1_L2_VOLT,NULL as GEN_L2_L3_VOLT,NULL as GEN_L1_L3_VOLT from rvlfMsgInHst_Techno_355 H                   
			INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                  
			INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                  
			INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
			inner join rvlfMAKDevices MD on MD.BoxId=H.BoxId   
			left join rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId
	              
		   where  OriginDateTime between                  
		   CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) and  VA.VehicleId = @VehicleID             
		   and MD.IsDelete=0 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 H.BOXMSGINTYPEID NOT IN(102,103)         
			AND CommInfo1 IS NOT NULL                  
		  AND (@bitIsMDTMsg=0 OR H.BoxMsgInTypeId IN(77,98,109,110,111)) and h.CustomProp not like '%18;GPRS%') as a order by Timestamp desc, MessageInID desc  
		end
		
   -- --------------Get the Latest value for Device ------------------------------------------------------------------                 
   select B.BoxId,LastLatitude,LastLongitude,                  
    CASE WHEN H.BoxMsgInTypeId =51 OR H.BoxMsgInTypeId =90  THEN ''
     WHEN ISNULL(H.Speed,0) = 0 THEN '-'   ELSE CAST(CAST(LastSpeed  * @ConversionFactor as int) as varchar(10)) END as LastSpeed,                  
    CASE WHEN LastSpeed = 0 OR LastCommunicatedDateTime<> LastStatusDateTime                   
    THEN -1 ELSE B.Heading END as Heading,                  
    Replace(ISNULL( LastStreetAddress, 'Address is not resolved'),'''','\''')  as LastStreetAddress,                  
    DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,LastValidDateTime)) as LastStatusDateTime,                  
    B.NearestLandmark, V.VehicleId,V.VehicleDescription,                  
    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(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Idling:',';') 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 (dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SENSOR_STATUS=',';')) = 'ON'                         
         THEN 1 ELSE 0 End End                  
      ELSE 2 END as IgnitionStatus,                  
    @Distance as Units,                  
   -- CASE WHEN H.BoxMsgInTypeId = 51 THEN                
   --    (case when @Lang='LanguageArNew' THEN N'*.1B 'D319) DD ' when @Lang='LanguageHindi' THEN N'8	M	*	@	!	 	G	 2	?		 		2	M	2			(	'  ELSE 'Speed Violated for ' END)                   
   --   --+CAST(CAST(Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @Distance                   
   --+'(' + dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'                  
   -- ELSE                   
     dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)--CT.BoxMsgInTypeDesc                   
    --END
	+ 
  ISNULL(' (T: ' + dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Temperature: #','$') + ', ' +  
  'H: ' + dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Humidity: #','$') + ', ' +  
  'P: ' + dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Pressure: #','$') + ', ' +  
  'W: ' + dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Wind Speed: #','$') 
		+ dbo.rvlf_fn_GetParamValueWithIndex(H.WeatherInfo, 'Wind Direction: #','$') + ')', '') as MessageDetails,                   
    ISNULL(CASE WHEN (L.LandMarkID IS NULL OR H.LandMarkID = 0) THEN '-' ELSE isnull(L.LandmarkName,'-') END,'-') AS Landmark,                  
    L.LandmarkName as LandmarkName, L.Latitude as LandmarkLatitude, L.Longitude as LandmarkLongitude, L.Radius as LandmarkRadius,               
    replace(L.StreetAddress,@NewLine,' ') As LandMarkAddress ,H.RoadSpeedLimit              
    from rvlfBoxId B INNER JOIN rvlfVehicleAssignment VA on B.BoxId = VA.BoxId                  
    INNER JOIN rvlfMsgInHst H ON  H.BoxId=VA.BoxId AND H.OriginDateTime=B.LastValidDateTime AND H.Latitude=B.LastLatitude AND H.Longitude=B.LastLongitude                   
    INNER JOIN rvlfVehicle V on V.VehicleId = VA.VehicleId                  
    --LEFT OUTER join rvlfTripDetails t ON h.MessageInID = t.StartMessageInID                  
    --LEFT OUTER JOIN rvlfTripDetails d ON h.MessageInID = d.EndMessageInID                  
    INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                  
    LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID                      
    where VA.VehicleId = @vehicleId                    
    --AND H.BOXMSGINTYPEID NOT IN(102,103)                  
    --AND (DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,LastStatusDateTime))                  
    --BETWEEN CONVERT(DateTime,@startdate,109) and CONVERT(DateTime,@enddate,109))          
         
 --Get Geozone details            
 Select distinct dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'GeozoneId=',';') as GeozoneNo    
 ,G.GeozoneName,G.GeozoneType,latlng = STUFF((SELECT '~' + cast(Latitude as varchar)+'#' + cast(Longitude as varchar)            
	FROM rvlfGeozoneSet b WHERE b.GeozoneNo = GS.GeozoneNo FOR XML PATH('')), 1, 1, ''),@bigOrganizationID,G.OrganizationId,
	(SELECT IsRestricted FROM rvlfGeozoneRestricted WHERE VehicleId=@VehicleID AND GeozoneNo=G.GeozoneNo) AS IsRestricted,
	ISNULL(G.Radius,0) AS CircleRadius, G.OrganizationId 
       --H.CustomProp          
 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                                             
    INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID              
    --inner join rvlfOrganizationGeozone G on G.GeozoneId=CAST(SUBSTRING(H.CustomProp,CHARINDEX('GeozoneId=',H.CustomProp,0)+10,(CHARINDEX(';',H.CustomProp,0) - (CHARINDEX('GeozoneId=',H.CustomProp,0)+10))) AS INT)            
    inner join rvlfOrganizationGeozone G on G.GeozoneId=CAST(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'GeozoneId=',';') AS INT)            
    and v.OrganizationId=G.OrganizationId          
    inner join rvlfGeozoneSet GS on GS.GeozoneNo=G.GeozoneNo            
   where  OriginDateTime between             
   CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109) AND    VA.VehicleId = @VehicleID and        
   CHARINDEX('GeozoneId=',H.CustomProp,0) <> 0 and H.BoxMsgInTypeId=5 --and G.OrganizationId=@bigOrganizationID
 END  
 ELSE                  
  BEGIN            
  SELECT 'Exceeds Threshold' as ResultValue                  
END                  
End                                


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng2_Optimzd_TechnoMobile]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RVLT_SP_GetLatLng2_Optimzd_TechnoMobile]
(
	@deviceID varchar(50)=null,
	@bigQueryingUser bigint = NULL
)
as
/******************************************************************************/
--2013-01-30 11:12:17.890
-- Name : RVLT_SP_GetLatLng2 27,'2016-12-25 08:00:00 AM','2016-06-25 08:00:00 PM',2000,'desc',14
-- Name : RVLT_SP_GetLatLng2_Optimzd 188,'2017-07-18 04:00:00 PM','2017-07-18 10:00:00 PM',2000,'desc',14
-- Description : To get the messages that needs to be shown in the grid
-- Author : T. Sathish Kumar
-- Company : Angler Technologies
-- History : <<Date(dd-MON-yyyy)>> Initial Reason
/******************************************************************************/
	Begin
		declare @Lang varchar(50), @LangSetting varchar(20)
		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) ,
		@Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings
		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
		inner join rvlfOrganization o on u.OrganizationId = o.OrganizationId

		DECLARE @userIds table (userId bigint)
		DECLARE @bigVehOrganizationID bigint =@bigOrganizationID--(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
		
		declare @startDate datetime=getdate()
		SET @startDate=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@startDate))

		declare @DeviceTypeID int=0
		select @DeviceTypeID=VehicleTypeId from rvlfVehicle where VehicleId=@deviceID

		if(@DeviceTypeID=1)
			begin
				select *,ROW_NUMBER() over (order by timestamp) as AutoID
				from (
				select top 1 H.MessageInID,H.BoxId,VA.BoxID as DeviceID,H.BoxMsgInTypeId,H.CommInfo1,H.CommInfo2,H.CustomProp,H.StreetAddress,H.SequenceNum,H.IsArmed,H.IsProcessed,H.IsArchived,H.ControllerID,H.Alarm,isnull(H.Batt_Volt,'0') as Batt_Volt,isnull(H.Batt_Current,'0') as Batt_Current,isnull(H.Batt_LstRreplacement,'0') as Batt_LstRreplacement,isnull(H.Chrg_Alternator,'0') as Chrg_Alternator,isnull(H.Coolant_Temp,'0') as Coolant_Temp,isnull(H.EngineSpeed,'0') as EngineSpeed,isnull(H.Engine_RunTime,'') as Engine_RunTime,isnull(H.FuelLevel,'0') as FuelLevel,isnull(H.Tot_Watts,'0') as Tot_Watts,isnull(H.Tot_VA,'0') as Tot_VA,isnull(H.Tot_VAr,'0') as Tot_VAr,isnull(H.Gen_KWh,'0') as Gen_KWh,isnull(H.Gen_KVAh,'0') as Gen_KVAh,isnull(H.Gen_KVArh,'0') as Gen_KVArh,isnull(H.Gen_Freq,'0') as Gen_Freq,isnull(H.Gen_AvgPF,'0') as Gen_AvgPF,isnull(H.Gen_L1_PF,'0') as Gen_L1_PF
				,isnull(H.Gen_L1_VAr ,'0') as Gen_L1_VAr
,isnull(H.Gen_L1_VA ,'0') as Gen_L1_VA
,isnull(H.Gen_L1_Watts ,'0') as Gen_L1_Watts
,isnull(H.Gen_L1_Current ,'0') as Gen_L1_Current
,isnull(H.Gen_L2_PF ,'0') as Gen_L2_PF
,isnull(H.Gen_L2_VAr ,'0') as Gen_L2_VAr
,isnull(H.Gen_L2_VA ,'0') as Gen_L2_VA
,isnull(H.Gen_L2_Watts ,'0') as Gen_L2_Watts
,isnull(H.Gen_L2_Current ,'0') as Gen_L2_Current
,isnull(H.Gen_L3_PF ,'0') as Gen_L3_PF
,isnull(H.Gen_L3_VAr ,'0') as Gen_L3_VAr
,isnull(H.Gen_L3_VA ,'0') as Gen_L3_VA
,isnull(H.Gen_L3_Watts ,'0') as Gen_L3_Watts
,isnull(H.Gen_L3_Current ,'0') as Gen_L3_Current
,isnull(H.Gen_LNVolt ,'0') as Gen_LNVolt
,isnull(H.Gen_LLVolt ,'0') as Gen_LLVolt
,isnull(H.NumofStarts ,'0') as NumofStarts
,isnull(H.Oil_Temp ,'0') as Oil_Temp
,isnull(H.Oil_Pressure ,'0') as Oil_Pressure
,isnull(H.GateWayID ,'0') as GateWayID
,isnull(H.ComMode ,'0') as ComMode
,isnull(MD.EquipmentSrNo, '0') as EquipmentSrNo,
				[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime),
				DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime),
				TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,OriginDateTime),
				DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [TimestampSort],v.vehicleid,vt.VehicleTypeName as CustomerName,vt.VehicleTypeId,MD.ContactNo,0 as isMapIT,CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,H.StreetAddress as Address, @Distance as Units,
				'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,(CASE WHEN cast(ISNULL(H.Latitude,0) as decimal(14,6)) = 0 THEN 1 ELSE ValidGps END) AS ValidGPS,
				cast(ISNULL(H.Latitude,0) as decimal(14,6)) as Latitude, cast(ISNULL(H.Longitude,0) as decimal(14,6)) as Longitude, 0 as Speed, CASE WHEN H.Speed = 0 OR H.ValidGps > 0 THEN -1 ELSE CAST(Heading as varchar(3)) END as Heading, v.VehicleDescription, OriginDateTime, BoxMsgInTypeDesc as [Message],'' as MessageDetails,0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,NULL as S1_Tot_Watts,NULL as S1_Tot_VA,NULL as S1_Tot_VAr,NULL as S1_KWh,NULL as S1_KVAh,NULL as S1_KVArh,NULL as S1_Freq,NULL as S1_AvgPF,NULL as S1_L1_PF,NULL as S1_L1_VAr,NULL as S1_L1_VA,NULL as S1_L1_Watts,NULL as S1_L1_Current,NULL as S1_L2_PF,NULL as S1_L2_VAr,NULL as S1_L2_VA,NULL as S1_L2_Watts,NULL as S1_L2_Current,NULL as S1_L3_PF,NULL as S1_L3_VAr,NULL as S1_L3_VA,NULL as S1_L3_Watts,NULL as S1_L3_Current,NULL as S2_Tot_Watts,NULL as S2_Tot_VA,NULL as S2_Tot_VAr,NULL as S2_KWh,NULL as S2_KVAh,NULL as S2_KVArh,NULL as S2_Freq,NULL as S2_AvgPF,NULL as S2_L1_PF,NULL as S2_L1_VAr,NULL as S2_L1_VA,NULL as S2_L1_Watts,NULL as S2_L1_Current,NULL as S2_L2_PF,NULL as S2_L2_VAr,NULL as S2_L2_VA,NULL as S2_L2_Watts,NULL as S2_L2_Current,NULL as S2_L3_PF,NULL as S2_L3_VAr,NULL as S2_L3_VA,NULL as S2_L3_Watts,NULL as S2_L3_Current,NULL as Main_Gen_LNVolt, H.GEN_L1_N_VOLT,H.GEN_L2_N_VOLT,H.GEN_L3_N_VOLT,H.GEN_L1_L2_VOLT,H.GEN_L2_L3_VOLT,H.GEN_L1_L3_VOLT,NULL As S1_L1_N_Voltage,NULL As S1_L2_N_Voltage,NULL As S1_L3_N_Voltage,NULL As S1_L1_L2_Voltage,NULL As S1_L2_L3_Voltage,NULL As S1_L3_L1_Voltage,NULL As S2_L1_N_Voltage,NULL As S2_L2_N_Voltage,NULL As S2_L3_N_Voltage,NULL As S2_L1_L2_Voltage,NULL As S2_L2_L3_Voltage,NULL As S2_L3_L1_Voltage,NULL AS S1_LN_Volt,NULL as S1_LL_Volt,NULL as S2_LN_Volt,NULL as S2_LL_Volt 
				from rvlfMsgInHst_Techno H
				INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
				INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId
				INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID
				inner join rvlfMAKDevices MD on MD.BoxId=H.BoxId
				left join rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId
				where VA.VehicleId = @deviceID
				and MD.IsDelete=0 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)) order by H.DateTimeReceived, H.MessageInID desc
				) as a order by Timestamp desc, MessageInID desc
			end
		else if(@DeviceTypeID=2)
			begin
				select *,ROW_NUMBER() over (order by timestamp) as AutoID
				from (
				select top 1 H.MessageInID,H.BoxId,VA.BoxID as DeviceID,H.BoxMsgInTypeId,H.CommInfo1,H.CommInfo2,H.CustomProp,H.StreetAddress,H.SequenceNum,H.IsArmed,H.IsProcessed,H.IsArchived,H.ControllerID,H.Alarm,NULL as Batt_Volt,'' as Batt_Current,'' as Batt_LstRreplacement,'' as Chrg_Alternator,NULL as Coolant_Temp,NULL as EngineSpeed,NULL as Engine_RunTime,NULL as FuelLevel,NULL as Tot_Watts,NULL as Tot_VA,NULL as Tot_VAr,NULL as Gen_KWh,NULL as Gen_KVAh,NULL as Gen_KVArh,NULL as Gen_Freq,NULL as Gen_AvgPF,NULL as Gen_L1_PF,NULL as Gen_L1_VAr,NULL as Gen_L1_VA,NULL as Gen_L1_Watts,NULL as Gen_L1_Current,NULL as Gen_L2_PF,NULL as Gen_L2_VAr,NULL as Gen_L2_VA,NULL as Gen_L2_Watts,NULL as Gen_L2_Current,NULL as Gen_L3_PF,NULL as Gen_L3_VAr,NULL as Gen_L3_VA,NULL as Gen_L3_Watts,NULL as Gen_L3_Current,NULL as Gen_LNVolt,NULL as Gen_LLVolt,NULL as NumofStarts,NULL as Oil_Temp,NULL as Oil_Pressure,H.GateWayID,H.ComMode, MD.EquipmentSrNo,
				[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime),
				DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,OriginDateTime),
				TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,OriginDateTime),
				DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [TimestampSort],v.vehicleid,vt.VehicleTypeName as CustomerName,vt.VehicleTypeId,MD.ContactNo,0 as isMapIT,CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,H.StreetAddress as Address, @Distance as Units,
				'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,(CASE WHEN cast(ISNULL(H.Latitude,0) as decimal(14,6)) = 0 THEN 1 ELSE ValidGps END) AS ValidGPS,
				cast(ISNULL(H.Latitude,0) as decimal(14,6)) as Latitude, cast(ISNULL(H.Longitude,0) as decimal(14,6)) as Longitude, 0 as Speed, CASE WHEN H.Speed = 0 OR H.ValidGps > 0 THEN -1 ELSE CAST(Heading as varchar(3)) END as Heading, v.VehicleDescription, OriginDateTime, BoxMsgInTypeDesc as [Message],'' as MessageDetails,0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus
				,isnull(H.S1_Tot_Watts ,'0') as S1_Tot_Watts
,isnull(H.S1_Tot_VA ,'0') as S1_Tot_VA
,isnull(H.S1_Tot_VAr ,'0') as S1_Tot_VAr
,isnull(H.S1_KWh ,'0') as S1_KWh
,isnull(H.S1_KVAh ,'0') as S1_KVAh
,isnull(H.S1_KVArh ,'0') as S1_KVArh
,isnull(H.S1_Freq ,'0') as S1_Freq
,isnull(H.S1_AvgPF ,'0') as S1_AvgPF
,isnull(H.S1_L1_PF ,'0') as S1_L1_PF
,isnull(H.S1_L1_VAr ,'0') as S1_L1_VAr
,isnull(H.S1_L1_VA ,'0') as S1_L1_VA
,isnull(H.S1_L1_Watts ,'0') as S1_L1_Watts
,isnull(H.S1_L1_Current ,'0') as S1_L1_Current
,isnull(H.S1_L2_PF ,'0') as S1_L2_PF
,isnull(H.S1_L2_VAr ,'0') as S1_L2_VAr
,isnull(H.S1_L2_VA ,'0') as S1_L2_VA
,isnull(H.S1_L2_Watts ,'0') as S1_L2_Watts
,isnull(H.S1_L2_Current ,'0') as S1_L2_Current
,isnull(H.S1_L3_PF ,'0') as S1_L3_PF
,isnull(H.S1_L3_VAr ,'0') as S1_L3_VAr
,isnull(H.S1_L3_VA ,'0') as S1_L3_VA
,isnull(H.S1_L3_Watts ,'0') as S1_L3_Watts
,isnull(H.S1_L3_Current ,'0') as S1_L3_Current
,isnull(H.S2_Tot_Watts ,'0') as S2_Tot_Watts
,isnull(H.S2_Tot_VA ,'0') as S2_Tot_VA
,isnull(H.S2_Tot_VAr ,'0') as S2_Tot_VAr
,isnull(H.S2_KWh ,'0') as S2_KWh
,isnull(H.S2_KVAh ,'0') as S2_KVAh
,isnull(H.S2_KVArh ,'0') as S2_KVArh
,isnull(H.S2_Freq ,'0') as S2_Freq
,isnull(H.S2_AvgPF ,'0') as S2_AvgPF
,isnull(H.S2_L1_PF ,'0') as S2_L1_PF
,isnull(H.S2_L1_VAr ,'0') as S2_L1_VAr
,isnull(H.S2_L1_VA ,'0') as S2_L1_VA
,isnull(H.S2_L1_Watts ,'0') as S2_L1_Watts
,isnull(H.S2_L1_Current ,'0') as S2_L1_Current
,isnull(H.S2_L2_PF ,'0') as S2_L2_PF
,isnull(H.S2_L2_VAr ,'0') as S2_L2_VAr
,isnull(H.S2_L2_VA ,'0') as S2_L2_VA
,isnull(H.S2_L2_Watts ,'0') as S2_L2_Watts
,isnull(H.S2_L2_Current ,'0') as S2_L2_Current
,isnull(H.S2_L3_PF ,'0') as S2_L3_PF
,isnull(H.S2_L3_VAr ,'0') as S2_L3_VAr
,isnull(H.S2_L3_VA ,'0') as S2_L3_VA
,isnull(H.S2_L3_Watts ,'0') as S2_L3_Watts
,isnull(H.S2_L3_Current ,'0') as S2_L3_Current
,isnull(H.Main_Gen_LNVolt ,'0') as Main_Gen_LNVolt
,isnull(H.S1_L1_N_Voltage ,'0') as S1_L1_N_Voltage
,isnull(H.S1_L2_N_Voltage ,'0') as S1_L2_N_Voltage
,isnull(H.S1_L3_N_Voltage ,'0') as S1_L3_N_Voltage
,isnull(H.S1_L1_L2_Voltage ,'0') as S1_L1_L2_Voltage
,isnull(H.S1_L2_L3_Voltage ,'0') as S1_L2_L3_Voltage
,isnull(H.S1_L3_L1_Voltage ,'0') as S1_L3_L1_Voltage
,isnull(H.S2_L1_N_Voltage ,'0') as S2_L1_N_Voltage
,isnull(H.S2_L2_N_Voltage ,'0') as S2_L2_N_Voltage
,isnull(H.S2_L3_N_Voltage ,'0') as S2_L3_N_Voltage
,isnull(H.S2_L1_L2_Voltage ,'0') as S2_L1_L2_Voltage
,isnull(H.S2_L2_L3_Voltage ,'0') as S2_L2_L3_Voltage
,isnull(H.S2_L3_L1_Voltage ,'0') as S2_L3_L1_Voltage
				,NULL as GEN_L1_N_VOLT,NULL as GEN_L2_N_VOLT,NULL as GEN_L3_N_VOLT,NULL as GEN_L1_L2_VOLT,NULL as GEN_L2_L3_VOLT,NULL as GEN_L1_L3_VOLT,H.S1_LN_Volt,H.S1_LL_Volt,H.S2_LN_Volt,H.S2_LL_Volt from rvlfMsgInHst_Techno_355 H
				INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
				INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId
				INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID
				inner join rvlfMAKDevices MD on MD.BoxId=H.BoxId
				left join rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId
				where VA.VehicleId = @deviceID
				and MD.IsDelete=0 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)) order by H.DateTimeReceived, H.MessageInID desc
				) as a order by Timestamp desc, MessageInID desc
			end
	End
GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng2_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[RVLT_SP_GetLatLng2_PhoneGap]      
(                    
	@vehicleId varchar(50),                    
	@startdate as datetime,                    
	@enddate datetime,                    
	@interval as int,                    
	@orderby varchar(10),                    
	@bigQueryingUser bigint = 0,                    
	@bitIsMDTMsg bit=0 ,                     
	@bigLastHours int = null,                  
	@controllerID varchar(50)=null      
)                    
as                   
/******************************************************************************/                    
--2013-01-30 11:12:17.890                
-- Name  : RVLT_SP_GetLatLng2_PhoneGap 805,'2017-11-29 10:00:00 AM','2017-11-29 11:10:00 AM',2000,'desc',453 ,0,0,'TR-A6'               
-- Description : To get the messages that needs to be shown in the grid                    
-- Author  : T. Sathish Kumar                    
-- Company  : Angler Technologies                    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
/******************************************************************************/                                           
	Begin                    
		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 
		DECLARE @OperationTypeID table (OperationTypeID bigint) 
		DECLARE @controllerType tinyint= (select VehicleTypeId from rvlfVehicle where VehicleId=@vehicleId)
		SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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           
		--print @HoursToBeAdded                    
		--print @MinsToBeAdded      
		INSERT INTO @OperationTypeID  
		SELECT OperationTypeID FROM rvlfUserGroupSecurity s                   
		WHERE s.ModuleId in(22,26) and s.UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser)                   
		-------------------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,BoxId bigint,DeviceID bigint,ValidGps int,Latitude varchar(4),Longitude varchar(4),Distance varchar(4),Speed varchar(4),
		Heading varchar(10),  
		[Timestamp] datetime,DateTimeReceived varchar(100),VehicleDescription varchar(500),MessageDetails varchar(1000),[Address] varchar(1500),Units varchar(100),IgnitionStatus int,
		StreetAddress varchar(1500),  
		isMapIT int,AutoID bigint,mapitFunction varchar(1000),Param1 varchar(50),Param2 varchar(50),Param3 varchar(50),
		Param4  varchar(50),Param5	varchar(50),Param6	varchar(50),Param7	varchar(50),Param8	varchar(50),Param9	varchar(50),Param10	varchar(50),
		Param11	varchar(50),Param12	varchar(50),Param13	varchar(50),VehicleTypeName varchar(50),VehicleTypeId tinyint,controllerID varchar(50),DCSIM tinyint,[Status] varchar(10),isAvail int,IsAlarm tinyint)  
       
		IF(@controllerType=1) 
			BEGIN                      
				insert into @tmpHistory      
				SELECT 
				MessageInID ,BoxId ,DeviceID ,ValidGps ,Latitude ,Longitude ,Distance ,Speed,Heading,  
				[Timestamp] ,[Timestamp] ,VehicleDescription ,MessageDetails ,[Address] ,Units ,IgnitionStatus ,StreetAddress,  
				isMapIT ,ROW_NUMBER() over (order by timestamp) as AutoID,                  
				'' as mapitFunction, Param1 ,Param2 ,Param3 ,Param4 ,Param5,Param6,Param7	,Param8	,Param9,Param10 ,Param11,Param12,Param13,VehicleTypeName,VehicleTypeId,controllerID,DCSIM,[Status],isAvail,Alarm
				FROM( 
				Select DISTINCT(H.MessageInID) as MessageInID,H.CustomProp,H.BoxId, MD.BoxID as DeviceID, 
				0 AS ValidGPS, 
				'0' as Latitude, '0' as Longitude,   
				H.NearestLandMark as Distance,'-'  as Speed,'0' as Heading, 
				[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
				--DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),			                
				MD.EquipmentName as VehicleDescription,    H.OriginDateTime,BoxMsgInTypeDesc as [Message],H.BoxMsgInTypeId as BoxMsgInTypeId , 
				H.OriginDateTime AS RoadsAPITime,  
				--TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,H.OriginDateTime),   
				--DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,H.OriginDateTime)) as [TimestampSort],   
				Case when H.BoxMsgInTypeId = 114 and CHARINDEX('18;GPRS',H.CustomProp,0) <> 0  THEN 'Send Health Status'      
				when h.BoxMsgInTypeId in (4,7,13,24) then ct.BoxMsgInTypeName +' '+isnull(cast(H.CmdId as varchar),'')       	
				ELSE ct.BoxMsgInTypeName --dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)
				END as MessageDetails, 0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,
				H.StreetAddress AS Address, @Distance as Units,                         
				--CASE WHEN H.ValidGps > 0 OR H.BoxMsgInTypeId IN (9,14,15,16,17,24) OR Speed = 0 then '-'                  
				--WHEN H.BoxMsgInTypeId IN (96) then '-' WHEN H.Heading between 335 and 360 THEN 'N'                  
				--WHEN H.Heading between 0 and 25 THEN 'N'   WHEN H.Heading between 25 and 65 THEN 'NE'                  
				--WHEN H.Heading between 65 and 115 THEN 'E'  WHEN H.Heading between 115 and 155 THEN 'SE'                  
				--WHEN H.Heading between 155 and 210 THEN 'S' WHEN H.Heading between 210 and 245 THEN 'SW'                  
				--WHEN H.Heading between 245 and 300 THEN 'W' WHEN H.Heading between 300 and 335 THEN 'NW' END as Direction ,											
				-- 'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,                  
				--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(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Idling:',';') 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 (dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SENSOR_STATUS=',';')) = 'ON' then 1 else 0 End End                  
				--	ELSE 2 END as IgnitionStatus,
				0 as IgnitionStatus,H.StreetAddress,
				0 AS IsDefaultAlarm,          
				0 as isMapIT,
				MD.vehicleid ,vt.VehicleTypeName,isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo,
				--isnull(H.controllerID,'-') as controllerID,
				(isnull(cast(cm.ControllerName as varchar(50)),'-')) +' - '+(isnull(cast(H.controllerID as varchar(2)),'-')) AS controllerID,
				isnull(p.RefID,'-') as RefID,isnull(p.CmdId,'-') as CmdId,ISNULL(h.DCSIM,'-') AS DCSIM,
				isnull([Seconday_Current_Limit(IDC)],'-') as Param1,isnull(Secondary_Voltage,'-') as Param2
				,isnull(Spark_Rate,'-') as Param3,isnull(Operating_Charge_Ratio,'-') as Param4
				,isnull(Optinal_Input_Power,'-') as Param5,isnull(Corona_Power,'-') as Param6,isnull(VDC_peak,'-') as Param7
				,isnull(VDC_Through,'-') as Param8,isnull(IAC_PRI,'-') as Param9,isnull(Operating_IDC_Limit,'-') as Param10
				,isnull(Mains_Frequency,'-') as Param11,isnull(Total_Accumulated_Spark,'-') as Param12,	isnull(Total_Operating_Time,'-') as Param13, 
				CASE WHEN H.CustomProp LIKE '%IsAlarm=1' THEN 'Alarm' ELSE (CASE WHEN DATEDIFF(HH,cm.LastReporteDateTime,GETDATE())> 24 THEN 'Offline' ELSE 'Online' END) END as [status],
				0 as isAvail,isnull(h.Alarm,0) as Alarm
				FROM rvlfMsgInHst H
				LEFT JOIN rvlfMsgInHstParam_PIII P on h.MessageInID=p.Messageinid
				--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                     
				INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId    
				--INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
				INNER JOIN rvlfMAKDevices MD on MD.BoxId=H.BoxId   
				inner join adrControllerMaster CM on h.boxid=CM.EquipmentId and h.ControllerID= CM.ControllerPositionId	and dcsim is null
				LEFT JOIN rvlfVehicleType vt on MD.SubTypeId=vt.VehicleTypeId	              
				WHERE  H.OriginDateTime BETWEEN CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109) 
				and  MD.VehicleId = @VehicleID and MD.IsDelete=0 and 
				(@controllerID is null or @controllerID='' or @controllerID='ALL' or cm.ControllerName =@controllerID)
				and CT.OperationTypeID IN (select OperationTypeID from @OperationTypeID) AND CommInfo1 IS NOT NULL   and H.BoxMsgInTypeId in (4,13,15) 
				--UNION ALL                  
				--   /************-------------------------------***** Get Commands details---------------------------------------******************/                  
				--    SELECT NULL as MessageInID,null as Customprop,null as BoxId,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,
				--	NULL as Speed, 0 as Heading,[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),        
				--	SentDateTime = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime), 
				--    V.VehicleDescription,'' as origindatetime,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId,
				--	CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 14) AS RoadsAPITime,                      
				--    TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime), 
				--       DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [TimestampSort],
				--    CASE WHEN OH.BoxCmdOutTypeId = 39 OR OH.BoxCmdOutTypeId = 4 THEN dbo.rvlf_fn_GetCmdMsgDetails(OH.CustomProp + ',', OH.BoxCmdOutTypeId, VA.BoxID)             ELSE BoxcmdTypeDesc END as MessageDetails,
				--	OH.UserId,Priority, 
				--    /**************** Changed the Acknowledgement to be return based on the value ************/                  
				--    CASE WHEN Acknowledged = 1 THEN 'True' WHEN Acknowledged = 0 THEN 'False' WHEN  Acknowledged = 2 THEN 'Success'                  
				--      WHEN  Acknowledged = 3 THEN 'Update Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect' WHEN  Acknowledged = 5 THEN 'No Communication'                  
				--      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'                  
				--      ELSE 'Nothing' END AS Acknowledged,                  
				--    CASE WHEN Acknowledged = 1 THEN 'Acknowledged' WHEN Acknowledged = 0 THEN 'Not Acknowledged' WHEN  Acknowledged = 2 THEN 'Success'                  
				--      WHEN  Acknowledged = 3 THEN 'Upgrade Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect'   WHEN  Acknowledged = 5 THEN 'No Communication'  
				--      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'      
				--      ELSE '' END AS AckStatus,                  
				--    'N/A' as Address,@Distance as Units,'' as Direction ,/*null as mapitFunction,*/'setValue('' '')' as jsFunction, NULL as IgnitionStatus,
				--	NULL as StreetAddress, NULL as IsDefaultAlarm,null as isMapIT ,va.vehicleid,vt.VehicleTypeName , isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo ,
				--	NULL,NULL,NULL,NULL,'-','-','-','-','-','-','-','-','-','-','-','-','-',
				--	 (CASE WHEN DATEDIFF(HH,B.LastStatusDateTime,GETDATE())> 24 THEN 'Offline' ELSE 'Online' END) as [status],0 as isAvail
				--    FROM rvlfMsgOutHst OH    
				--	inner join rvlfBoxId b on oh.BoxId=b.BoxId                
				--    INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID 
				--	INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID                  
				--    INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId  
				--	INNER JOIN rvlfMAKDevices MD on MD.BoxId=oH.BoxId   
				--	LEFT JOIN rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId                
				--    WHERE  SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)                  
				--    AND VA.VehicleID = @VehicleID and CT.OperationTypeId IN (select OperationTypeID from @OperationTypeID) 
				) as a --ORDER BY Timestamp desc, MessageInID DESC 
			END
		ELSE IF(@controllerType=2) 
			BEGIN  
				insert into @tmpHistory
				SELECT 
				MessageInID ,BoxId ,DeviceID ,ValidGps ,Latitude ,Longitude ,Distance ,Speed ,Heading ,  
				[Timestamp] ,[Timestamp] ,VehicleDescription ,MessageDetails ,[Address] ,Units ,IgnitionStatus ,StreetAddress,  
				isMapIT ,ROW_NUMBER() over (order by timestamp) as AutoID,                  
				''  as mapitFunction,
				Param1 ,Param2 ,Param3 ,Param4 ,Param5,Param6,Param7	,Param8	,Param9,Param10 ,Param11,Param12,Param13,VehicleTypeName,VehicleTypeId,controllerID,DCSIM,[Status],isAvail,Alarm
				FROM( 
				Select DISTINCT(H.MessageInID) as MessageInID,H.CustomProp,H.BoxId, MD.BoxID as DeviceID, 
				0 AS ValidGPS, 
				'0' as Latitude, '0' as Longitude,   
				H.NearestLandMark as Distance,'-'  as Speed,'0' as Heading, 
				[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
				--DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
				MD.EquipmentName as VehicleDescription, H.OriginDateTime,BoxMsgInTypeDesc as [Message],H.BoxMsgInTypeId as BoxMsgInTypeId , 
				H.OriginDateTime AS RoadsAPITime,    
				--TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,H.OriginDateTime),   
				--DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,H.OriginDateTime)) as [TimestampSort],                                 
				Case --when H.BoxMsgInTypeId = 114 and CHARINDEX('18;GPRS',H.CustomProp,0) <> 0  THEN 'Send Health Status'      
				when h.BoxMsgInTypeId in (4,7,13,24) then ct.BoxMsgInTypeName +' '+isnull(cast(H.CmdId as varchar),'')       	
				ELSE  ct.BoxMsgInTypeName --dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)
				END as MessageDetails, 0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,
				H.StreetAddress AS Address, @Distance as Units,                         
				--CASE WHEN H.ValidGps > 0 OR H.BoxMsgInTypeId IN (9,14,15,16,17,24) OR Speed = 0 then '-'                  
				--WHEN H.BoxMsgInTypeId IN (96) then '-' WHEN H.Heading between 335 and 360 THEN 'N'                  
				--WHEN H.Heading between 0 and 25 THEN 'N'   WHEN H.Heading between 25 and 65 THEN 'NE'                  
				--WHEN H.Heading between 65 and 115 THEN 'E'  WHEN H.Heading between 115 and 155 THEN 'SE'                  
				--WHEN H.Heading between 155 and 210 THEN 'S' WHEN H.Heading between 210 and 245 THEN 'SW'                  
				--WHEN H.Heading between 245 and 300 THEN 'W' WHEN H.Heading between 300 and 335 THEN 'NW' END as Direction ,											
				--'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,                  
				0 as IgnitionStatus,
				Replace(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''')  as StreetAddress,
				0 AS IsDefaultAlarm,       
				0 as isMapIT,
				MD.vehicleid ,vt.VehicleTypeName,isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo
				, (isnull(cast(cm.ControllerName as varchar(50)),'-')) +' - '+(isnull(cast(H.controllerID as varchar(2)),'-')) AS controllerID,
				--ISNULL(H.controllerID,'-') AS controllerID,
				ISNULL(P.RefID,'-') AS RefID,ISNULL(P.CmdId,'-') AS CmdId,ISNULL(h.DCSIM,'-') AS DCSIM,
				ISNULL(P.Primary_Voltage_Value,'-') AS Param1,ISNULL(P.Primary_Current_Value,'-') AS Param2
				,ISNULL(P.Primary_Power_Value,'-') AS Param3,ISNULL(P.Secondary_Voltage_Value,'-') AS Param4,
				ISNULL(P.Secondary_Current_Value,'-') AS Param5,ISNULL(P.Spark_Per_Minute,'-') AS Param6
				,ISNULL(P.Arcs_Per_Minute,'-') AS Param7,
				ISNULL(P.Under_Voltage_TripMode,'-') AS Param8,
				ISNULL(P.Program_no_of_Rapper,'-') AS Param9,ISNULL(P.Primary_Voltage_limit,'-') AS Param10
				,ISNULL(P.Primary_Current_Limit,'-') AS Param11,ISNULL(P.Secondary_Voltage_Limit,'-') AS Param12,
				ISNULL(P.Secondary_Current_Limit,'-') AS Param13,
				CASE	WHEN  CHARINDEX('%IsAlarm=1%', H.CustomProp)<>0  THEN 'Alarm' ELSE (CASE WHEN DATEDIFF(HH,CM.LastReporteDateTime,GETDATE())> 24 THEN 'Offline' ELSE 'Online' END) END as [status], 
				case when h.BoxMsgInTypeId= 24 then 1 else 0 end as isAvail,isnull(h.Alarm,0) as Alarm
				FROM rvlfMsgInHst H                   
				left JOIN rvlfMsgInHstParam_PR P on h.MessageInID=p.Messageinid
				--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                     
				INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                      
				--INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
				INNER JOIN rvlfMAKDevices MD on MD.BoxId=H.BoxId 
				inner join adrControllerMaster CM on h.boxid=CM.EquipmentId and h.ControllerID= CM.ControllerPositionId	and h.DCSIM=cm.DCSIMId
				left join rvlfAlarm a on h.MessageInID=a.MessageInID  
				LEFT JOIN rvlfVehicleType vt on MD.SubTypeId=vt.VehicleTypeId	              
				WHERE  H.OriginDateTime BETWEEN CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109) 
				and  MD.VehicleId = @VehicleID and MD.IsDelete=0 and 
				(@controllerID is null or @controllerID='' or @controllerID='ALL' or  cm.ControllerName=@controllerID)
				and CT.OperationTypeID IN (select OperationTypeID from @OperationTypeID) AND CommInfo1 IS NOT NULL  and H.BoxMsgInTypeId in (7,24,15)    
				--UNION ALL              
				--   /************-------------------------------***** Get Commands details---------------------------------------******************/                  
				--    SELECT NULL as MessageInID,null as Customprop,null as BoxId,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,
				--	NULL as Speed, 0 as Heading,[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),        
				--	SentDateTime = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime), 
				--    V.VehicleDescription,'' as origindatetime,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId,
				--	CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 14) AS RoadsAPITime,                      
				--    TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime), 
				--       DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [TimestampSort],
				--    CASE WHEN OH.BoxCmdOutTypeId = 39 OR OH.BoxCmdOutTypeId = 4 THEN dbo.rvlf_fn_GetCmdMsgDetails(OH.CustomProp + ',', OH.BoxCmdOutTypeId, VA.BoxID)                        ELSE BoxcmdTypeDesc END as MessageDetails,
				--	 OH.UserId,Priority, 
				--  /**************** Changed the Acknowledgement to be return based on the value ************/                  
				--    CASE WHEN Acknowledged = 1 THEN 'True' WHEN Acknowledged = 0 THEN 'False' WHEN  Acknowledged = 2 THEN 'Success'                  
				--      WHEN  Acknowledged = 3 THEN 'Update Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect' WHEN  Acknowledged = 5 THEN 'No Communication'                  
				--      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'                  
				--      ELSE 'Nothing' END AS Acknowledged,                  
				--    CASE WHEN Acknowledged = 1 THEN 'Acknowledged' WHEN Acknowledged = 0 THEN 'Not Acknowledged' WHEN  Acknowledged = 2 THEN 'Success'                  
				--      WHEN  Acknowledged = 3 THEN 'Upgrade Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect'   WHEN  Acknowledged = 5 THEN 'No Communication'  
				--      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'      
				--      ELSE '' END AS AckStatus,                  
				--    'N/A' as Address,@Distance as Units,'' as Direction ,/*null as mapitFunction,*/'setValue('' '')' as jsFunction, NULL as IgnitionStatus,
				--	NULL as StreetAddress, NULL as IsDefaultAlarm,null as isMapIT ,va.vehicleid,vt.VehicleTypeName , isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo  ,
				--	NULL,NULL,NULL,NULL,'-','-','-','-','-','-','-','-','-','-','-','-','-'  ,
				--	(CASE WHEN DATEDIFF(HH,B.LastStatusDateTime,GETDATE())> 24 THEN 'Offline' ELSE 'Online' END) as [status]  ,   0 as isAvail       
				--    FROM rvlfMsgOutHst OH inner join rvlfBoxId b on oh.BoxId=b.BoxId                 
				--    INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID 
				--	INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID                  
				--    INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId  
				--	INNER JOIN rvlfMAKDevices MD on MD.BoxId=oH.BoxId   
				--	LEFT JOIN rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId                
				--    WHERE  SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)                  
				--    AND VA.VehicleID = @VehicleID and CT.OperationTypeId IN (select OperationTypeID from @OperationTypeID)
				) as a --ORDER BY Timestamp desc, MessageInID DESC 
			End 
  
		Select * from @tmpHistory order by Timestamp desc, MessageInID desc       

		Select null  as PlayBackLatLong               
                  
	End 



GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng2_PhoneGap_bkp]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[RVLT_SP_GetLatLng2_PhoneGap_bkp]      
(                    
 @vehicleId varchar(50),                    
 @startdate as datetime,                    
 @enddate datetime,                    
 @interval as int,                    
 @orderby varchar(10),                    
 @bigQueryingUser bigint = 0,                    
 @bitIsMDTMsg bit=0 ,                     
 @bigLastHours int = null,                  
 @controllerID int=null   
)                    
as                   
/******************************************************************************/                    
--2013-01-30 11:12:17.890                
-- Name  : RVLT_SP_GetLatLng2_PhoneGap 805,'2017-12-05 10:00:00 AM','2017-12-05 11:00:00 AM',2000,'desc',454               
-- Description : To get the messages that needs to be shown in the grid                    
-- Author  : T. Sathish Kumar                    
-- Company  : Angler Technologies                    
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason    
/******************************************************************************/                                           
Begin                    
   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 
	DECLARE @OperationTypeID table (OperationTypeID bigint) 
    DECLARE @controllerType tinyint= (select VehicleTypeId from rvlfVehicle where VehicleId=@vehicleId)

  SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@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           
                        
    --print @HoursToBeAdded                    
    --print @MinsToBeAdded      
 INSERT INTO @OperationTypeID  
	SELECT OperationTypeID FROM rvlfUserGroupSecurity s                   
     WHERE s.ModuleId in(22,26) and s.UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser)                   
                      
	-------------------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,BoxId bigint,DeviceID bigint,ValidGps int,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),Units varchar(100),IgnitionStatus int,StreetAddress varchar(max),  
    isMapIT int,AutoID bigint,mapitFunction varchar(max),Param1 varchar(50),Param2 varchar(50),Param3 varchar(50),
Param4  varchar(50),Param5	varchar(50),Param6	varchar(50),Param7	varchar(50),Param8	varchar(50),Param9	varchar(50),Param10	varchar(50),
Param11	varchar(50),Param12	varchar(50),Param13	varchar(50),VehicleTypeName varchar(50),VehicleTypeId tinyint,controllerID tinyint,DCSIM tinyint,[Status] varchar(10),isAvail int)  
       
                   
    IF(@controllerType=1) 
BEGIN                      
 insert into @tmpHistory      
   SELECT 
   MessageInID ,BoxId ,DeviceID ,ValidGps ,Latitude ,Longitude ,Distance ,Speed ,Heading ,  
    [Timestamp] ,DateTimeReceived ,VehicleDescription ,MessageDetails ,[Address] ,Units ,IgnitionStatus ,StreetAddress,  
     isMapIT ,ROW_NUMBER() over (order by timestamp) as AutoID,                  
     ';SetMapItValue('''+CAST(Latitude as varchar(15)) +'~#~'+CAST(Longitude as varchar(15))+'~#~' +StreetAddress+'~#~'+ '-'+'~#~'+ 
     Convert(varchar,[TimeStamp],101)+' '+ SubString(Convert(varchar,[TimeStamp],9),12,9) + SUBSTRING(Convert(varchar,[TimeStamp],9), 25, 2) + '~#~'
	 + CAST(Heading as varchar(3))+ '~#~'+ISNULL(cast(a.Distance as varchar(5)),'')+'~#~'+ cast(isNull(IgnitionStatus,0) as CHAR(1)) +        
     '~#~'+'' +'~#~'+ replace(MessageDetails,@NewLine,'') +'~#~'+CAST(MessageInID AS varchar(40))+'~&~'', this.checked, this.id);'  as mapitFunction,
	 Param1 ,Param2 ,Param3 ,Param4 ,Param5,Param6,Param7	,Param8	,Param9,Param10 ,Param11,Param12,Param13,VehicleTypeName,VehicleTypeId,controllerID,DCSIM,[Status],isAvail
	 --,Param14,Param15,Param16,Param17 ,Param18,Param19,Param20,Param21,Param22 ,Param23,Param24,Param25,Param26,Param27,Param28,Param29,Param30,
	 --Param31,Param32 ,Param33,Param34,Param35,Param36,Param37,Param38,Param39,Param40,Param41,Param42,Param43,Param44,Param45,Param46 ,Param47
   FROM( 
		Select DISTINCT(H.MessageInID) as MessageInID,H.CustomProp,H.BoxId, VA.BoxID as DeviceID, 
			(CASE WHEN cast(ISNULL(H.Latitude,0) as decimal(14,6)) = 0 THEN 1 ELSE ValidGps END) AS ValidGPS, 
			cast(ISNULL(H.Latitude,0) as decimal(14,6)) as Latitude, cast(ISNULL(H.Longitude,0) as decimal(14,6)) as Longitude,   
			H.NearestLandMark as Distance,'-'  as Speed,CASE WHEN H.Speed = 0 OR H.ValidGps > 0 THEN -1 ELSE CAST(h.Heading as varchar(3))  END as Heading, 
			[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
			DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
			v.VehicleDescription,    H.OriginDateTime,BoxMsgInTypeDesc as [Message],H.BoxMsgInTypeId as BoxMsgInTypeId , 
			CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,H.OriginDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD					(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,H.OriginDateTime)), 14) AS RoadsAPITime,  
			TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,H.OriginDateTime),   
			DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,H.OriginDateTime)) as [TimestampSort],   
			Case when H.BoxMsgInTypeId = 114 and CHARINDEX('18;GPRS',H.CustomProp,0) <> 0  THEN 'Send Health Status'      
			when h.BoxMsgInTypeId in (4,7,13,24) then ct.BoxMsgInTypeName +' '+isnull(cast(H.CmdId as varchar),'')       	
			ELSE dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)
			END as MessageDetails, 0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,
			H.StreetAddress AS Address, @Distance as Units,                         
			CASE WHEN H.ValidGps > 0 OR H.BoxMsgInTypeId IN (9,14,15,16,17,24) OR Speed = 0 then '-'                  
			WHEN H.BoxMsgInTypeId IN (96) then '-' WHEN H.Heading between 335 and 360 THEN 'N'                  
			WHEN H.Heading between 0 and 25 THEN 'N'   WHEN H.Heading between 25 and 65 THEN 'NE'                  
			WHEN H.Heading between 65 and 115 THEN 'E'  WHEN H.Heading between 115 and 155 THEN 'SE'                  
			WHEN H.Heading between 155 and 210 THEN 'S' WHEN H.Heading between 210 and 245 THEN 'SW'                  
			WHEN H.Heading between 245 and 300 THEN 'W' WHEN H.Heading between 300 and 335 THEN 'NW' END as Direction ,											
			 'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,                  
			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(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Idling:',';') 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 (dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SENSOR_STATUS=',';')) = 'ON' then 1 else 0 End End                  
				ELSE 2 END as IgnitionStatus,
			Replace(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''')  as StreetAddress,
			CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,          
           (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,
			v.vehicleid ,vt.VehicleTypeName,isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo,
		isnull(H.controllerID,'-') as controllerID,isnull(p.RefID,'-') as RefID,isnull(p.CmdId,'-') as CmdId,ISNULL(h.DCSIM,'-') AS DCSIM,
		isnull([Seconday_Current_Limit(IDC)],'-') as Param1,
		isnull(Secondary_Voltage,'-') as Param2
		,isnull(Spark_Rate,'-') as Param3,isnull(Operating_Charge_Ratio,'-') as Param4
		,isnull(Optinal_Input_Power,'-') as Param5,isnull(Corona_Power,'-') as Param6,isnull(VDC_peak,'-') as Param7
		,isnull(VDC_Through,'-') as Param8,isnull(IAC_PRI,'-') as Param9,isnull(Operating_IDC_Limit,'-') as Param10
		,isnull(Mains_Frequency,'-') as Param11,isnull(Total_Accumulated_Spark,'-') as Param12,
		isnull(Total_Operating_Time,'-') as Param13, 

		CASE	WHEN H.CustomProp LIKE '%IsAlarm=1' THEN 'Alarm' 
		ELSE (CASE WHEN DATEDIFF(HH,B.LastStatusDateTime,GETDATE())> 24 THEN 'Offline' ELSE 'Online' END) 
 END as [status],
 0 as isAvail
		--isnull(Operating_Corona_Energy,'-') as Param14
		--,isnull(Input_Energy,'-') as Param15,isnull(Secondary_current_Limit,'-') as Param16
		--,isnull(Sec_Current_Drop_AfterSpark,'-') as Param17,isnull(T_Recovery_cyc,'-') as Param18
		--,isnull(T_Fast_Ramp_cyc,'-') as Param19,isnull(Charge_Ratio,'-') as Param20
		--,isnull(Recharge_HW,'-') as Param21,isnull(BC_IDC_Min,'-') as Param22
		--,isnull(RAP_IDC_Limit,'-') as Param23,isnull(BC_CR_Maximum,'-') as Param24
		--,isnull(Load_Status1_IDC_Limit,'-') as Param25,isnull(LS_1_V_Limit,'-') as Param26
		--,isnull(LS_1_IDC_Setbk,'-') as Param27,isnull(RAP_TM1_Pause,'-') as Param28
		--,isnull(RAP_TM1_Run,'-') as Param29,isnull(RAP_TM2_Pause,'-') as Param30
		--,isnull(RAP_TM2_Run,'-') as Param31,isnull(RAP_TM3_Pause,'-') as Param32
		--,isnull(RAP_TM3_Run,'-') as Param33,
		--isnull((case when RAP_MOT1_ON_OFF=0 then 'OFF' when RAP_MOT1_ON_OFF=1 then 'ON' else '-'end ),'-') as Param34
		--,isnull((case when RAP_MOT2_ON_OFF=0 then 'OFF' when RAP_MOT2_ON_OFF=1 then 'ON' else '-'end ),'-') as Param35,
		--isnull((case when RAP_MOT3_ON_OFF=0 then 'OFF' when RAP_MOT3_ON_OFF=1 then 'ON' else '-'end ),'-') as Param36
		--,isnull((case when RAP_CONT_ON_OFF=0 then 'OFF' when RAP_CONT_ON_OFF=1 then 'ON' else '-'end ),'-') as Param37,
		--isnull((case when Back_Corona_ON_OFF=0 then 'OFF' when Back_Corona_ON_OFF=1 then 'ON' else '-'end ),'-') as Param38
		--,isnull((case when HT_ON_OFF=0 then 'OFF' when HT_ON_OFF=1 then 'ON' else '-'end ),'-') as Param39
		--,isnull(Sec_Curr_drop_after_dbleSpark,'-') as Param40
		--,isnull(MAX_Spark_Rate,'-') as Param41,isnull(TQuench_CYC,'-') as Param42
		--,isnull(Back_Corona_MEAS,'-') as Param43,isnull(BC_IDC_Step,'-') as Param44
		--,isnull(BC_Hold_Time,'-') as Param45,isnull([LS-1_CR],'-') as Param46
		--,isnull(RECHARGE_FIRING,'-') as Param47
		FROM rvlfMsgInHst H   
		inner join rvlfBoxId b on h.BoxId=b.BoxId                
		left JOIN rvlfMsgInHstParam_PIII P on h.MessageInID=p.Messageinid
		INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                     
		INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                      
		INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
		INNER JOIN rvlfMAKDevices MD on MD.BoxId=H.BoxId   
		LEFT JOIN rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId	              
		WHERE  H.OriginDateTime BETWEEN CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109) 
		and  VA.VehicleId = @VehicleID and MD.IsDelete=0 and 
		(@controllerID is null or @controllerID=0 or p.controllerID=@controllerID)
		and CT.OperationTypeID IN (select OperationTypeID from @OperationTypeID) AND CommInfo1 IS NOT NULL   and H.BoxMsgInTypeId in (4,13,15)               
   
UNION ALL                  
   /************-------------------------------***** Get Commands details---------------------------------------******************/                  
    SELECT NULL as MessageInID,null as Customprop,null as BoxId,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,
	NULL as Speed, 0 as Heading,[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),        
	SentDateTime = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime), 
    V.VehicleDescription,'' as origindatetime,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId,
	CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 14) AS RoadsAPITime,                      
    TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime), 
       DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [TimestampSort],
    CASE WHEN OH.BoxCmdOutTypeId = 39 OR OH.BoxCmdOutTypeId = 4 THEN dbo.rvlf_fn_GetCmdMsgDetails(OH.CustomProp + ',', OH.BoxCmdOutTypeId, VA.BoxID)             ELSE BoxcmdTypeDesc END as MessageDetails,
	OH.UserId,Priority, 
    /**************** Changed the Acknowledgement to be return based on the value ************/                  
    CASE WHEN Acknowledged = 1 THEN 'True' WHEN Acknowledged = 0 THEN 'False' WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Update Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect' WHEN  Acknowledged = 5 THEN 'No Communication'                  
      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'                  
      ELSE 'Nothing' END AS Acknowledged,                  
    CASE WHEN Acknowledged = 1 THEN 'Acknowledged' WHEN Acknowledged = 0 THEN 'Not Acknowledged' WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Upgrade Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect'   WHEN  Acknowledged = 5 THEN 'No Communication'  
      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'      
      ELSE '' END AS AckStatus,                  
    'N/A' as Address,@Distance as Units,'' as Direction ,/*null as mapitFunction,*/'setValue('' '')' as jsFunction, NULL as IgnitionStatus,
	NULL as StreetAddress, NULL as IsDefaultAlarm,null as isMapIT ,va.vehicleid,vt.VehicleTypeName , isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo ,
	NULL,NULL,NULL,NULL,'-','-','-','-','-','-','-','-','-','-','-','-','-',
	 (CASE WHEN DATEDIFF(HH,B.LastStatusDateTime,GETDATE())> 24 THEN 'Offline' ELSE 'Online' END) as [status],0 as isAvail
    FROM rvlfMsgOutHst OH    
	inner join rvlfBoxId b on oh.BoxId=b.BoxId                
    INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID 
	INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID                  
    INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId  
	INNER JOIN rvlfMAKDevices MD on MD.BoxId=oH.BoxId   
	LEFT JOIN rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId                
    WHERE  SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)                  
    AND VA.VehicleID = @VehicleID and CT.OperationTypeId IN (select OperationTypeID from @OperationTypeID) 
) as a --ORDER BY Timestamp desc, MessageInID DESC 
END
ELSE IF(@controllerType=2) 
BEGIN  
 insert into @tmpHistory
  SELECT 
   MessageInID ,BoxId ,DeviceID ,ValidGps ,Latitude ,Longitude ,Distance ,Speed ,Heading ,  
    [Timestamp] ,DateTimeReceived ,VehicleDescription ,MessageDetails ,[Address] ,Units ,IgnitionStatus ,StreetAddress,  
     isMapIT ,ROW_NUMBER() over (order by timestamp) as AutoID,                  
     ';SetMapItValue('''+CAST(Latitude as varchar(15)) +'~#~'+CAST(Longitude as varchar(15))+'~#~' +StreetAddress+'~#~'+ '-'+'~#~'+ 
     Convert(varchar,[TimeStamp],101)+' '+ SubString(Convert(varchar,[TimeStamp],9),12,9) + SUBSTRING(Convert(varchar,[TimeStamp],9), 25, 2) + '~#~'
	 + CAST(Heading as varchar(3))+ '~#~'+ISNULL(cast(a.Distance as varchar(5)),'')+'~#~'+ cast(isNull(IgnitionStatus,0) as CHAR(1)) +        
     '~#~'+'' +'~#~'+ replace(MessageDetails,@NewLine,'') +'~#~'+CAST(MessageInID AS varchar(40))+'~&~'', this.checked, this.id);'  as mapitFunction,
	 Param1 ,Param2 ,Param3 ,Param4 ,Param5,Param6,Param7	,Param8	,Param9,Param10 ,Param11,Param12,Param13,VehicleTypeName,VehicleTypeId,controllerID,DCSIM,[Status],isAvail
	 --,Param14,Param15,Param16,Param17 ,Param18,Param19,Param20,Param21,Param22 ,Param23,Param24,Param25,Param26,Param27,Param28,Param29,Param30,
	 --Param31,Param32 ,Param33,Param34,Param35,Param36,Param37,Param38,Param39,Param40,Param41,Param42,Param43,Param44,Param45,Param46 ,Param47                             
  
   FROM( 
		Select DISTINCT(H.MessageInID) as MessageInID,H.CustomProp,H.BoxId, VA.BoxID as DeviceID, 
			(CASE WHEN cast(ISNULL(H.Latitude,0) as decimal(14,6)) = 0 THEN 1 ELSE ValidGps END) AS ValidGPS, 
			cast(ISNULL(H.Latitude,0) as decimal(14,6)) as Latitude, cast(ISNULL(H.Longitude,0) as decimal(14,6)) as Longitude,   
			H.NearestLandMark as Distance,'-'  as Speed,CASE WHEN H.Speed = 0 OR H.ValidGps > 0 THEN -1 ELSE CAST(h.Heading as varchar(3))  END as Heading, 
			[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
			DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
			v.VehicleDescription,    H.OriginDateTime,BoxMsgInTypeDesc as [Message],H.BoxMsgInTypeId as BoxMsgInTypeId , 
			CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,H.OriginDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD					(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,H.OriginDateTime)), 14) AS RoadsAPITime,    
			TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,H.OriginDateTime),   
			DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,H.OriginDateTime)) as [TimestampSort],                                 
			Case when H.BoxMsgInTypeId = 114 and CHARINDEX('18;GPRS',H.CustomProp,0) <> 0  THEN 'Send Health Status'      
			when h.BoxMsgInTypeId in (4,7,13,24) then ct.BoxMsgInTypeName +' '+isnull(cast(H.CmdId as varchar),'')       	
			ELSE dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime,@Lang)
			END as MessageDetails, 0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,
			H.StreetAddress AS Address, @Distance as Units,                         
			CASE WHEN H.ValidGps > 0 OR H.BoxMsgInTypeId IN (9,14,15,16,17,24) OR Speed = 0 then '-'                  
			WHEN H.BoxMsgInTypeId IN (96) then '-' WHEN H.Heading between 335 and 360 THEN 'N'                  
			WHEN H.Heading between 0 and 25 THEN 'N'   WHEN H.Heading between 25 and 65 THEN 'NE'                  
			WHEN H.Heading between 65 and 115 THEN 'E'  WHEN H.Heading between 115 and 155 THEN 'SE'                  
			WHEN H.Heading between 155 and 210 THEN 'S' WHEN H.Heading between 210 and 245 THEN 'SW'                  
			WHEN H.Heading between 245 and 300 THEN 'W' WHEN H.Heading between 300 and 335 THEN 'NW' END as Direction ,											
			 'setValue('''+ cast(H.MessageInID AS varchar(50))+''',this)' as jsFunction,                  
			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(dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'Idling:',';') 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 (dbo.rvlf_fn_GetParamValueWithIndex(h.CustomProp,'SENSOR_STATUS=',';')) = 'ON' then 1 else 0 End End                  
				ELSE 2 END as IgnitionStatus,
			Replace(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''')  as StreetAddress,
			CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,       
           (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,
			v.vehicleid ,vt.VehicleTypeName,isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo
	,ISNULL(H.controllerID,'-') AS controllerID,ISNULL(P.RefID,'-') AS RefID,ISNULL(P.CmdId,'-') AS CmdId,ISNULL(h.DCSIM,'-') AS DCSIM,
	ISNULL(P.Primary_Voltage_Value,'-') AS Param1,ISNULL(P.Primary_Current_Value,'-') AS Param2
	,ISNULL(P.Primary_Power_Value,'-') AS Param3,ISNULL(P.Secondary_Voltage_Value,'-') AS Param4,
	ISNULL(P.Secondary_Current_Value,'-') AS Param5,ISNULL(P.Spark_Per_Minute,'-') AS Param6
	,ISNULL(P.Arcs_Per_Minute,'-') AS Param7,
	ISNULL(P.Under_Voltage_TripMode,'-') AS Param8,
	ISNULL(P.Program_no_of_Rapper,'-') AS Param9,ISNULL(P.Primary_Voltage_limit,'-') AS Param10
	,ISNULL(P.Primary_Current_Limit,'-') AS Param11,ISNULL(P.Secondary_Voltage_Limit,'-') AS Param12,
	ISNULL(P.Secondary_Current_Limit,'-') AS Param13,
		CASE	WHEN  CHARINDEX('%IsAlarm=1%', H.CustomProp)<>0  THEN 'Alarm' 
		ELSE (CASE WHEN DATEDIFF(HH,B.LastStatusDateTime,GETDATE())> 24 THEN 'Offline' ELSE 'Online' END) 
 END as [status], 
 case when h.BoxMsgInTypeId= 24 then 1 else 0 end as isAvail
	--,ISNULL(P.Under_Voltage_Set_Point,'-') AS Param14,
	--ISNULL(P.Secondary_Current_Peak_Limit,'-') AS Param15,ISNULL(P.Ramp,'-') AS Param16,ISNULL(P.Pedestal,'-') AS Param17,
	--ISNULL(P.Quench_Time,'-') AS Param18,ISNULL(P.Spark_Rate,'-') AS Param19,ISNULL(P.IE_Charge_Halfcycle,'-') AS Param20,
	--ISNULL(P.IE_Discharge_Cycle,'-') AS Param21,ISNULL(P.IE_Background_Power,'-') AS Param22	,
	--ISNULL(P.IE_Optimise_Timer,'-') AS Param23,ISNULL(P.Power_Down_Rapping,'-') AS Param24,
	--ISNULL(P.Rapper1_Interval_Timer,'-') AS Param25,ISNULL(P.Rapper1_On_timer,'-') AS Param26,
	--ISNULL(P.Rapper2_Interval_timer,'-') AS Param27,ISNULL(P.Rapper2_On_Timer,'-') AS Param28,
	--ISNULL(P.Rapper3_Interval_Timer,'-') AS Param29,ISNULL(P.Rapper3_On_Timer,'-') AS Param30,
	--ISNULL(P.Rapper4_Interval_Timer,'-') AS Param31,ISNULL(P.Rapper4_On_Timer,'-') AS Param32,ISNULL(P.Phase_Back,'-') AS Param33,
	--null as Param34,null as Param35,null as Param36,null as Param37,null as Param38,null as Param39,null as Param40,null as Param41,null as Param42
	--	,null as Param43,null as Param44,null as Param45,null as Param46,null as Param47
		FROM rvlfMsgInHst H  inner join rvlfBoxId b on h.BoxId=b.BoxId                 
		left JOIN rvlfMsgInHstParam_PR P on h.MessageInID=p.Messageinid
		INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                     
		INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                      
		INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
		INNER JOIN rvlfMAKDevices MD on MD.BoxId=H.BoxId   
		LEFT JOIN rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId	              
		WHERE  H.OriginDateTime BETWEEN CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109) 
		and  VA.VehicleId = @VehicleID and MD.IsDelete=0 and
		(@controllerID is null or @controllerID=0 or p.controllerID=@controllerID)
		and CT.OperationTypeID IN (select OperationTypeID from @OperationTypeID) AND CommInfo1 IS NOT NULL  and H.BoxMsgInTypeId in (7,24,15)                
   
UNION ALL              
   /************-------------------------------***** Get Commands details---------------------------------------******************/                  
    SELECT NULL as MessageInID,null as Customprop,null as BoxId,VA.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,
	NULL as Speed, 0 as Heading,[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),        
	SentDateTime = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime), 
    V.VehicleDescription,'' as origindatetime,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId,
	CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 14) AS RoadsAPITime,                      
    TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime), 
       DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [TimestampSort],
    CASE WHEN OH.BoxCmdOutTypeId = 39 OR OH.BoxCmdOutTypeId = 4 THEN dbo.rvlf_fn_GetCmdMsgDetails(OH.CustomProp + ',', OH.BoxCmdOutTypeId, VA.BoxID)                        ELSE BoxcmdTypeDesc END as MessageDetails,
	 OH.UserId,Priority, 
  /**************** Changed the Acknowledgement to be return based on the value ************/                  
    CASE WHEN Acknowledged = 1 THEN 'True' WHEN Acknowledged = 0 THEN 'False' WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Update Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect' WHEN  Acknowledged = 5 THEN 'No Communication'                  
      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'                  
      ELSE 'Nothing' END AS Acknowledged,                  
    CASE WHEN Acknowledged = 1 THEN 'Acknowledged' WHEN Acknowledged = 0 THEN 'Not Acknowledged' WHEN  Acknowledged = 2 THEN 'Success'                  
      WHEN  Acknowledged = 3 THEN 'Upgrade Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect'   WHEN  Acknowledged = 5 THEN 'No Communication'  
      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'      
      ELSE '' END AS AckStatus,                  
    'N/A' as Address,@Distance as Units,'' as Direction ,/*null as mapitFunction,*/'setValue('' '')' as jsFunction, NULL as IgnitionStatus,
	NULL as StreetAddress, NULL as IsDefaultAlarm,null as isMapIT ,va.vehicleid,vt.VehicleTypeName , isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo  ,
	NULL,NULL,NULL,NULL,'-','-','-','-','-','-','-','-','-','-','-','-','-'  ,
	(CASE WHEN DATEDIFF(HH,B.LastStatusDateTime,GETDATE())> 24 THEN 'Offline' ELSE 'Online' END) as [status]  ,   0 as isAvail       
    FROM rvlfMsgOutHst OH inner join rvlfBoxId b on oh.BoxId=b.BoxId                 
    INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID 
	INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID                  
    INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId  
	INNER JOIN rvlfMAKDevices MD on MD.BoxId=oH.BoxId   
	LEFT JOIN rvlfVehicleType vt on v.VehicleTypeId=vt.VehicleTypeId                
    WHERE  SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)                  
    AND VA.VehicleID = @VehicleID and CT.OperationTypeId IN (select OperationTypeID from @OperationTypeID)
) as a --ORDER BY Timestamp desc, MessageInID DESC 
End 
  
	Select * from @tmpHistory order by Timestamp desc, MessageInID desc       

Select null  as PlayBackLatLong        
              
                  
End 


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng2_VXL]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RVLT_SP_GetLatLng2_VXL]    
(                  
 @vehicleId varchar(50)=null,                  
 @startdate as datetime =null,
 @enddate datetime =null,
 @interval as int=2000,                  
 @orderby varchar(10)='desc',                  
 @bigQueryingUser bigint = null,                  
 @bitIsMDTMsg bit=0 ,                
 @bitIsMessage bit = 0,          
 @bigLastHours int = null ,                  
 @controller varchar(50)=null,
 @bigCustomerId varchar(100)=null
)
as
/***************************************************************************************************************************/
--2013-01-30 11:12:17.890              
-- Name  : RVLT_SP_GetLatLng2_VXL 27,'2017-12-15 8:10:00 aM','2017-12-15 11:30:00 pM',2000,'desc',453 ,0,0,null,'TR-A6' 
-- Description : To get the messages that needs to be shown in the grid                  
-- Author  : T. Sathish Kumar                  
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
/***************************************************************************************************************************/
Begin                  
	DECLARE @Lang varchar(50),  @LangSetting varchar(20)                               
	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 
	DECLARE @OperationTypeID table (OperationTypeID bigint) 
    DECLARE @controllerType tinyint= (select VehicleTypeId from rvlfVehicle where VehicleId=@vehicleId)
	               
    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)  ,
			@Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings                
    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    
	inner join rvlfOrganization o on u.OrganizationId = o.OrganizationId                               
                      
	--Get the operation id of priviledged user---   	
	INSERT INTO @OperationTypeID  
	SELECT OperationTypeID FROM rvlfUserGroupSecurity s                   
     WHERE s.ModuleId in(22,26) and s.UserGroupId IN (SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser)                   
                      
	-------------------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)  	            
    -----------------------------------------------------------------------          
     
        
   SELECT *,[Timestamp] as DateTimeReceived,ROW_NUMBER() over (order by timestamp) as AutoID                     
   FROM( 
		Select DISTINCT(H.MessageInID),H.CustomProp,H.BoxId, MD.BoxID as DeviceID, 
			0 AS ValidGPS, 
			0.0 as Latitude, 0.0 as Longitude,   
			H.NearestLandMark as Distance,'-'  as Speed,0 as Heading, 
			[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
			--DateTimeReceived = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,H.OriginDateTime),                
 			MD.EquipmentName as VehicleDescription,    H.OriginDateTime,BoxMsgInTypeDesc as [Message],H.BoxMsgInTypeId as BoxMsgInTypeId , 
			H.OriginDateTime AS RoadsAPITime,    
			TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,H.OriginDateTime),   
			DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,H.OriginDateTime)) as [TimestampSort],                                 
			ct.BoxMsgInTypeName as MessageDetails, 0 as UserID,0 as Priority,NULL as Acknowledged, '' as AckStatus,
			H.StreetAddress AS Address, @Distance as Units,	 
			''  as StreetAddress,
			CASE WHEN (CT.Isviolation = 1 OR CT.IsDefaultAlarm = 1) THEN 1 ELSE 0 END AS IsDefaultAlarm,          
			MD.vehicleid ,vt.VehicleTypeName,isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo,					
		
	   isnull(h.Alarm,0) as Alarm,
	case when H.BoxMsgInTypeId in (8) then 1 else 0 end as Showdetails,0 AS ControllerPositionId,'' AS ControllerName,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T1=',';'),'') AS T1,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';'),'') AS T2,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';'),'') AS T3,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T4=',';'),'') AS T4,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T5=',';'),'') AS T5,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(replace(H.CustomProp,'DPp1','DPp11'), 'P1=',';'),'0') AS P1,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P2=',';'),'') AS P2,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P3=',';'),'') AS P3,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P4=',';'),'') AS P4,
	--ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P5=',';'),'') AS P5,
	ISNULL(MS.P5,'0') AS P5,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'VR1=',';'),'') AS VR,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'VY1=',';'),'') AS VY,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'VB1=',';'),'') AS VB,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'CR1=',';'),'') AS CR,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'CY1=',';'),'') AS CY,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'CB1=',';'),'') AS CB,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'WH1=',';'),'') AS WH,
	case when isnull(H.odometer,'')='0' then '' else isnull(H.odometer,'') end AS WH1_1,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PF1=',';'),'') AS PF,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';'),'') AS PO,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'VR1=',';'),'') AS VR2,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'VY1=',';'),'') AS VY2,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'VB1=',';'),'') AS VB2,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'CR1=',';'),'') AS CR2,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'CY1=',';'),'') AS CY2,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'CB1=',';'),'') AS CB2,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'WH2=',';'),'') AS WH2,
	case when isnull(h.duration,'')='0' then '' else isnull(h.duration,'') end AS WH2_1,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PF1=',';'),'') AS PF2,
	ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';'),'') AS PO2,MD.EConsumptionType,
	DPs= ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPs=',';'),'') ,
	DPp= ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp=',';'),''),
	DPp1=  ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp1=',';'),'')  ,isnull(MD.VFantype,0) as VFantype
	,isnull(MS.CR3,0) as CR3,isnull(MS.CY3,0) as CY3,isnull(MS.CB3,0) as CB3,isnull(MS.CR3_R ,0) as CR3_R
	,isnull(MS.WH3,0) as WH3,isnull(MS.PF3,0) as PF3,isnull(MS.PO3,0) as PO3,isnull(MS.CR4,0) as CR4
	,isnull(MS.CY4,0) as CY4,isnull(MS.CB4,0) as CB4,isnull(MS.CR4_R ,0) as CR4_R,isnull(MS.WH4,0) as WH4
	,isnull(MS.PF4,0) as PF4,isnull(MS.PO4,0) as PO4,isnull(MS.CR5,0) as CR5,isnull(MS.CY5,0) as CY5
	,isnull(MS.CB5,0) as CB5,isnull(MS.CR5_R ,0) as CR5_R,isnull(MS.WH5,0) as WH5,isnull(MS.PF5,0) as PF5
	,isnull(MS.PO5,0) as PO5,isnull(MS.CY3_R ,0) as CY3_R,isnull(MS.CB3_R ,0) as CB3_R,isnull(MS.CY4_R ,0) as CY4_R
	,isnull(MS.CB4_R ,0) as CB4_R,isnull(MS.CY5_R ,0) as CY5_R,isnull(MS.CB5_R ,0) as CB5_R,isnull(MP.CR6,0) as CR6
	,isnull(MP.CY6,0) as CY6,isnull(MP.CB6,0) as CB6,isnull(MP.CR6_R ,0) as CR6_R,isnull(MP.WH6,0) as WH6
	,isnull(MP.PF6,0) as PF6,isnull(MP.PO6,0) as PO6,isnull(MP.P6,0) as P6,isnull(MP.P6_R,0) as P6_R
	,isnull(MP.CR7,0) as CR7,isnull(MP.CY7,0) as CY7,isnull(MP.CB7,0) as CB7,isnull(MP.CR7_R ,0) as CR7_R
	,isnull(MP.WH7,0) as WH7,isnull(MP.PF7,0) as PF7 ,isnull(MP.PO7,0) as PO7 ,isnull(MP.CR8,0) as CR8
	,isnull(MP.CY8,0) as CY8 ,isnull(MP.CB8,0) as CB8 ,isnull(MP.CR8_R ,0) as CR8_R ,isnull(MP.WH8,0) as WH8
	,isnull(MP.PF8,0) as PF8 ,isnull(MP.PO8,0) as PO8 ,isnull(MP.CR9,0) as CR9 ,isnull(MP.CY9,0) as CY9
	,isnull(MP.CB9,0) as CB9 ,isnull(MP.CR9_R ,0) as CR9_R ,isnull(MP.WH9,0) as WH9 ,isnull(MP.PF9,0) as PF9
	,isnull(MP.PO9,0) as PO9 ,isnull(MP.P7,0) as P7 ,isnull(MP.P7_R,0) as P7_R ,isnull(MP.CR10,0) as CR10
	,isnull(MP.CY10,0) as CY10 ,isnull(MP.CB10,0) as CB10 ,isnull(MP.CR10_R,0) as CR10_R ,isnull(MP.WH10,0) as WH10
	,isnull(MP.PF10,0) as PF10 ,isnull(MP.PO10,0) as PO10 ,isnull(MP.CR11,0) as CR11 ,isnull(MP.CY11,0) as CY11
	,isnull(MP.CB11,0) as CB11 ,isnull(MP.CR11_R,0) as CR11_R ,isnull(MP.WH11,0) as WH11 ,isnull(MP.PF11,0) as PF11
	,isnull(MP.PO11,0) as PO11 ,isnull(MP.CY6_R,0) as CY6_R ,isnull(MP.CB6_R,0) as CB6_R ,isnull(MP.CY7_R,0) as CY7_R
	,isnull(MP.CB7_R,0) as CB7_R ,isnull(MP.CY8_R,0) as CY8_R ,isnull(MP.CB8_R,0) as CB8_R ,isnull(MP.CY9_R,0) as CY9_R
	,isnull(MP.CB9_R,0) as CB9_R ,isnull(MP.CY10_R,0) as CY10_R ,isnull(MP.CB10_R,0) as CB10_R ,isnull(MP.CY11_R,0) as CY11_R
	,isnull(MP.CB11_R,0) as CB11_R ,isnull(MF.CR12,0) as CR12 ,isnull(MF.CY12,0) as CY12 ,isnull(MF.CB12,0) as CB12
	,isnull(MF.CR12_R,0) as CR12_R ,isnull(MF.WH12,0) as WH12 ,isnull(MF.PF12,0) as PF12 ,isnull(MF.PO12,0) as PO12
	,isnull(MF.P8,0) as P8 ,isnull(MF.P8_R,0) as P8_R ,isnull(MF.CR13,0) as CR13 ,isnull(MF.CY13,0) as CY13 ,isnull(MF.CB13,0) as CB13
	,isnull(MF.CR13_R,0) as CR13_R ,isnull(MF.WH13,0) as WH13 ,isnull(MF.PF13,0) as PF13 ,isnull(MF.PO13,0) as PO13
	,isnull(MF.CR14,0) as CR14 ,isnull(MF.CY14,0) as CY14 ,isnull(MF.CB14,0) as CB14 ,isnull(MF.CR14_R,0) as CR14_R
	,isnull(MF.WH14,0) as WH14 ,isnull(MF.PF14,0) as PF14 ,isnull(MF.PO14,0) as PO14 ,isnull(MF.P9,0) as P9
	,isnull(MF.P9_R,0) as P9_R ,isnull(MF.CR15,0) as CR15 ,isnull(MF.CY15,0) as CY15 ,isnull(MF.CB15,0) as CB15
	,isnull(MF.CR15_R,0) as CR15_R ,isnull(MF.WH15,0) as WH15 ,isnull(MF.PF15,0) as PF15 ,isnull(MF.PO15,0) as PO15
	,isnull(MF.CR16,0) as CR16 ,isnull(MF.CY16,0) as CY16 ,isnull(MF.CB16,0) as CB16 ,isnull(MF.CR16_R,0) as CR16_R
	,isnull(MF.WH16,0) as WH16 ,isnull(MF.PF16,0) as PF16 ,isnull(MF.PO16,0) as PO16 ,isnull(MF.P10,0) as P10
	,isnull(MF.P10_R ,0) as P10_R ,isnull(MF.CR17,0) as CR17 ,isnull(MF.CY17,0) as CY17 ,isnull(MF.CB17,0) as CB17
	,isnull(MF.CR17_R,0) as CR17_R ,isnull(MF.WH17,0) as WH17 ,isnull(MF.PF17,0) as PF17 ,isnull(MF.PO17,0) as PO17
	,isnull(MF.CR18,0) as CR18 ,isnull(MF.CY18,0) as CY18 ,isnull(MF.CB18,0) as CB18 ,isnull(MF.CR18_R,0) as CR18_R
	,isnull(MF.WH18,0) as WH18 ,isnull(MF.PF18,0) as PF18 ,isnull(MF.PO18,0) as PO18 ,isnull(MF.P11,0) as P11
	,isnull(MF.P11_R ,0) as P11_R ,isnull(MF.CR19,0) as CR19 ,isnull(MF.CY19,0) as CY19 ,isnull(MF.CB19,0) as CB19
	,isnull(MF.CR19_R,0) as CR19_R ,isnull(MF.WH19,0) as WH19 ,isnull(MF.PF19,0) as PF19 ,isnull(MF.PO19,0) as PO19
	,isnull(MF.CY12_R,0) as CY12_R ,isnull(MF.CB12_R,0) as CB12_R ,isnull(MF.CY13_R,0) as CY13_R ,isnull(MF.CB13_R,0) as CB13_R
	,isnull(MF.CY14_R,0) as CY14_R ,isnull(MF.CB14_R,0) as CB14_R ,isnull(MF.CY15_R,0) as CY15_R ,isnull(MF.CB15_R,0) as CB15_R
	,isnull(MF.CY16_R,0) as CY16_R ,isnull(MF.CB16_R,0) as CB16_R ,isnull(MF.CY17_R,0) as CY17_R ,isnull(MF.CB17_R,0) as CB17_R
	,isnull(MF.CY18_R,0) as CY18_R ,isnull(MF.CB18_R,0) as CB18_R ,isnull(MF.CY19_R,0) as CY19_R ,isnull(MF.CB19_R,0) as CB19_R
	,isnull(MS.WH3_EC,0) as WH3_EC ,isnull(MS.WH4_EC,0) as WH4_EC ,isnull(MS.WH5_EC,0) as WH5_EC ,isnull(MP.WH6_EC,0) as WH6_EC
	,isnull(MP.WH7_EC,0) as WH7_EC ,isnull(MP.WH8_EC,0) as WH8_EC ,isnull(MP.WH9_EC,0) as WH9_EC ,isnull(MP.WH10_EC,0) as WH10_EC
	,isnull(MP.WH11_EC,0) as WH11_EC ,isnull(MF.WH12_EC,0) as WH12_EC ,isnull(MF.WH13_EC,0) as WH13_EC ,isnull(MF.WH14_EC,0) as WH14_EC
	,isnull(MF.WH15_EC,0) as WH15_EC ,isnull(MF.WH16_EC,0) as WH16_EC ,isnull(MF.WH17_EC,0) as WH17_EC ,isnull(MF.WH18_EC,0) as WH18_EC
	,isnull(MF.WH19_EC,0) as WH19_EC --,CM.ControllerPositionId,CM.ControllerName
	FROM rvlfMsgInHst H                   
	left join rvlfMsgInHst_Secondary MS on H.MessageInID=MS.MessageInID
	left join rvlfMsgInHst_Primary MP on H.MessageInID=MP.MessageInID
	left join rvlfMsgInHst_FibreCompactor MF on H.MessageInID=MF.MessageInID
	--left JOIN rvlfMsgInHstParam_PR P on h.MessageInID=p.Messageinid
	--INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId                     
	INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId                      
	--INNER JOIN rvlfVehicle V on V.VehicleID = VA.VehicleID        
	INNER JOIN rvlfMAKDevices MD on MD.BoxId=H.BoxId 
 	--inner join adrControllerMaster CM on h.boxid=CM.EquipmentId and h.ControllerID= CM.ControllerPositionId	and h.DCSIM=cm.DCSIMId
	--left join rvlfAlarm a on h.MessageInID=a.MessageInID  
	INNER JOIN rvlfVehicleType vt on MD.SubTypeId=vt.VehicleTypeId	              
	WHERE  H.OriginDateTime BETWEEN CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109) 
	AND ((@bigCustomerId IS NULL OR @bigCustomerId='' or @bigCustomerId='0') OR MD.CustomerId = @bigCustomerId )                                      
	and  MD.VehicleId = @VehicleID and MD.IsDelete=0--and  cm.IsDeleted=0 and
	--(@controller is null or @controller='' or @controller='ALL' or  cm.ControllerName=@controller)
	--and CT.OperationTypeID IN (select OperationTypeID from @OperationTypeID) AND CommInfo1 IS NOT NULL  and H.BoxMsgInTypeId in (1,7,24,15,14)                
   
--UNION ALL              
--   /************-------------------------------***** Get Commands details---------------------------------------******************/                  
--    SELECT NULL as MessageInID,null as Customprop,oh.BoxId ,MD.BoxID as DeviceID,3 as ValidGPS,0.0 as Latitude,0.0 as Longitude,'' as Distance,
--	NULL as Speed, 0 as Heading,[Timestamp] = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime),        
--	--SentDateTime = dbo.rvlf_fn_DayLightSavings_Date(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,SentDateTime), 
--    Md.EquipmentName as  VehicleDescription,'' as origindatetime,'Command' as Message, OH.BoxCmdOutTypeId as BoxMsgInTypeId,
--	--CONVERT(VARCHAR(10), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 103) + ' '  + convert(VARCHAR(8), DATEADD(MINUTE,@MinsToBeAdded,DATEADD(HOUR,@HoursToBeAdded,SentDateTime)), 14) AS RoadsAPITime,   
--	                  SentDateTime AS RoadsAPITime,
--    TimestampDisp = dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,SentDateTime), 
--       DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,SentDateTime)) as [TimestampSort],
--    --CASE WHEN OH.BoxCmdOutTypeId = 39 OR OH.BoxCmdOutTypeId = 4 THEN dbo.rvlf_fn_GetCmdMsgDetails(OH.CustomProp + ',', OH.BoxCmdOutTypeId, VA.BoxID) ELSE BoxcmdTypeDesc END as MessageDetails,
--	BoxcmdTypeDesc as MessageDetails,
--	 OH.UserId,Priority, 
--    /**************** Changed the Acknowledgement to be return based on the value ************/                  
--    CASE WHEN Acknowledged = 1 THEN 'True' WHEN Acknowledged = 0 THEN 'False' WHEN  Acknowledged = 2 THEN 'Success'                  
--      WHEN  Acknowledged = 3 THEN 'Update Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect' WHEN  Acknowledged = 5 THEN 'No Communication'                  
--      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'                  
--      ELSE 'Nothing' END AS Acknowledged,                  
--    CASE WHEN Acknowledged = 1 THEN 'Acknowledged' WHEN Acknowledged = 0 THEN 'Not Acknowledged' WHEN  Acknowledged = 2 THEN 'Success'                  
--      WHEN  Acknowledged = 3 THEN 'Upgrade Failed' WHEN  Acknowledged = 4 THEN 'CRC Incorrect'   WHEN  Acknowledged = 5 THEN 'No Communication'  
--      WHEN  Acknowledged = 6 THEN 'Aborted' WHEN  Acknowledged IS NULL and OH.BoxCmdOutTypeId = 22 THEN  'Under Processing'      
--      ELSE '' END AS AckStatus,                 
--    'N/A' as Address,@Distance as Units,--'' as Direction ,/*null as mapitFunction,*/'setValue('' '')' as jsFunction, NULL as IgnitionStatus,
--	NULL as StreetAddress, NULL as IsDefaultAlarm--,null as isMapIT
--	 ,MD.VehicleId,vt.VehicleTypeName , isnull(vt.VehicleTypeId,0) as VehicleTypeId, MD.EquipmentSrNo  
--	,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
--	,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,NULL,NULL,null,0,0,null,null,
--	NULL AS T1,NULL AS T2,NULL AS T3,NULL AS P1,NULL AS P2,NULL AS P3,NULL AS P4,NULL AS P5,NULL AS VR,NULL AS VY,NULL AS VB,NULL AS CR,NULL AS CY,
--	NULL AS CB,NULL AS WH,NULL AS PF,NULL AS PO,NULL AS VR2,NULL AS VY2,NULL AS VB2,NULL AS CR2,NULL AS CY2,
--	NULL AS CB2,NULL AS WH2,NULL AS PF2,NULL AS PO2
--    FROM rvlfMsgOutHst OH                  
--    --INNER JOIN rvlfVehicleAssignment VA on VA.BoxID = OH.BoxID 
--	--INNER JOIN rvlfVehicle V on V.VehicleID = VA.vehicleID                  
--    INNER JOIN rvlfBoxCmdOutType CT on CT.BoxCmdOutTypeId = OH.BoxCmdOutTypeId  
--	INNER JOIN rvlfMAKDevices MD on MD.BoxId=oH.BoxId
--	--inner join adrControllerMaster CM on OH.boxid=CM.EquipmentId and OH.ControllerID= CM.ControllerPositionId	   
--	LEFT JOIN rvlfVehicleType vt on MD.SubTypeId=vt.VehicleTypeId                
--    WHERE  SentDateTime Between CONVERT(varchar(35),@startdate,109) and CONVERT(varchar(35),@enddate,109)                  
--    AND MD.VehicleID = @VehicleID and CT.OperationTypeId IN (select OperationTypeID from @OperationTypeID)
) as a ORDER BY RoadsAPITime desc, MessageInID DESC 


SELECT DISTINCT A.*
  from (                            
  select ih.MessageInID,md.EquipmentName,IH.BoxID as 'EquipmentID',
  MD.CustomerName as CustomerName,CASE WHEN IH.BoxMsgInTypeId = 28 
OR IH.BoxMsgInTypeId = 73 OR IH.BoxMsgInTypeId = 94 OR IH.BoxMsgInTypeId = 98 or IH.BoxMsgInTypeId=56  THEN m.BoxMsgInTypeDesc
		 WHEN IH.BoxMsgInTypeId in (4,7,13,24) then m.BoxMsgInTypeName 
         ELSE dbo.rvlf_fn_GetAlarmDetails_Optimzd( IH.customprop,IH.BoxMsgInTypeID, IH.BoxId, IH.MessageInID, IH.OriginDateTime,'LanguageEn' ) END  
		 as MessageDetails, OriginDateTime= dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,IH.OriginDateTime),
		  ReceivedDateTime= dbo.rvlf_fn_DayLightSavings(@startdate,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,IH.DateTimeReceived),
 IH.BoxMsgInTypeId   as MessageID,md.EquipmentName as VehicleDescription, 
		 Interlock=SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),1,1),
		 AutoManual=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),2,1)=1 then 'Auto' else 'Manual' end,
		 MotorofCentrifugalFan=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),3,1)=1 then 'Not Tripped' else 'Tripped' end ,
		 MotorofCentrifugalFan2=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),4,1) =1 then 'Not Tripped' else 'Tripped' end ,
		 SecondaryNozzleGearMotor=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),5,1)=1 then 'Not Tripped' else 'Tripped' end,
		 SecondaryDustSuctionFanMotor=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),6,1)=1 then 'Running' else 'Stalled' end ,
		 SecondaryDustCompactorGearMotor=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),7,1) =1 then 'Not Tripped' else 'Tripped' end,
		 Primary1DiscGearMotor=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),8,1)=1 then 'Not Tripped' else 'Tripped' end,
		 Primary1SuctionFanMotor=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),9,1) =1 then 'Not Tripped' else 'Tripped' end,
		 Primary1FibreCompactorGearMotor=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),10,1)=1 then 'Not Tripped' else 'Tripped' end,
		 Primary2DiscGearMotor=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),11,1)=1 then 'Not Tripped' else 'Tripped' end,
		 Primary2SuctionFanMotor=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),12,1) =1 then 'Not Tripped' else 'Tripped' end,
		 Primary2FibreCompactorGearMotor=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),13,1)=1 then 'Not Tripped' else 'Tripped' end,
		 FibreCompactorMotor_1=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),14,1)=1 then 'Not Tripped' else 'Tripped' end,
		 VentilatorFanMotor_1=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),15,1)=1 then 'Not Tripped' else 'Tripped' end,
		 FibreCompactorMotor_2=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),16,1)=1 then 'Not Tripped' else 'Tripped' end,
		 VentilatorFanMotor_2=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),17,1)=1 then 'Not Tripped' else 'Tripped' end,
		 FibreCompactorMotor_3=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),18,1)=1 then 'Not Tripped' else 'Tripped' end,
		 VentilatorFanMotor_3=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),19,1)=1 then 'Not Tripped' else 'Tripped' end,
		 FibreCompactorMotor_4=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),20,1)=1 then 'Not Tripped' else 'Tripped' end,
		 VentilatorFanMotor_4=case when SUBSTRING(dbo.rvlf_fn_GetParamValueWithIndex(CustomProp,'Input=',';'),21,1)=1 then 'Not Tripped' else 'Tripped' end,


		 isnull(MD.VFantype,0) as VFantype
   from rvlfMsgInHst IH    
   inner join rvlfBoxId B on IH.BoxId=b.BoxId                         
   --INNER JOIN rvlfVehicleAssignment va ON IH.BoxId = va.BoxId                            
   --INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId                            
   INNER JOIN rvlfBoxSettings s on IH.BoxId= s.BoxId                            
   INNER JOIN rvlfBoxMsgInType m ON IH.BoxMsgInTypeId = m.BoxMsgInTypeId                            
   INNER JOIN rvlfBoxProtocolType pt ON IH.BoxProtocolTypeId = pt.BoxProtocolTypeId                            
   --LEFT OUTER JOIN rvlfLandmark fm ON IH.LandMarkID = fm.LandmarkID                             
   --INNER JOIN rvlfCommMode cm ON s.CommModeId = cm.CommModeId                           
   inner join rvlfMAKDevices MD on MD.BoxId=IH.BoxId                   
 WHERE  (IH.OriginDateTime BETWEEN @startdate and @enddate)
	AND ((@bigCustomerId IS NULL OR @bigCustomerId='' or @bigCustomerId='0') OR MD.CustomerId = @bigCustomerId )                                      
	and  MD.VehicleId = @VehicleID and MD.IsDelete=0 and IH.BoxMsgInTypeId=8 ) A         
	order by a.OriginDateTime desc

	 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
   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 

End 
GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng3]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RVLT_SP_GetLatLng3]
(
	@vehicleId varchar(50),
	@startdate as datetime,
	@enddate datetime, 
	@interval as int,
	@orderby varchar(10),
	@bigQueryingUser bigint = 0
)
As
/******************************************************************************/
--	Name		:	RVLT_SP_GetLatLng3
--	Description	:	To gets the messages that needs to be plotted in the Map.
--	Author		:	T. Sathish Kumar
--	Company		:	Angler Technologies
--	History		:	<<Date(dd-MON-yyyy)>> Initial Reason
--				:	11-Dec-2009	MJJC	Changed to show only the message for which the user has the rights
--				:	19-Dec-2009 MJJC	Included the ignition status by checkign the trip details
--				:	08-Jan-2010 LK		To retrieve address, landmark separately.
--				:	08-Jan-2010 MJJC	To get the fuel level indication in the ignition status.
--				:	10-Jan-2010 MJJC	To get the fuel and message details cor current postion indicator too.
--				:	11-Jan-2010 MJJC	To get the message details from the function itself
--				:	25-Jan-2010 MJJC	To update the alarm details function parameters
--				:	30-Jan-2010 MJJC	To check the Sensor off with duration packet
--              :	22-Apr-2010 LK	    To load the different icon for Violations & Alarms
--				:	26-Apr-2010 MJJC	Done the related change for shoing speed with violation
--				:	26-July-2010 VN	 To get the speed with duration without speed
/******************************************************************************/
Begin
	------- Included by Kumuthini on 16-July-09 ---------------------
	DECLARE @HoursToBeAdded INT = 0
	DECLARE @MinsToBeAdded INT = 0
	DECLARE @Distance varchar(20)
	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
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser

	--------------------------------
	
	-------------------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))
	---------------------------------------------------------------------------------------------------------
	DECLARE @intTotalRecords int
	SELECT @intTotalRecords = COUNT(*) 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  
		LEFT OUTER join rvlfTripDetails t ON h.MessageInID = t.StartMessageInID
		LEFT OUTER JOIN rvlfTripDetails d ON h.MessageInID = d.EndMessageInID
    where VA.VehicleId = @VehicleID and OriginDateTime between 
    CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109)
    and 
		CT.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s 
			WHERE s.ModuleId = 26 and s.UserGroupId IN 
			(SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))
    and H.ValidGps=0 
    
    IF @intTotalRecords < @interval OR @interval = 30
		BEGIN
			select H.MessageInID, VA.BoxID as DeviceID, ValidGPS, 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 =51 THEN '-' ELSE CAST( CAST(Speed  * @ConversionFactor as int) as varchar(3)) END  as Speed, 
			CASE WHEN H.Speed = 0 OR H.ValidGps > 0 THEN -1 ELSE Heading END as Heading,
			 DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,OriginDateTime)) as [Timestamp],
			VehicleDescription, BoxMsgInTypeName as Message, H.BoxMsgInTypeId as BoxMsgInTypeId ,
				CASE WHEN H.BoxMsgInTypeId = 51 THEN
					'Speed Violated for ' 
					--+CAST(CAST(Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @Distance 
					+' (' + dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'
				ELSE 
					dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId , H.MessageInID, H.OriginDateTime) END
				as MessageDetails,	
						0 as UserID,0 as Priority,NULL as Acknowledged, CASE WHEN (H.LandMarkID IS NULL or H.LandMarkID = 0) THEN
						 Replace(ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''') 
						ELSE L.LandmarkName END as Address, 
						Replace( ISNULL(H.StreetAddress,'Address is not resolved'),'''','\''')  AS StreetAddress,
						ISNULL(CASE WHEN (L.LandMarkID IS NULL OR H.LandMarkID = 0) THEN '-' ELSE L.LandmarkName END,'-')
						AS Landmark,
						@Distance as Units,
						CASE 
						WHEN H.ValidGps > 1 OR H.BoxMsgInTypeId IN (9, 14,15,16,17,24) then '-'
						WHEN H.Heading between 335 and 360 THEN 'N' 
						 WHEN H.Heading between 0 and 25 THEN 'N' 
						WHEN H.Heading between 25 and 65 THEN 'NE' 
						WHEN H.Heading between 65 and 115 THEN 'E' 
						WHEN H.Heading between 115 and 155 THEN 'SE' 
						WHEN H.Heading between 155 and 210 THEN 'S' 
						WHEN H.Heading between 210 and 245 THEN 'SW' 
						WHEN H.Heading between 245 and 300 THEN 'W' 
						WHEN H.Heading between 300 and 335 THEN 'NW' END as Direction,
						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 = 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 ,
						ISNULL(t.TripId,0) as IgnitionOn, ISNULL(d.TripId,0) as IgnitionOff,L.LandmarkID,
				L.LandmarkName as LandmarkName, L.Latitude as LandmarkLatitude, L.Longitude as LandmarkLongitude, L.Radius as LandmarkRadius, L.StreetAddress As LandMarkAddress
			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  
				LEFT OUTER join rvlfTripDetails t ON h.MessageInID = t.StartMessageInID
				LEFT OUTER JOIN rvlfTripDetails d ON h.MessageInID = d.EndMessageInID
			where VA.VehicleId = @VehicleID and OriginDateTime between 
			CONVERT(varchar(35),@startdate,109)  and CONVERT(varchar(35),@enddate,109)
			and 
				CT.OperationTypeID IN (SELECT OperationTypeID FROM rvlfUserGroupSecurity s 
					WHERE s.ModuleId = 26 and s.UserGroupId IN 
					(SELECT UserGroupId FROM rvlfUserGroupAssignment WHERE UserId = @bigQueryingUser))
			and H.ValidGps=0 
			ORDER BY H.OriginDateTime,  H.MessageInID
		    
			-- Get the Latest value for Device
			select B.BoxId,LastLatitude,LastLongitude,
				CASE WHEN H.BoxMsgInTypeId =51 THEN '' ELSE 
					CAST(CAST(LastSpeed  * @ConversionFactor as int) as varchar(10)) END as LastSpeed,
				CASE WHEN LastSpeed = 0 OR LastCommunicatedDateTime<> LastStatusDateTime 
				THEN -1 ELSE B.Heading END as Heading,
				Replace(ISNULL( LastStreetAddress, 'Address is not resolved'),'''','\''')  as LastStreetAddress,
				DateAdd(n,@MinsToBeAdded,DateAdd(hh,@HoursToBeAdded,LastStatusDateTime)) as LastStatusDateTime,
				B.NearestLandmark, V.VehicleId,V.VehicleDescription,
				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 = 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,
				@Distance as Units,
				CASE WHEN H.BoxMsgInTypeId = 51 THEN
					'Speed Violated for ' 
					--+CAST(CAST(Speed  * @ConversionFactor as int) AS varchar(3))+' ' + @Distance 
					+' (' + dbo.rvlf_fn_GetDuration(H.CustomProp,H.BoxMsgInTypeId,H.BoxID,1)+')'
				ELSE 
					dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId, H.MessageInID, H.OriginDateTime )--CT.BoxMsgInTypeDesc 
				END 
				as MessageDetails,
				ISNULL(CASE WHEN (L.LandMarkID IS NULL OR H.LandMarkID = 0) THEN '-' ELSE L.LandmarkName END,'-') AS Landmark,
				L.LandmarkName as LandmarkName, L.Latitude as LandmarkLatitude, L.Longitude as LandmarkLongitude, L.Radius as LandmarkRadius, L.StreetAddress As LandMarkAddress
			from rvlfBoxId B INNER JOIN rvlfVehicleAssignment VA on B.BoxId = VA.BoxId
				INNER JOIN rvlfMsgInHst H ON B.MessageInId = H.MessageInID
				INNER JOIN rvlfVehicle V on V.VehicleId = VA.VehicleId
				LEFT OUTER join rvlfTripDetails t ON h.MessageInID = t.StartMessageInID
				LEFT OUTER JOIN rvlfTripDetails d ON h.MessageInID = d.EndMessageInID
				INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId
				LEFT OUTER JOIN rvlfLandmark L ON h.LandMarkID = L.LandmarkID 
			where VA.VehicleId = @vehicleId
		END
	ELSE
		BEGIN
			SELECT 'Exceeds Threshold' as ResultValue
		END
END
-- exec [RVLT_SP_GetLatLng3] '6','2009-06-05 10:00:00','2009-12-26 21:40:00',300,'asc',3
-- exec RVLT_SP_GetLatLng3 '9','2009-11-14 18:50:25.000', '2009-12-25 18:50:25.000',300,'asc', 3


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLngByTimeDiff]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_GetLatLngByTimeDiff](@timeint int)
AS
BEGIN
DECLARE @sec varchar(10),@endsec varchar(10)
SET @sec = (Select Datepart(ss,min(timestamp)) from rvlt_tbl_gpsdata)
--Select @sec
SET @endsec = @sec + @timeint
-- SELeCT @endsec
DECLARE @query varchar(500)
SET @query = 'select * from rvlt_tbl_gpsdata where datepart(ss,timestamp) like ''' + @sec + ''' or datepart(ss,timestamp) like ''' + @endsec + ''' '
exec(@query)
END


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetMonitorData]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[RVLT_SP_GetMonitorData]
	-- Add the parameters for the stored procedure here
	@BoxID nvarchar(100) =NULL,
	@bigQueryingUser bigint =NULL,
	@SiteId bigint = NULL,
	@bigOrganizationID bigint =NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	

  IF @bigOrganizationID Is null              
    set @bigOrganizationID=(select organizationID from rvlfUser where UserId=@bigQueryingUser)
     --DECLARE THE VARIABLES FOR GET THE TIMEZONE DETAILS                                    
  DECLARE @HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@SpeedUnit varchar(50),@DefaultDateFormat INT = 0,@ConversionFactor numeric (10,2) =  1.0                                            
  DECLARE @Lang varchar(50),  @LangSetting varchar(20)                                     
  SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,                               
  @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   

 /*************************************** Get Dashboard Details *****************************************************/

   SELECT B.MessageInID, MD.VehicleID, B.BoxID as DeviceID, Md.EquipmentName as VehicleDescription, VT.VehicleTypeName AS EquipmentTypeName,   VT.VehicleTypeId,ISNULL((SELECT FleetName FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From 
 rvlfFleetVehicles Where VehicleId = MD.VehicleId and FleetId <> 176)), 'Site Not Assigned') as SiteName,
 OriginDateTime = dbo.rvlf_fn_DayLightSavings  (B.LastStatusDateTime,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,T.OriginDateTime),                             
	FORMAT(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,B.LastStatusDateTime)),'dd-MMM-yyyy hh:mm tt')as OriginDateTimeSort,
	T.BoxMsgInTypeId, 
		CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN 
				'1' 
			 ELSE 
				'0'
			END AS [Status], 
	ISNULL(T.Gen_Freq,'0')		AS Gen_Freq,
	ISNULL(T.Gen_LNVolt,'0')	AS Gen_LNVolt,
	ISNULL(T.Gen_LLVolt,'0')	AS Gen_LLVolt ,
    cast(ISNULL(T.Tot_Watts,'0') as decimal(18,2)) AS Tot_Watts,
	cast(ISNULL(T.Tot_VA,'0') as decimal(18,2)) AS Tot_VA,
	cast(ISNULL(T.Tot_VAr,'0')as decimal(18,2)) AS Tot_VAr,
	ISNULL(T.Gen_KWh,'0')		AS Gen_KWh,ISNULL(T.Gen_KVArh,'0')AS Gen_KVArh,ISNULL(T.Gen_KVAh,'0')AS Gen_KVAh,
	ISNULL(T.Gen_L1_PF,'0')		AS Gen_L1_PF,
    ISNULL(T.Gen_L1_VAr,'0')	AS Gen_L1_VAr,
    ISNULL(T.Gen_L1_VA,'0')		AS Gen_L1_VA,
    ISNULL(T.Gen_L1_Watts,'0')	AS Gen_L1_Watts,
    ISNULL(T.Gen_L1_Current,'0') AS Gen_L1_Current,
    ISNULL(T.Gen_L2_PF,'0')		 AS Gen_L2_PF,
    ISNULL(T.Gen_L2_VAr,'0')	AS Gen_L2_VAr,
    ISNULL(T.Gen_L2_VA,'0') AS Gen_L2_VA,
    ISNULL(T.Gen_L2_Watts,'0') AS Gen_L2_Watts,
    ISNULL(T.Gen_L2_Current,'0') AS Gen_L2_Current,
    ISNULL(T.Gen_L3_PF,'0') AS Gen_L3_PF,
    ISNULL(T.Gen_L3_VAr,'0') AS Gen_L3_VAr,
    ISNULL(T.Gen_L3_VA,'0') AS Gen_L3_VA,
    ISNULL(T.Gen_L3_Watts,'0') AS Gen_L3_Watts,
    ISNULL(T.Gen_L3_Current,'0') AS Gen_L3_Current,		
	ISNULL(T.Batt_Volt,'0') AS Batt_Volt,ISNULL(T.Chrg_Alternator,'0') AS Chrg_Alternator,ISNULL(T.Coolant_Temp,'0') AS Coolant_Temp,
	ISNULL(T.EngineSpeed,'0') AS EngineSpeed,ISNULL(T.Oil_Temp,'0') AS Oil_Temp,ISNULL(T.Oil_Pressure,'0') AS Oil_Pressure,
	ISNULL(T.FuelLevel,'0') AS FuelLevel, 
	case when (convert(int, convert(int, isnull(Engine_RunTime,0) /60 / 60))>=10) then 
			convert(varchar(9), convert(int, convert(int, isnull(Engine_RunTime,0) /60 / 60)))
		else
			right('00' +convert(varchar(9), convert(int, convert(int, isnull(Engine_RunTime,0) /60 / 60))),2)
		end
		+ ':' +
        right('00' + convert(varchar(2), convert(int, convert(int, (isnull(Engine_RunTime,0) / 60) - (convert(int, isnull(Engine_RunTime,0) /60 / 60) * 60 )))), 2) + ':' +
        right('00' + convert(varchar(6), isnull(Engine_RunTime,0) % 60), 2) as Engine_RunTime,
	--CONVERT(time(0), DATEADD(SECOND, Engine_RunTime, 0)) AS Engine_RunTime,		
    ISNULL(GEN_L1_N_VOLT,'0') AS GEN_L1_N_VOLT, 
    ISNULL(GEN_L2_N_VOLT,'0') AS GEN_L2_N_VOLT, 
    ISNULL(GEN_L3_N_VOLT,'0') AS GEN_L3_N_VOLT, 
    ISNULL(GEN_L1_L2_VOLT,'0') AS GEN_L1_L2_VOLT, 
    ISNULL(GEN_L2_L3_VOLT,'0') AS GEN_L2_L3_VOLT, 
    ISNULL(GEN_L1_L3_VOLT,'0') AS GEN_L1_L3_VOLT, 
    ISNULL(GENCURRENT_L1,'0') AS GENCURRENT_L1, 
    ISNULL(GENCURRENT_L2,'0') AS GENCURRENT_L2, 
    ISNULL(GENCURRENT_L3,'0') AS GENCURRENT_L3, 
    ISNULL(BatteryCharger_OP_Cur,'0') AS BatteryCharger_OP_Cur, 
	ISNULL(T3.S1_Tot_Watts,'0') AS S1_Tot_Watts,
    ISNULL(S1_Tot_VA,'0')AS S1_Tot_VA,
    ISNULL(S1_Tot_VAr,'0') AS S1_Tot_VAr,
    ISNULL(S1_KWh,'0') AS S1_KWh,
    ISNULL(S1_KVAh,'0') AS S1_KVAh,
    ISNULL(S1_KVArh,'0') AS S1_KVArh,
    ISNULL(S1_Freq,'0') AS S1_Freq,
	ISNULL(S1_LN_Volt,'0')AS S1_LN_Volt,
    ISNULL(S1_LL_Volt,'0') AS S1_LL_Volt,
    ISNULL(S1_AvgPF,'0') AS S1_AvgPF,
    ISNULL(S1_L1_PF,'0') AS S1_L1_PF,
    ISNULL(S1_L1_VAr,'0') AS S1_L1_VAr,
    ISNULL(S1_L1_VA,'0') AS S1_L1_VA,
    ISNULL(S1_L1_Watts,'0') AS S1_L1_Watts,
    ISNULL(S1_L1_Current,'0') AS S1_L1_Current,
    ISNULL(S1_L2_PF,'0') AS S1_L2_PF,
    ISNULL(S1_L2_VAr,'0') AS S1_L2_VAr,
    ISNULL(S1_L2_VA,'0') AS S1_L2_VA,
    ISNULL(S1_L2_Watts,'0') AS S1_L2_Watts,
    ISNULL(S1_L2_Current,'0') AS S1_L2_Current,
    ISNULL(S1_L3_PF,'0') AS S1_L3_PF,
    ISNULL(S1_L3_VAr,'0') AS S1_L3_VAr,
    ISNULL(S1_L3_VA,'0') AS S1_L3_VA,
    ISNULL(S1_L3_Watts,'0') AS S1_L3_Watts,
    ISNULL(S1_L3_Current,'0') AS S1_L3_Current,
    ISNULL(S2_Tot_Watts,'0') AS S2_Tot_Watts,
    ISNULL(S2_Tot_VA,'0') AS S2_Tot_VA,
    ISNULL(S2_Tot_VAr,'0') AS S2_Tot_VAr,
    ISNULL(S2_KWh,'0') AS S2_KWh,
    ISNULL(S2_KVAh,'0') AS S2_KVAh,
    ISNULL(S2_KVArh,'0') AS S2_KVArh,
    ISNULL(S2_Freq,'0') AS S2_Freq,	
    ISNULL(S2_LN_Volt,'0') As S2_LN_Volt,
    ISNULL(S2_LL_Volt,'0') AS S2_LL_Volt,
    ISNULL(S2_AvgPF,'0') AS S2_AvgPF,
    ISNULL(S2_L1_PF,'0') AS S2_L1_PF,
    ISNULL(S2_L1_VAr,'0') AS S2_L1_VAr,
    ISNULL(S2_L1_VA,'0') AS S2_L1_VA,
    ISNULL(S2_L1_Watts,'0') AS S2_L1_Watts,
    ---ISNULL(S2_L1_Current,'0') AS S2_L1_Current,
    ISNULL(S2_L2_PF,'0') AS S2_L2_PF,
    ISNULL(S2_L2_VAr,'0') AS S2_L2_VAr,
    ISNULL(S2_L2_VA,'0') AS S2_L2_VA,
    ISNULL(S2_L2_Watts,'0') AS S2_L2_Watts,
    --ISNULL(S2_L2_Current,'0') AS S2_L2_Current,
    ISNULL(S2_L3_PF,'0') AS S2_L3_PF,
    ISNULL(S2_L3_VAr,'0') AS S2_L3_VAr,
    ISNULL(S2_L3_VA,'0') AS S2_L3_VA,
    ISNULL(S2_L3_Watts,'0') AS S2_L3_Watts,
	CASE WHEN S2_L1_L2_Voltage IS NOT NULL OR S2_L1_L2_Voltage <> '0' THEN ISNULL(S1_L1_Current,'0') ELSE '0' END AS S2_L1_Current,
	CASE WHEN S2_L2_L3_Voltage IS NOT NULL OR S2_L2_L3_Voltage <> '0' THEN ISNULL(S1_L2_Current,'0') ELSE '0' END AS S2_L2_Current,
	CASE WHEN S2_L3_L1_Voltage IS NOT NULL OR S2_L3_L1_Voltage <> '0'THEN ISNULL(S1_L3_Current,'0') ELSE '0' END AS S2_L3_Current,
    --ISNULL(S2_L3_Current,'0') AS S2_L3_Current,
    ISNULL(Main_Gen_LNVolt,'0') AS Main_Gen_LNVolt,
	ISNULL(T3.Gen_LLVolt,'0') AS S1_S2LLVolt,
    ISNULL(S1_L1_N_Voltage,'0') AS S1_L1_N_Voltage,
    ISNULL(S1_L2_N_Voltage,'0') AS S1_L2_N_Voltage,
    ISNULL(S1_L3_N_Voltage,'0') AS S1_L3_N_Voltage,
    ISNULL(S1_L1_L2_Voltage,'0') AS S1_L1_L2_Voltage,
    ISNULL(S1_L2_L3_Voltage,'0') AS S1_L2_L3_Voltage,
    ISNULL(S1_L3_L1_Voltage,'0') AS S1_L3_L1_Voltage,
    ISNULL(S2_L1_N_Voltage,'0') AS S2_L1_N_Voltage,
    ISNULL(S2_L2_N_Voltage,'0') AS S2_L2_N_Voltage,
    ISNULL(S2_L3_N_Voltage,'0') AS S2_L3_N_Voltage,
    ISNULL(S2_L1_L2_Voltage,'0') AS S2_L1_L2_Voltage,
    ISNULL(S2_L2_L3_Voltage,'0') AS S2_L2_L3_Voltage,
    ISNULL(S2_L3_L1_Voltage,'0') AS S2_L3_L1_Voltage,
	isnull(Supervisor_State,'-') as Supervisor_State,
	isnull(Gen_Rating,'-')+' kw' as Gen_Rating,
	CASE WHEN VT.VehicleTypeId =1 THEN T.Digital_IP ELSE T3.Digital_IP END AS Digital_IP,
	CASE WHEN VT.VehicleTypeId =1 THEN T.Digital_OP ELSE T3.Digital_OP END AS Digital_OP,ISNULL(CustomerName,'-') AS GatewayId,
	CASE WHEN VT.VehicleTypeId =1 THEN 
	CASE WHEN T.Controller_Mode ='Stop'    THEN '0'  
	     WHEN T.Controller_Mode ='Auto'    THEN '1' 
		 WHEN T.Controller_Mode ='Manual'  THEN '2'   
		 WHEN T.Controller_Mode ='Start'  THEN '4' 
		 WHEN T.Controller_Mode ='Mute'  THEN '5'
		 END ELSE 
		  CASE WHEN S2_L1_Current='0.1' or S2_L1_Current='1' THEN '0'  -- 335 Device type Stop mode
		  WHEN S2_L2_Current='0.1' or S2_L2_Current='1' THEN '2' -- 335 Device type Manual mode
		  WHEN S2_L3_Current='0.1' or S2_L3_Current='1' THEN '1' -- 335 Device type Auto mode
		 ELSE '0'
		  END 
		 END AS CtrMode, ISNULL(SUBSTRING(T3.Digital_IP,10,1),'0') AS S1_Open,
		 CASE WHEN SUBSTRING(T3.Digital_IP,9,1)='1' OR SUBSTRING(T3.Digital_IP,8,1) ='1' THEN '1' ELSE '0' END AS S2_Open
  INTO #TempTable FROM rvlfMAKDevices MD 
	inner join rvlfVehicle V on md.VehicleId=v.VehicleId     
	left join rvlfParamRange PR on md.BoxId=pr.Boxid and pr.IsActive=1   
	--INNER JOIN rvlfFleetVehicles RFV ON MD.VehicleId = RFV.vehicleId
	INNER JOIN rvlfBoxID B ON B.BoxID = MD.BoxId                        
	--INNER JOIN rvlfMsgInHst h ON h.MessageInID = B.MessageInId 
	LEFT OUTER JOIN rvlfMsgInHst_Techno T ON T.MessageInID = B.MessageInID
	LEFT OUTER JOIN rvlfMsgInHst_Techno_355 T3 ON T3.MessageInID = B.MessageInId
	--INNER JOIN rvlfBoxMsgInType CT ON T.BoxMsgInTypeId = CT.BoxMsgInTypeId	
	LEFT OUTER JOIN rvlfVehicleType VT On MD.SubTypeId = VT.VehicleTypeId  
  WHERE  Md.OrganizationID=@bigOrganizationID                                   
  AND (@BoxID IS NULL or @BoxID = '' OR MD.BoxId= @BoxID) 	
  ORDER BY T.OriginDateTime  desc	
	
  SELECT * FROM #TempTable

DECLARE @Value varchar(50);
DECLARE @leng int=0; 
DECLARE @cnt int =0;
--DECLARE @DIO_tbl table(Sno int Identity(1,1), Digit_IP varchar(50),Digit_OP varchar(50))
Declare @Digit_IP Table(Sno int Identity(1,1),InputType varchar(10),InputDescription varchar(50),InputActiveStatus tinyint,InputState tinyint)
Declare @Digit_OP Table(Sno int Identity(1,1),OutputType varchar(10),OutputDescription varchar(50),OutputActiveStatus tinyint,OutputState tinyint)
Declare @DigitIP_Expension Table(Sno int Identity(1,1),InputType varchar(10),InputDescription varchar(50),InputActiveStatus tinyint,InputState tinyint)
DECLARE @vehType tinyint;

SELECT @leng= LEN(ISNULL(Digital_IP,'0000000000000000')), @Value=CASE WHEN [Status]='1' THEN ISNULL(Digital_IP,'0000000000000000') ELSE '0000000000000000' END, @vehType= VehicleTypeId FROM #TempTable

WHILE(@cnt < @leng)
BEGIN
 --Set @Result += SUBSTRING(@Value,(@leng-@cnt),1) +',' 
 IF(@vehType=1)
 BEGIN 
   INSERT INTO @Digit_IP(InputType,InputDescription,InputActiveStatus,InputState)
   SELECT InputType,InputDescription,SUBSTRING(@Value,(@cnt+1),1),SUBSTRING(@Value,(@cnt+1),1) 
   FROM rvlfDigitIP_7410 WHERE InputId=@cnt
 End
 ELSE
 BEGIN
   INSERT INTO @Digit_IP(InputType,InputDescription,InputActiveStatus,InputState)
   SELECT InputType,InputDescription,SUBSTRING(@Value,(@leng-@cnt),1),SUBSTRING(@Value,(@leng-@cnt),1) 
   FROM rvlfDigitip_335 WHERE InputId=@cnt and InputId NOT IN(9,10,11,12,13,14)

   INSERT INTO @DigitIP_Expension(InputType,InputDescription,InputActiveStatus,InputState)
   SELECT InputType,InputDescription,SUBSTRING(@Value,(@leng-@cnt),1),SUBSTRING(@Value,(@leng-@cnt),1) 
   FROM rvlfDigitip_335 WHERE InputId=@cnt and InputId IN(9,10,11,12,13,14)

 END
 SET @cnt=@cnt+1;
END

SET @cnt =0;
SET @leng=0; 

SELECT @leng= LEN(ISNuLL(Digital_OP,'0000000000000000')), @Value=CASE WHEN [Status]='1' THEN ISNuLL(Digital_OP,'0000000000000000') ELSE '0000000000000000' END , @vehType= VehicleTypeId FROM #TempTable

while(@cnt < @leng)
begin

  IF(@vehType=1)
  BEGIN
   --Set @Result += SUBSTRING(@Value,(@leng-@cnt),1) +',' 
   INSERT INTO @Digit_OP(OutputType,OutputDescription,OutputActiveStatus,OutputState)
   SELECT OutputType,OutputDescription,SUBSTRING(@Value,(@cnt+1),1),SUBSTRING(@Value,(@cnt+1),1) 
   FROM rvlfDigitOP_7410 WHERE OutputId=@cnt 
  END
  ELSE
  BEGIN
   --Set @Result += SUBSTRING(@Value,(@cnt),1) +',' 
    
    INSERT INTO @Digit_OP(OutputType,OutputDescription,OutputActiveStatus,OutputState)
   SELECT OutputType,OutputDescription,SUBSTRING(@Value,(@leng-@cnt),1),SUBSTRING(@Value,(@leng-@cnt),1) 
   FROM rvlfDigitOP_335 WHERE OutputId=@cnt  and OutputId IN( 5,6,7,8,9,10,11)

   update @Digit_OP set OutputActiveStatus= T.S2_L2_Current,OutputState= T.S2_L2_Current From #TempTable T where OutputType='f'
   update @Digit_OP set OutputActiveStatus= T.S2_L1_Current,OutputState= T.S2_L1_Current From #TempTable T where OutputType='h'
   update @Digit_OP set OutputActiveStatus= T.S1_L3_Current,OutputState= T.S1_L3_Current From #TempTable T where OutputType='i'

  END
  set @cnt=@cnt+1;

end


SELECT * FROM @Digit_IP

SELECT * FROM @Digit_OP  

SELECT * FROM @DigitIP_Expension

drop table #TempTable 	

END

GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetOrgStatistics]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[RVLT_SP_GetOrgStatistics]                              
(
	@bigOrganizationID bigint,
    @bigFleetID bigint = null,
	@dtStartDate datetime, 
	@dtEndDate datetime, 
	@bigQueryingUser bigint,
	@bigTopNos bigint
)                              
                              
as                              
Begin    
	DECLARE @HoursToBeAdded INT = 0
	DECLARE @MinsToBeAdded INT = 0
	DECLARE @ConversionFactor numeric (10,2) = 1.0
	DECLARE @CaptionPrefix varchar(10)

    SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,
		   @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END ,
		   @CaptionPrefix = CASE WHEN up.Distance = 0 THEN 'miles' ELSE 'kms' END
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser
    		   
		   print 'capiton'
		   print @CaptionPrefix
    print @bigQueryingUser
    print @CaptionPrefix
    
    IF @bigFleetID IS NULL
		SELECT @bigFleetID = FleetID FROM rvlfFleet where OrganizationId = @bigOrganizationID and IsDefault=1
    
/***************** Organization Statistics ***************/
	SELECT COUNT(*) as 'No of Vehicles' from rvlfVehicle where OrganizationId = @bigOrganizationID

	SELECT SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0 THEN 1 ELSE 0 END) as Moving,
		SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN 1 ELSE 0 END) as Idling,
		SUM(CASE WHEN SUBSTRING(LastSensorMask,6,1) =0 THEN 1 ELSE 0 END) as Parked FROM rvlfBoxId b
		INNER JOIN rvlfVehicleAssignment va ON b.BoxId = va.BoxId 
		INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
		WHERE v.OrganizationId = @bigOrganizationID

--/********************* Alarms ********************/
	SELECT top (@bigTopNos) 
			--SUM(CASE WHEN a.AlarmLevelId = 2 THEN 1 ELSE 0 END) as WarningAlarms,
			SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) as CriticalAlarms,
			 a.BoxID,v.VehicleDescription,
			 --SUBSTRING(v.VehicleDescription,1, 10) 
			--+ CASE WHEN LEN(v.VehicleDescription)>10 THEN '...' ELSE '' END 
			v.VehicleDescription  as VehicleName
		FROM rvlfAlarm a
			INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId
			INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
			INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId
		WHERE 
			(@bigOrganizationID IS NULL OR @bigOrganizationID = '' OR v.OrganizationId = @bigOrganizationID) AND
			(@bigFleetID IS NULL OR fv.FleetId = @bigFleetID OR @bigFleetID = '') AND 
			((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR (@dtStartDate = '' OR @dtEndDate = '') OR 
			  a.DateTimeCreated BETWEEN @dtStartDate AND @dtEndDate)
		GROUP BY a.BoxId, v.VehicleDescription
		HAVING
			 --SUM(CASE WHEN a.AlarmLevelId = 2 THEN 1 ELSE 0 END) > 0 AND
			  SUM(CASE WHEN a.AlarmLevelId = 3 THEN 1 ELSE 0 END) >0
		ORDER BY 
		--CASE WHEN 
		CriticalAlarms DESC
		
		--	/****************** Idling Vs Running *****************/
		
		SELECT top(@bigTopNos) h.BoxId,
			dbo.rvlf_fn_GetTimeFromSeconds(
				SUM(CAST(dbo.rvlf_fn_GetDuration(h.CustomProp,h.BoxMsgInTypeId, h.BoxId, 0)as int))) as IdlingTimeFormatted,
				SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp,BoxMsgInTypeID, h.BoxId, 0) as int)) / 60 as IdlingTime,
			v.VehicleDescription, 
			 --SUBSTRING(v.VehicleDescription,1, 10) 
			--+ CASE WHEN LEN(v.VehicleDescription)>10 THEN '...' ELSE '' END 
			v.VehicleDescription  as VehicleName
		FROM rvlfMsgInHst h 
			INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
			INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
			INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId AND fv.FleetId = @bigFleetID
		WHERE h.BoxMsgInTypeId = 9
			AND h.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate 
		GROUP BY h.BoxId, v.VehicleDescription
		HAVING SUM(CAST(dbo.rvlf_fn_GetDuration(CustomProp,BoxMsgInTypeID, h.BoxId, 0) as int) % 3600) / 60 > 0
		ORDER BY IdlingTime DESC
	--SELECT TOP (@bigTopNos) 
	
	--	CASE WHEN SUM(datediff(ss,t.startDate,t.EndDate)) = 0 THEN 0 ELSE
	--	CAST((SUM(t.IdlingDuration)*1.00 / SUM(datediff(ss,t.startDate,t.EndDate))*100) 
	--	as /*numeric(18,2)*/ int)END as IdlingPercentage, 
		
	--	dbo.rvlf_fn_GetTimeFromSeconds(SUM(t.IdlingDuration)) as IdlingDuration,
		
	--	100 - CASE WHEN SUM(datediff(ss,t.startDate,t.EndDate)) = 0 THEN 0 ELSE
	--	CAST((SUM(t.IdlingDuration)*1.00 / SUM(datediff(ss,t.startDate,t.EndDate))*100) 
	--	as /*numeric(18,2)*/int )END as RunnningPercentage,
		
	--	dbo.rvlf_fn_GetTimeFromSeconds(SUM(datediff(ss,t.startDate,t.EndDate)) - SUM(t.IdlingDuration)) as RunningTime,
		
	--	v.VehicleDescription, t.BoxId, 
	--	SUBSTRING(v.VehicleDescription,1, 10) 
	--		+ CASE WHEN LEN(v.VehicleDescription)>10 THEN '...' ELSE '' END as VehicleName
		
	--	from rvlfTripDetails t
	--	INNER JOIN rvlfVehicleAssignment va ON t.BoxId = va.BoxId
	--	INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
	--	INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId
	--	INNER JOIN rvlfFleet f ON fv.FleetId= f.FleetId
	--	INNER JOIN rvlfOrganization g ON f.OrganizationId = g.OrganizationId
	--	INNER JOIN rvlfMake m ON v.MakeId =m.MakeId
	--	INNER JOIN rvlfModel d ON v.ModelId = d.ModelId
	--	--INNER JOIN rvlfTimeZones tz ON v.TimeZone = tz.TimeZoneID
	--WHERE	
	--	( @bigFleetID IS NULL  OR f.FleetId = @bigFleetID) AND 
	--	((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR
	--	  t.StartDate BETWEEN @dtStartDate AND @dtEndDate)
	--GROUP BY t.BoxId,v.VehicleDescription
	--ORDER BY IdlingPercentage DESC 
	
	/**************** Speed Alerts *************/
	SELECT top (@bigTopNos) 
			SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END) as SpeedAlerts,
			 a.BoxID,v.VehicleDescription, -- SUBSTRING(v.VehicleDescription,1, 10) 
			--+ CASE WHEN LEN(v.VehicleDescription)>10 THEN '...' ELSE '' END 
			v.VehicleDescription  as VehicleName
		FROM rvlfMsgInHst  a
			INNER JOIN rvlfVehicleAssignment va ON a.BoxId = va.BoxId
			INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
			INNER JOIN rvlfFleetVehicles fv ON v.VehicleId = fv.VehicleId
		WHERE 
			(@bigOrganizationID IS NULL OR v.OrganizationId = @bigOrganizationID) AND
			(@bigFleetID IS NULL OR fv.FleetId = @bigFleetID) 
			AND 
			((@dtStartDate IS NULL OR @dtEndDate IS NULL) OR
			  a.OriginDateTime BETWEEN @dtStartDate AND @dtEndDate)
		GROUP BY a.BoxId, v.VehicleDescription
		HAVING SUM(CASE WHEN a.BoxMsgInTypeId = 4 THEN 1 ELSE 0 END)>0
		ORDER BY 
		--CASE WHEN 
		SpeedAlerts DESC
		
	/***************** Distance Travelled *****************/
		DECLARE @tblUtilizationBoxes TABLE
	(
		SlNo int identity(1,1), BoxID int, VehicleDescription varchar(250), VehicleName varchar(13),
		StartOdometer bigint, EndOdometer bigint
	)

	INSERT INTO @tblUtilizationBoxes (BoxID, VehicleName, VehicleDescription )
		SELECT distinct h.BoxId ,-- SUBSTRING(v.VehicleDescription,1, 10) 
			--+ CASE WHEN LEN(v.VehicleDescription)>10 THEN '...' ELSE '' END,
			v.VehicleDescription as VehicleName , v.VehicleDescription FROM rvlfMsgInHst h 
			INNER JOIN rvlfVehicleAssignment va ON h.BoxId = va.BoxId
			INNER JOIN rvlfVehicle v ON va.VehicleId = v.VehicleId
			INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId = v.VehicleId and fv.FleetId= @bigFleetID
		WHERE
			v.OrganizationId = @bigOrganizationID 
			AND h.OriginDateTime between @dtStartDate and @dtEndDate 
			
	DECLARE @intCounter int;
	SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes 
	DECLARE @intBoxID int 
	WHILE @intCounter IS NOT NULL
		BEGIN
		print 'counter'
		print @intCounter
		
			SELECT @intBoxID = BoxID FROM @tblUtilizationBoxes WHERE slno = @intCounter
			print 'Boxid'
		print @intBoxID
			UPDATE @tblUtilizationBoxes SET EndOdometer =
				(SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,
					(CHARINDEX(';',CustomProp,
					CHARINDEX('Odometer=',CustomProp,1))) -
					(CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst 
				WHERE 
					BoxId = @intBoxID
					AND OriginDateTime between @dtStartDate and @dtEndDate 
					AND CustomProp LIKE '%Odometer%'
				ORDER BY OriginDateTime ASC) WHERE BoxID = @intBoxID
				
			UPDATE @tblUtilizationBoxes SET StartOdometer =
				(SELECT TOP 1 SUBSTRING(CustomProp, CHARINDEX('Odometer=',CustomProp,0)+9,
					(CHARINDEX(';',CustomProp,
					CHARINDEX('Odometer=',CustomProp,1))) -
					(CHARINDEX('Odometer=',CustomProp,1)+9)) FROM rvlfMsgInHst 
				WHERE 
					BoxId = @intBoxID
					AND OriginDateTime between @dtStartDate and @dtEndDate 
					AND CustomProp LIKE '%Odometer%'
				ORDER BY OriginDateTime DESC)
				WHERE BoxID=@intBoxID
			SELECT @intCounter = MAX(SlNo) FROM @tblUtilizationBoxes WHERE SlNo < @intCounter
		END
		print @CaptionPrefix
	SELECT TOP (@bigTopNos ) BoxID, VehicleDescription, VehicleName, 
		CEILING((StartOdometer - EndOdometer)*@ConversionFactor) as DistanceTravelled,
		@CaptionPrefix as CaptionPrefix
		 FROM @tblUtilizationBoxes	
		WHERE (StartOdometer - EndOdometer) >0 
		ORDER BY (StartOdometer - EndOdometer ) DESC
End
--[RVLT_SP_GetOrgStatistics] 1,null,'2009-10-09 1:08:08','2009-10-09 9:08:08',3, 10

 --[RVLT_SP_GetOrgStatistics] 1,null,'2009-10-15 18:00','2009-10-16 18:00',0, 3


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetRouteETA_AutoUpdate]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
       
CREATE PROCEDURE [dbo].[RVLT_SP_GetRouteETA_AutoUpdate]  
    (                                            
 @ModeID BIGINT = null,  
 @AutoNoETA  BIGINT = null,  
 @NextStopDistance varchar(200) = null,  
 @NextStopDuration varchar(200) = null,  
 @NextStopETA  varchar(200) = null,
 @DestinationStopDistance varchar(200) = null,  
 @DestinationStopDuration varchar(200) = null,  
 @DestinationStopETA  varchar(200) = null                                      
)                                                                 
AS                                                
/******************************************************************************/                                            
-- Name  : RVLT_SP_GetRouteETA_AutoUpdate 0,0  
-- Description : To get the vehicle details for monitor                                            
-- Author  : N.Ranjith                                          
-- Company  : Angler Technologies                                            
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                                            
/******************************************************************************/                                                         
BEGIN                                         
 IF @ModeID = 0  
 Begin  
                  
		 Declare @TempMsginHst table  
		 (  
		 AutoNoETA bigint, 
		 BoxId bigint, 
		RouteID bigint,  
		NextStopID bigint,  
		NextStopName varchar(300),
		NextStopLat varchar(100),
		NextStopLon varchar(100),
		DestinationStopID bigint,  
		DestinationStopName varchar(300),
		DestinationLatLon varchar(300),  
		StopStatus varchar(300),
		Customprop varchar(max),
		RouteStatus int,		
		OrganizationId int,
		MsgStatus varchar(300)
		 )  
   
		 insert into @TempMsginHst  (AutoNoETA, Boxid,RouteID,NextStopID,NextStopName,StopStatus,Customprop,NextStopLat,NextStopLon,RouteStatus,OrganizationId,MsgStatus) 
                       
		 SELECT DISTINCT Mhst.AutoNoETA, Mhst.BoxId, (dbo.rvlf_fn_GetParamValueWithIndex(Mhst.CustomProp,'RouteID=',';')), (dbo.rvlf_fn_GetParamValueWithIndex(Mhst.CustomProp,'NxtStopID=',';')),
		 OG.GeozoneName,
		 (dbo.rvlf_fn_GetParamValueWithIndex(Mhst.CustomProp,'AlertMsg=',';'))  , Mhst.Customprop,GS.latitude,GS.Longitude,Mhst.RouteStatus,og.OrganizationId,
		 (CASE WHEN H.BoxMsgInTypeId IN(5,6) AND Speed >0 THEN  'Moving'                                        
          WHEN H.BoxMsgInTypeId IN(5,6) AND Speed=0 THEN 'Idling'                                    
         WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed > 0  THEN  'Moving'                                    
         WHEN SUBSTRING(LastSensorMask,6,1) =1 and LastSpeed = 0 THEN  'Idling'                                      
         WHEN SUBSTRING(LastSensorMask,6,1) =0 OR H.BoxMsgInTypeId=12 THEN  'Parked'                  
           END) as  MsgStatus
		   FROM rvlfRouteETA   Mhst  
		   inner join rvlfOrganizationGeozone OG on OG.GeozoneId =  (dbo.rvlf_fn_GetParamValueWithIndex(Mhst.CustomProp,'NxtStopID=',';'))
		   inner join rvlfGeozoneSet GS on GS.GeozoneNo  = OG.geozoneNo
		   inner join rvlfBoxId b on b.BoxId = Mhst.BoxID
		   inner join rvlfMsgInHst h on h.MessageInID = b.MessageInId
		   WHERE  Mhst.RouteStatus = 0 
   
		   Declare @VDestinationName varchar(200),@VDestinationID bigint,@VDestinationLat varchar(200),@VDestinationLon varchar(200),@NxtStopID Bigint,  
		   @CurrentLocationLat varchar(200),@CurrentLocationLon varchar(200),@RouteID bigint, @LatLonVal varchar(max) = null , @AutoNoETATmp bigint 
    
		   DECLARE @intBoxIdLooping INT =(SELECT MIN(BoxId) FROM @TempMsginHst)    
      
		   WHILE @intBoxIdLooping IS NOT NULL    
		   BEGIN                            
			select top 1 @NxtStopID = NextStopID,@RouteID=h.RouteID,@CurrentLocationLat=b.LastLatitude ,@CurrentLocationLon =b.LastLongitude,@AutoNoETATmp = h.AutoNoETA
			  from @TempMsginHst h 
			  inner join rvlfBoxId b on b.BoxId =h.BoxId
			  where h.BoxId =@intBoxIdLooping  and h.RouteStatus = 0
  
			select @LatLonVal = COALESCE(@LatLonVal,'') + cast(Latitude as varchar(max)) + ',' + cast(Longitude as varchar(max)) + '$' FROM rvlfRouteDetails RD  
			inner join rvlfOrganizationGeozone OG on OG.GeozoneId =RD.LndID   
			inner join rvlfGeozoneSet GB  on OG.GeozoneNo=GB.GeozoneNo  
			where RouteId =@RouteID  and   
			SeqID >=(select SeqID from rvlfRouteDetails where routeid = @RouteID and LndID = @NxtStopID) order by SeqID  

			select top 1 @VDestinationID = s.LndID,@VDestinationName=og.GeozoneName from rvlfRouteDetails s 
			inner join rvlfOrganizationGeozone og on og.GeozoneId = s.LndID 
			where routeid = @RouteID   order by SeqID Desc

			update @TempMsginHst set 
			DestinationLatLon = @CurrentLocationLat + ',' + @CurrentLocationLon + '$' +  @LatLonVal,DestinationStopName = @VDestinationName,DestinationStopID=@VDestinationID
			where BoxId = @intBoxIdLooping and RouteID =@RouteID and AutoNoETA= @AutoNoETATmp  

			set @LatLonVal = null      
			set @LatLonVal= null      
			SELECT @intBoxIdLooping = MIN(BoxId) from @TempMsginHst WHERE BoxId > @intBoxIdLooping                  
		   END      
    
			UPDATE a 
		SET a.RouteID=t.RouteID, a.NextStop = t.NextStopID,  a.NextStopName=t.NextStopName , a.NextStopLat = t.NextStopLat,a.NextStopLon = t.NextStopLon,
		a.DestinationStopID =t.DestinationStopID,a.DestinationStopName = t.DestinationStopName,a.DestinationLatLon=t.DestinationLatLon,a.StopStatus=t.StopStatus,
		a.MsgStatus=t.MsgStatus
		FROM          
			rvlfrouteETA a
		INNER JOIN 
		   @TempMsginHst t on  t.AutoNoETA = a.AutoNoETA
		where t.AutoNoETA = a.AutoNoETA

   select top 1  RE.AutoNoETA, RE.BoxID,v.VehicleDescription as VehicleName,RE.ScheduleID,b.LastValidDateTime as OriginDateTime,b.LastStreetAddress as StreetAddress,RE.StartLocation,RE.StartLocationDateTime,b.LastLatitude as CurrentLocationLat,   
   b.LastLongitude as CurrentLocationLon,RE.NextStop,RE.NextStopName,RE.NextStopDistance,RE.NextStopDuration,RE.NextStopETA,RE.NextStopLat,RE.NextStopLon,
   RE.DestinationStopID,RE.DestinationStopName,RE.DestinationStopDistance,RE.DestinationStopDuration,RE.DestinationStopETA,RE.DestinationLatLon,
   b.LastSpeed as Speed,RE.MsgStatus,RE.CustomProp,RE.StopStatus,RE.RouteStatus,RE.MessageInId
    from rvlfrouteETA  RE   inner join rvlfBoxId b on b.BoxId =RE.BoxID
	inner join rvlfVehicleAssignment va on va.BoxId = b.BoxId
	inner join rvlfVehicle v on v.VehicleId=va.VehicleId
    where Routestatus = 0   --ORDER BY OriginDateTimeSort DESC,VehicleDescription  ASC     
END  
Else if  @ModeID = 1  
Begin           
update rvlFRouteETA set nextstopdistance =@NextStopDistance,nextstopduration =@NextStopDuration,NextStopETA=@NextStopETA,
Destinationstopdistance =@DestinationStopDistance,Destinationstopduration =@DestinationStopDuration,DestinationStopETA=@DestinationStopETA
 where AutoNoETA =@AutoNoETA  and Routestatus = 0 
END  
END 

GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetStudentRouteDetails_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RVLT_SP_GetStudentRouteDetails_PhoneGap]                
(                              
@bigQueryingUser bigint = 0,            
@intStudentId varchar(max) = null            
)                              
as                             
/******************************************************************************/                                  
-- Name  : RVLT_SP_GetStudentRouteDetails_PhoneGap 11,null                   
-- Description : Get Child location                           
-- Author  : N.Ranjith            
-- Company  : Angler Technologies                              
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason              
/******************************************************************************/                                                     
Begin       
  
  --DECLARE THE VARIABLES FOR GET THE TIMEZONE DETAILS                                      
 DECLARE @HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@SpeedUnit varchar(50),@DefaultDateFormat INT = 0,@ConversionFactor numeric (10,2) = 1.0                                               
  declare @Lang varchar(50),  @LangSetting varchar(20)     
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                                          
   @SpeedUnit = CASE WHEN up.Distance = 0 THEN 'MPH' ELSE 'KMPH' 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 @TempMsginHst table    
   (    
  AutoNoETA bigint,   
  BoxId bigint,   
  VehicleID bigint,  
  VehicleName varchar(500), 
  CurrentAddress varchar(max), 
  LastCommunicationDate datetime,
  RouteID bigint,    
  CurrentLat varchar(100),  
  CurrentLon varchar(100),    
  NextStopID bigint,    
  NextStopName varchar(300),   
  NextStopLat varchar(100),  
  NextStopLon varchar(100),  
  NextStopDistance varchar(1000),  
  NextStopDuration varchar(1000),  
  NextStopETA varchar(1000),  
  DestinationStopID bigint,    
  DestinationStopName varchar(300),  
  DestinationStopLatLon varchar(300),  
  DestinationStopDistance varchar(1000),  
  DestinationStopDuration varchar(1000),  
  DestinationStopETA varchar(1000),    
  StopStatus Bigint,  
  Customprop varchar(max),  
  RouteStatus int,    
  OrganizationId int,  
  MsgStatus varchar(300),  
  StudentID bigint,      
  StudentName nvarchar(200),        
  SchoolContactNo varchar(100),      
  SchoolName varchar(1000),      
  StudentImage varchar(max),      
  SchoolLatitude varchar(50),      
  SchoolLongitude varchar(50)  ,
  StudentStopID bigint,    
  StudentStopName varchar(300),   
  StudentStopLat varchar(100),  
  StudentStopLon varchar(100)    
   )    
     
   insert into @TempMsginHst  (AutoNoETA, Boxid,VehicleID,VehicleName,CurrentAddress,LastCommunicationDate,RouteID,CurrentLat,CurrentLon,  
    NextStopID,NextStopName,NextStopLat,NextStopLon,NextStopDistance,NextStopDuration,NextStopETA,  
   DestinationStopID,DestinationStopName,DestinationStopLatLon,DestinationStopDistance,DestinationStopDuration,DestinationStopETA,  
   StopStatus,Customprop,RouteStatus,OrganizationId,MsgStatus,StudentID,StudentName,SchoolContactNo,SchoolName,StudentImage,      
  SchoolLatitude,SchoolLongitude,StudentStopID,studentStopName,StudentStopLat,StudentStopLon)      
    
                         
   SELECT DISTINCT Mhst.AutoNoETA, Mhst.BoxId,v.VehicleId,v.VehicleDescription,
   Replace(ISNULL(B.LastStreetAddress,'Address is not resolved'),'''','\''') as CurrentAddress,
   CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,B.LastStatusDateTime)),@DefaultDateFormat)+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,B.LastStatusDateTime))AS TIME),22) as LastCommunicationDate, 

                                     
    Mhst.RouteID,b.LastLatitude,b.LastLongitude,  	
    Mhst.NextStop,Mhst.NextStopName,Mhst.NextStopLat,Mhst.NextStopLon,Mhst.NextStopDistance,Mhst.NextStopDuration,Mhst.NextStopETA,  
    Mhst.DestinationStopID,Mhst.DestinationStopName,Mhst.DestinationLatLon,Mhst.DestinationStopDistance,  
    Mhst.DestinationStopDuration,Mhst.DestinationStopETA,Mhst.StopStatus,Mhst.CustomProp,Mhst.RouteStatus,b.OrganizationId,Mhst.MsgStatus,  
    s.StudentMasterID as StudentID,s.StudentFirstName,sa.MobileNo as SchoolContactNo,SchoolName, s.Photo as StudentImage,  gs.Latitude,gs.Longitude,
	s.GeozoneId,og.GeozoneName,gs.Latitude,gs.Longitude     
     FROM rvlfRouteETA   Mhst    
     inner join rvlfOrganizationGeozone OG on OG.GeozoneId =  Mhst.NextStop  
     inner join rvlfGeozoneSet GS on GS.GeozoneNo  = OG.geozoneNo  
     INNER JOIN rvlfVehicleAssignment RVA    ON RVA.BoxId = Mhst.BoxId      
     inner join rvlfVehicle v on v.VehicleId = RVA.VehicleId  
     Inner Join rvlfBoxId b on b.BoxId = RVA.BoxId      
     left outer join rvlfStudentVehicleAssignment sv on sv.VehicleId =RVA.VehicleId              
           INNER JOIN rvlfStudentMaster s on s.StudentMasterId = sv.StudentMasterId          
           inner join rvlfSchoolMaster sa on sa.SchoolID =s.SchoolID        
           INNER JOIN rvlfParentMaster p on p.MobileNo = s.ContactNo       
     WHERE p.UserId = @bigQueryingUser and Mhst.RouteStatus = 0   
      AND (@intStudentId IS NULL OR @intStudentId='' OR s.StudentMasterID = @intStudentId)          

      Declare @LatLonVal varchar(max) = null    
        
    Select @LatLonVal =  (  
      Select  cast(Latitude as varchar(max)) + ',' + cast(Longitude as varchar(max)) + '$'  
      FROM rvlfRouteDetails RD    
   inner join rvlfOrganizationGeozone OG on OG.GeozoneId =RD.LndID     
   inner join rvlfGeozoneSet GB  on OG.GeozoneNo=GB.GeozoneNo    
   where RD.RouteID =(Select top 1 RouteID from @TempMsginHst)  order by SeqID   FOR XML PATH(''))        
     
 
     
     select ROW_NUMBER() over (order by AutoNoETA) as AutoID,AutoNoETA, Boxid,VehicleID,VehicleName,CurrentAddress,LastCommunicationDate, RouteID,CurrentLat,CurrentLon,  
    NextStopID,NextStopName,NextStopLat,NextStopLon,  
    --NextStopDistance as NextStopDistance,  
    --NextStopDuration as NextStopDuration,  
    --NextStopETA as NextStopETA,  
    Cast((cast(NextStopDistance as float) / 1000) as varchar(500)) + ' kms' as NextStopDistance,
   convert(varchar(10), dateadd(second, cast(NextStopETA as bigint), 0), 108) as NextStopDuration, 
    CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,DateAdd(second,cast(NextStopETA as bigint),GETUTCDATE()))),@DefaultDateFormat)+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,DateAdd(second,cast(NextStopETA as bigint),
	GETUTCDATE())))AS TIME),22)  as NextStopETA,
  
   DestinationStopID,DestinationStopName,DestinationStopLatLon,  
  -- DestinationStopDistance as DestinationStopDistance,  
  -- DestinationStopDuration as DestinationStopDuration,  
  -- DestinationStopETA as DestinationStopETA,  
  Cast((cast(DestinationStopDistance as float) / 1000)as varchar(500)) + ' kms' as DestinationStopDistance,
  convert(varchar(10), dateadd(second, cast(DestinationStopETA as bigint), 0), 108) as DestinationStopDuration ,
  CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,DateAdd(second,cast(DestinationStopETA as bigint),GETUTCDATE()))),@DefaultDateFormat)+ ' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,DateAdd(second,cast(DestinationStopETA as bigint),GETUTCDATE())))AS TIME),22)  as DestinationStopETA,
   StopStatus,Customprop,RouteStatus,OrganizationId,MsgStatus,@LatLonVal as RouteLatLon from @TempMsginHst  
  
   select AutoNoETA, Boxid,VehicleID,StudentID,StudentName,SchoolContactNo,SchoolName,StudentImage,      
  SchoolLatitude,SchoolLongitude,StudentStopID,StudentStopName,StudentStopLat,StudentStopLon from @TempMsginHst  
  
  select distinct t.VehicleID,  r.RouteID,og.GeozoneNo,og.GeozoneId,og.GeozoneName,r.SeqID,gs.Latitude,gs.Longitude,  
  (case when  r.SeqID =  
  (select top 1 (rr.SeqID - 1) from rvlfRouteDetails rr inner join  @TempMsginHst tt on tt.NextStopID = rr.LndID order by rr.SeqID)  
   then 1 else 0 end)  as VehicleCurrentStopID ,
   (Case when og.GeozoneId = t.StudentStopID then 1 else 0 end)  as StudentLocation
   from rvlfRouteDetails r  
        inner join rvlfOrganizationGeozone og on og.GeozoneID = r.LndID   
  inner join rvlfGeozoneSet gs on gs.GeozoneNo = og.GeozoneNo  
  inner join @TempMsginHst t on r.RouteID =t.RouteID and t.OrganizationId = og.OrganizationId  
        order by SeqID  
  
  select top 1 (rr.SeqID - 1) from rvlfRouteDetails rr inner join  @TempMsginHst tt on tt.NextStopID = rr.LndID order by rr.SeqID  
  
  
  --  Old backup procedure below till 05-Dec-2015  Ranjith
      
  --     Declare @TempMsginHst table    
  -- (    
  --AutoNoETA bigint,   
  --BoxId bigint,   
  --VehicleID bigint,  
  --VehicleName varchar(500),  
  --RouteID bigint,    
  --   CurrentLat varchar(100),  
  --CurrentLon varchar(100),  
  --NextStopID bigint,    
  --NextStopName varchar(300),   
  --NextStopLat varchar(100),  
  --NextStopLon varchar(100),  
  --NextStopDistance varchar(1000),  
  --NextStopDuration varchar(1000),  
  --NextStopETA varchar(1000),  
  --DestinationStopID bigint,    
  --DestinationStopName varchar(300),  
  --DestinationStopLatLon varchar(300),  
  --DestinationStopDistance varchar(1000),  
  --DestinationStopDuration varchar(1000),  
  --DestinationStopETA varchar(1000),    
  --StopStatus Bigint,  
  --Customprop varchar(max),  
  --RouteStatus int,    
  --OrganizationId int,  
  --MsgStatus varchar(300),  
  --StudentID bigint,      
  --StudentName nvarchar(200),        
  --SchoolContactNo varchar(100),      
  --SchoolName varchar(1000),      
  --StudentImage varchar(max),      
  --SchoolLatitude varchar(50),      
  --SchoolLongitude varchar(50)      
  -- )    
     
  -- insert into @TempMsginHst  (AutoNoETA, Boxid,VehicleID,VehicleName,RouteID,CurrentLat,CurrentLon,  
  --  NextStopID,NextStopName,NextStopLat,NextStopLon,NextStopDistance,NextStopDuration,NextStopETA,  
  -- DestinationStopID,DestinationStopName,DestinationStopLatLon,DestinationStopDistance,DestinationStopDuration,DestinationStopETA,  
  -- StopStatus,Customprop,RouteStatus,OrganizationId,MsgStatus,StudentID,StudentName,SchoolContactNo,SchoolName,StudentImage,      
  --SchoolLatitude,SchoolLongitude)      
     
                         
  -- SELECT DISTINCT Mhst.AutoNoETA, Mhst.BoxId,v.VehicleId,v.VehicleDescription, Mhst.RouteID,b.LastLatitude,b.LastLongitude,  
     
  --  Mhst.NextStop,Mhst.NextStopName,Mhst.NextStopLat,Mhst.NextStopLon,Mhst.NextStopDistance,Mhst.NextStopDuration,Mhst.NextStopETA,  
  --  Mhst.DestinationStopID,Mhst.DestinationStopName,Mhst.DestinationLatLon,Mhst.DestinationStopDistance,  
  --  Mhst.DestinationStopDuration,Mhst.DestinationStopETA,Mhst.StopStatus,Mhst.CustomProp,Mhst.RouteStatus,b.OrganizationId,Mhst.MsgStatus,  
  --  s.StudentMasterID as StudentID,s.StudentFirstName,sa.MobileNo as SchoolContactNo,SchoolName, s.Photo as StudentImage,  gs.Latitude,gs.Longitude      
  --   FROM rvlfRouteETA   Mhst    
  --   inner join rvlfOrganizationGeozone OG on OG.GeozoneId =  Mhst.NextStop  
  --   inner join rvlfGeozoneSet GS on GS.GeozoneNo  = OG.geozoneNo  
  --   INNER JOIN rvlfVehicleAssignment RVA    ON RVA.BoxId = Mhst.BoxId      
  --   inner join rvlfVehicle v on v.VehicleId = RVA.VehicleId  
  --   Inner Join rvlfBoxId b on b.BoxId = RVA.BoxId      
  --   left outer join rvlfStudentVehicleAssignment sv on sv.VehicleId =RVA.VehicleId              
  --         INNER JOIN rvlfStudentMaster s on s.StudentMasterId = sv.StudentMasterId          
  --         inner join rvlfSchoolMaster sa on sa.SchoolID =s.SchoolID        
  --         INNER JOIN rvlfParentMaster p on p.MobileNo = s.ContactNo       
  --   WHERE p.UserId = @bigQueryingUser --and Mhst.RouteStatus = 0   
  --    AND (@intStudentId IS NULL OR @intStudentId='' OR s.StudentMasterID = @intStudentId)          
       
  --    Declare @LatLonVal varchar(max) = null    
        
  --  Select @LatLonVal =  (  
  --    Select  cast(Latitude as varchar(max)) + ',' + cast(Longitude as varchar(max)) + '$'  
  --    FROM rvlfRouteDetails RD    
  -- inner join rvlfOrganizationGeozone OG on OG.GeozoneId =RD.LndID     
  -- inner join rvlfGeozoneSet GB  on OG.GeozoneNo=GB.GeozoneNo    
  -- where RD.RouteID =(Select top 1 RouteID from @TempMsginHst)  order by SeqID   FOR XML PATH(''))       
     
   
     
     
  --   select AutoNoETA, Boxid,VehicleID,VehicleName,RouteID,CurrentLat,CurrentLon,  
  --  NextStopID,NextStopName,NextStopLat,NextStopLon,  
  --  REPLACE(REPLACE(REPLACE(REPLACE(NextStopDistance,'<br>',''),'<b>',''),'</b>',''),'Distance: ','') as NextStopDistance,  
  --  REPLACE(REPLACE(REPLACE(REPLACE(NextStopDuration,'<br>',''),'<b>',''),'</b>',''),'Duration: ','') as NextStopDuration,  
  --  REPLACE(REPLACE(REPLACE(REPLACE(NextStopETA,'<br>',''),'<b>',''),'</b>',''),'ETA: ','') as NextStopETA,  
  -- DestinationStopID,DestinationStopName,DestinationStopLatLon,  
  -- REPLACE(REPLACE(REPLACE(REPLACE(DestinationStopDistance ,'<br>',''),'<b>',''),'</b>',''),'Distance: ','') as DestinationStopDistance,  
  -- REPLACE(REPLACE(REPLACE(REPLACE(DestinationStopDuration,'<br>',''),'<b>',''),'</b>',''),'Duration: ','') as DestinationStopDuration,  
  -- REPLACE(REPLACE(REPLACE(REPLACE(DestinationStopETA,'<br>',''),'<b>',''),'</b>',''),'ETA: ','') as DestinationStopETA,  
  -- StopStatus,Customprop,RouteStatus,OrganizationId,MsgStatus,@LatLonVal as RouteLatLon from @TempMsginHst  
  
  -- select AutoNoETA, Boxid,VehicleID,StudentID,StudentName,SchoolContactNo,SchoolName,StudentImage,      
  --SchoolLatitude,SchoolLongitude from @TempMsginHst  
  
  --select t.VehicleID,  r.RouteID,og.GeozoneNo,og.GeozoneId,og.GeozoneName,r.SeqID,gs.Latitude,gs.Longitude,  
  --(case when  r.SeqID =  
  --(select top 1 (rr.SeqID - 1) from rvlfRouteDetails rr inner join  @TempMsginHst tt on tt.NextStopID = rr.LndID order by rr.SeqID)  
  -- then 1 else 0 end)  as VehicleCurrentStopID  
  -- from rvlfRouteDetails r  
  --      inner join rvlfOrganizationGeozone og on og.GeozoneID = r.LndID   
  --inner join rvlfGeozoneSet gs on gs.GeozoneNo = og.GeozoneNo  
  --inner join @TempMsginHst t on r.RouteID =t.RouteID and t.OrganizationId = og.OrganizationId  
  --      order by SeqID  
  
  --select top 1 (rr.SeqID - 1) from rvlfRouteDetails rr inner join  @TempMsginHst tt on tt.NextStopID = rr.LndID order by rr.SeqID  
  
  
       
       
End

GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetTrendHistory]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----USE [VXLSystem]
----GO
----/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetTrendHistory_Test]    Script Date: 27-09-2019 10:40:34 ******/
----SET ANSI_NULLS ON
----GO
----SET QUOTED_IDENTIFIER ON
----GO
CREATE procedure [dbo].[RVLT_SP_GetTrendHistory]    
(
 @vehicleId varchar(max)=NULL,                  
 @startdate as datetime =NULL,
 @enddate datetime =NULL,
 @interval as int=2000,                  
 @orderby varchar(10)='desc',                  
 @bigQueryingUser bigint = NULL,
 @controller varchar(50)=NULL,                  
 @bitIsMDTMsg bit=0 ,                
 @bitIsMessage bit = 0,          
 @bigLastHours int = NULL,
 @Params varchar(Max)= NULL, 
 @VType tinyint = NULL
)
AS
/******************************************************************************/                  
-- Name  : RVLT_SP_GetTrendHistory_Test 926,'8/7/2019 12:00:00 AM','8/8/2019 12:00:00 AM',2000,'desc',453,null,0,0,null,'5,6,7,8'         
-- Description : To get the messages that needs to be shown in the grid                  
-- Author  : N.Ranjith
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
/******************************************************************************/      

Begin                 


 Declare @vehicleId1 varchar(max)=@vehicleId,                  
 @startdate1 as datetime =@startdate,
 @enddate1 datetime =@enddate,
 @interval1 as int=@interval,                  
 @orderby1 varchar(10)=@orderby,                  
 @bigQueryingUser1 bigint = @bigQueryingUser,
 @controller1 varchar(50)=@controller,                  
 @bitIsMDTMsg1 bit=@bitIsMDTMsg ,                
 @bitIsMessage1 bit = @bitIsMessage,          
 @bigLastHours1 int = @bigLastHours,
 @Params1 varchar(Max)= @Params 

	declare @Lang varchar(50),  @LangSetting varchar(20)  
	declare @param varchar(100);  
	DECLARE @sqlX NVARCHAR(Max); 
	DECLARE @MMvalues nvarchar(Max); 
                 
	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)  ,
			@Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings                
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz                  
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser1                  
    INNER JOIN rvlfUser u ON u.UserId = up.UserId    
	inner join rvlfOrganization o on u.OrganizationId = o.OrganizationId                               
                      
	DECLARE @userIds table (userId bigint)   
	
	Declare @Boxids Table(ID INT Identity(1,1),Boxid Varchar(50))     
	
	Insert into @Boxids(Boxid)
	Select B.BoxId from rvlfBoxId B Inner join rvlfVehicleAssignment VA On B.BoxId = VA.BoxId
	Inner join rvlfVehicle V On V.VehicleId = VA.VehicleId Where v.VehicleId IN(select  FieldValue FROM rvlf_fn_ConvertArrayToTable('926,965',','))
                   
	IF @bigOrganizationID > 1                   
		INSERT INTO @userIds SELECT UserID FROM rvlfUser WHERE OrganizationId = @bigOrganizationID                   
                      
	-------------------date conversion--included by Narayanasamy on 03-Nov-09---------------------------------                  
	 SET @startdate1=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@startdate1))                  
	 SET @enddate1=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@enddate1))        
	----------------------------------------------------------------------------------------------------------                  
    if(@bigLastHours1 <> 0)               
    Begin                  
		SET @enddate1=@startdate1                        
		SET @startdate1= DATEADD(hh,(-1 * @bigLastHours1) ,@startdate1)            
    End            
                
DECLARE @TabParam TABLE(id INT IDENTITY(1,1), Paramname VARCHAR(20))

INSERT INTO @TabParam (Paramname)
SELECT ParamDescr FROM rvlfTrendParamMst  WHERE ParamId IN(select FieldValue FROM rvlf_fn_ConvertArrayToTable(@Params1,','))

select
@param = STUFF((SELECT ', ' + CAST(Paramname AS VARCHAR(10)) [text()]
         FROM @TabParam         
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') FROM @TabParam 

DECLARE @BCount INT, @BTotalCount INT

CREATE  TABLE #TblParamMM ( ParamName VARCHAR(100), Minvalue VARCHAR(50), Maxvalue VARCHAR(50))

CREATE Table #TabParamsvalue  (OrigindateTime datetime, T1 Numeric(10,2),T2 Numeric(10,2),T3 Numeric(10,2),T4 Numeric(10,2),T5 Numeric(10,2), P1 INT,P2 INT,P3 INT,P4 INT, Dps INT, DPp INT, DPp1 INT,
P5 INT,P6 INT,P7 INT, P8 Numeric(10,2),P9 INT,P10 INT,P11 INT, PO1 Numeric(10,2), PO2 Numeric(10,2),PO3 Numeric(10,2),PO4 Numeric(10,2),PO5 Numeric(10,2),PO6 Numeric(10,2),
PO7 Numeric(10,2), PO8 Numeric(10,2),PO9 Numeric(10,2),PO10 Numeric(10,2),PO11 Numeric(10,2),PO12 Numeric(10,2),PO13 Numeric(10,2),PO14 Numeric(10,2),PO15 Numeric(10,2),PO16 Numeric(10,2),PO17 Numeric(10,2),PO18 Numeric(10,2),PO19 Numeric(10,2))

CREATE Table #TabDevicesvalue  ( BoxId Varchar(50), OrigindateTime datetime, T1 Numeric(10,2),T2 Numeric(10,2),T3 Numeric(10,2),T4 Numeric(10,2),T5 Numeric(10,2), P1 INT,P2 INT,P3 INT,P4 INT, Dps INT, DPp INT, DPp1 INT,
P5 INT,P6 INT,P7 INT, P8 Numeric(10,2),P9 INT,P10 INT,P11 INT, PO1 Numeric(10,2), PO2 Numeric(10,2),PO3 Numeric(10,2),PO4 Numeric(10,2),PO5 Numeric(10,2),PO6 Numeric(10,2),
PO7 Numeric(10,2), PO8 Numeric(10,2),PO9 Numeric(10,2),PO10 Numeric(10,2),PO11 Numeric(10,2),PO12 Numeric(10,2),PO13 Numeric(10,2),PO14 Numeric(10,2),PO15 Numeric(10,2),PO16 Numeric(10,2),PO17 Numeric(10,2),PO18 Numeric(10,2),PO19 Numeric(10,2))

IF(@VType='1')
BEGIN  
   SET @BCount =1;

   SET @BTotalCount = (select Count(*) from @Boxids)

   CREATE TABLE #TblDeviceBased (OriginDateTime DATETIME)       
   INSERT INTO #TabDevicesvalue 
   SELECT TOP 5000 h.BoxId ,cast(dbo.rvlf_fn_DayLightSavings(@startdate1,@bigQueryingUser1,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,h.OriginDateTime) as datetime) as OriginDateTime,-- pr.BoxId as DeviceID, Messageinid as MessageInID
   cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T1=',';'),'0') ='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T1=',';') END as numeric(10,2)) AS T1, 
   cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';'),'0') ='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';') END as numeric(10,2)) AS T2,
   cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';'),'0') ='NOT'THEN '0' ELSE  dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';') END as numeric(10,2)) AS T3, 
   cast(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T4=',';') as numeric(10,2)) AS T4,
   cast(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T5=',';') as numeric(10,2)) AS T5,
   cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P1=',';'),'0') ='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P1=',';') END as INT) AS P1,
   cast(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P2=',';') as INT) AS P2,
   cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P3=',';'),'0')='NOT' THEN '0' ELSE  dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P3=',';') END as INT) AS P3,
   cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P4=',';'),'0')='NOT' THEN '0' ELSE  dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P4=',';') END as int) AS P4,
   cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPs=',';'),'0')='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPs=',';') END as Int) AS Dps,
   cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp=',';'),'0')='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp=',';') END as Int) AS DPp,
   cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp1=',';'),'0')='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp1=',';') END as Int) AS DPp1,
   SM.P5 AS P5, PM.P6 AS P6, PM.P7 P7, FM.P8 AS P8, FM.P9 AS P9, FM.P10 AS P10, FM.P11 AS P11, 
   cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';'),'0')='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';') END as numeric(10,2)) AS PO1,
   cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO2=',';'),'0')='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO2=',';') END as numeric(10,2)) AS PO2,
   PO3 AS PO3,PO4 AS PO4,PO5 AS PO5,PO6 AS PO6,PO7 AS PO7, PO8 AS PO8, PO9 AS PO9, PO10 AS PO10, PO11 AS PO11,
   PO12 AS PO12,PO13 AS PO13,PO14 AS PO14,PO15 AS PO15,PO16 AS PO16,PO17 AS PO17,
   PO18 AS PO18,PO19 AS PO19
   FROM rvlfMsgInHst h
   inner join rvlfvehicleassignment va on va.boxid =h.boxid
   inner join rvlfvehicle v on v.vehicleid=va.vehicleid
   Left outer join rvlfMsgInHst_Primary PM On PM.MessageInID = h.MessageInID
   Left outer join rvlfMsgInHst_Secondary SM on SM.MessageInID = h.MessageInID
   Left outer join rvlfMsgInHst_FibreCompactor FM on Fm.MessageInID = h.MessageInID
   WHERE 
   --h.BoxId IN ('AA0003','AA0051') and BoxMsgInTypeId =1 and CONVERT(date,h.OriginDateTime) >= CONVERT(date,'2019-09-01 19:49:38.000') order by h.OriginDateTime desc 
 h.OriginDateTime between @startdate1 and @enddate1 and v.vehicleid IN(SELECT FieldValue FROM rvlf_fn_ConvertArrayToTable(@vehicleId1,',')) and  h.BoxMsgInTypeId=1
  ORDER BY OriginDateTime DESC

   declare @Colnname varchar(20), @addcol varchar(max), @upcol varchar(max); 

   WHILE @BCount <= @BTotalCount
    BEGIN
	   DECLARE  @TBoxid varchar(50) = (SELECT Boxid FROM @Boxids WHERE ID= @BCount)  
	   SET @Colnname =RTRIM(LTRIM(@TBoxid))+'_'+RTRIM(LTRIM(@param+''));
	   if(@BCount = 1)
	   BEGIN
	       SET @addcol = 'ALTER TABLE #TblDeviceBased ADD '+Cast(@Colnname as varchar(20)) +' varchar(20)';	       
	       EXEC(@addcol)

	       SET @sqlX = ' SELECT '+'OriginDateTime,'+ @param+' FROM #TabDevicesvalue where BoxId = '''+@TBoxid+'''';  
	       INSERT INTO #TblDeviceBased
	       exec sp_executesql @sqlX
	   END
	   ELSE
	   BEGIN
	      SET @addcol = 'ALTER TABLE #TblDeviceBased ADD '+Cast(@Colnname as varchar(20)) +' varchar(20)';	      
	      exec(@addcol)  

	      SET @sqlX = 'SELECT '+'OriginDateTime, '''+'null'+''','+@param+' FROM #TabDevicesvalue where BoxId = '''+@TBoxid+'''order by OriginDateTime desc ';	      
	      INSERT INTO #TblDeviceBased 
	      exec sp_executesql @sqlX 
		   
		 SET @upcol = 'update #TblDeviceBased set '+@Colnname+'= '''+'null'+''' Where '+@Colnname+' is null';
		
		exec(@upcol) 

	  END
	   SET @BCount = @BCount +1     
	END 
	
    SELECT * FROM #TblDeviceBased  

    DROP TABLE #TblDeviceBased
	

SELECT 'DeviceBased' AS DevType

END
ELSE   ------------ Param Based --------------------------------------------------------
BEGIN
INSERT INTO #TabParamsvalue 
Select top 5000 cast(dbo.rvlf_fn_DayLightSavings(@startdate1,@bigQueryingUser1,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,h.OriginDateTime) as datetime) as OriginDateTime,-- pr.BoxId as DeviceID, Messageinid as MessageInID
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T1=',';'),'0') ='NOT' THEN '' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T1=',';') END as numeric(10,2)) AS T1, 
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';'),'0') ='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';') END as numeric(10,2)) AS T2,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';'),'0') ='NOT'THEN '0' ELSE  dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';') END as numeric(10,2)) AS T3, 
cast(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T4=',';') as numeric(10,2)) AS T4,
cast(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T5=',';') as numeric(10,2)) AS T5,
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(replace(CustomProp,'DPp1','DPp11'), 'P1=',';'),'0') ='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P1=',';') END as INT) AS P1,
cast(dbo.rvlf_fn_GetParamValueWithIndex(replace(CustomProp,'DPp1','DPp11'), 'P1=',';') as INT) AS P1,
cast(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P2=',';') as INT) AS P2,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P3=',';'),'0')='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P3=',';') END as INT) AS P3,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P4=',';'),'0')='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P4=',';') END as int) AS P4,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPs=',';'),'0')='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPs=',';') END as Int) AS Dps,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp=',';'),'0')='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp=',';') END as Int) AS DPp,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp1=',';'),'0')='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp1=',';') END as Int) AS DPp1,
SM.P5 AS P5, PM.P6 AS P6, PM.P7 P7, FM.P8 AS P8, FM.P9 AS P9, FM.P10 AS P10, FM.P11 AS P11, 
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';'),'0')='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';') END as numeric(10,2)) AS PO1,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO2=',';'),'0')='NOT' THEN '0' ELSE dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO2=',';') END as numeric(10,2)) AS PO2,
PO3 AS PO3,  PO4 AS PO4,PO5 AS PO5,PO6 AS PO6,PO7 AS PO7,PO8 AS PO8, PO9 AS PO9,PO10 AS PO10,PO11 AS PO11,
PO12 AS PO12,PO13 AS PO13,PO14 AS PO14,PO15 AS PO15,PO16 AS PO16,PO17 AS PO17,
PO18 AS PO18,PO19 AS PO19
from rvlfMsgInHst h
inner join rvlfvehicleassignment va on va.boxid =h.boxid
inner join rvlfvehicle v on v.vehicleid=va.vehicleid
Inner join rvlfMsgInHst_Primary PM On PM.MessageInID = h.MessageInID
Inner join rvlfMsgInHst_Secondary SM on SM.MessageInID = h.MessageInID
Left outer join rvlfMsgInHst_FibreCompactor FM on Fm.MessageInID = h.MessageInID
Where 
h.OriginDateTime between @startdate1 and @enddate1 and v.vehicleid IN(select FieldValue FROM rvlf_fn_ConvertArrayToTable(@vehicleId1,',')) and  h.BoxMsgInTypeId=1
order by OriginDateTime desc
   
   SET @sqlX = ' SELECT '+'OriginDateTime,'+ @param + ' FROM #TabParamsvalue order by OriginDateTime desc';
   
   exec sp_executesql @sqlX
   
   Select 'ParamBased' as DevType 

END
--------------------------------------- Min and Max values ------------------------------------------------------


DECLARE @Count INT, @TotalCount INT, @Minval VARCHAR(50), @Maxval VARCHAR(50)
DECLARE @Paramlst VARCHAR(50)

    SET @Count =1;
    SET @TotalCount = (select Count(*) from @TabParam) 
	

     WHILE @Count <= @TotalCount
      BEGIN	 
        SET @Paramlst=(select Paramname from @TabParam where id = @Count) 

		INSERT INTO #TblParamMM(ParamName)
		select @Paramlst 		     
        SET @MMvalues = 'Update  #TblParamMM set Minvalue =  (SELECT ISNULL(MIN('+@Paramlst+'),''0'') FROM #TabParamsvalue),Maxvalue =  (SELECT ISNULL(MAX('+@Paramlst+'),''0'') FROM #TabParamsvalue)  where ParamName= '''+@Paramlst+''''      
        exec sp_executesql @MMvalues 
        SET @Count = @Count +1  
      END

 SELECT  * FROM #TblParamMM

 DROP TABLE #TabParamsvalue
 DROP TABLE #TabDevicesvalue
 DROP TABLE #TblParamMM

--DECLARE @Count INT, @TotalCount INT, @Minval VARCHAR(50), @Maxval VARCHAR(50)
--DECLARE @Paramlst VARCHAR(50)

--    SET @Count =1;
--    SET @TotalCount = (select Count(*) from @TabParam)

--IF(@VType = 2)
-- BEGIN
--    WHILE @Count <= @TotalCount
--      BEGIN
--        SET @Paramlst=(select Paramname from @TabParam where id = @Count)
--        SET @Minval = (select Paramname+'_Min' from @TabParam where id = @Count)
--        SET @Maxval = (select Paramname+'_Max' from @TabParam where id = @Count)
	 
--        declare @val varchar(MAX)=''
--        set @val='Insert  into #TblParamMM (ParamName, Minvalue, Maxvalue) ' + 'select '''+ @Paramlst +''',ISNULL('+ @Minval + ',''0''), ISNULL('+@Maxval + ',''0'')  from rvlfParamRange pr inner join rvlfVehicleAssignment va
--        on pr.Boxid = va.BoxId inner join rvlfVehicle v on v.VehicleId = va.VehicleId
--        where V.VehicleId IN (select FieldValue FROM rvlf_fn_ConvertArrayToTable('+''''+@vehicleId1+''''+','',''))'; 
--        EXECUTE(@val) 	 
--        SET @Count = @Count +1  
--      END
--SELECT  * FROM #TblParamMM
--END
--ELSE
--BEGIN
--       WHILE @Count <= @TotalCount
--       BEGIN
--        SET @Paramlst=(select Paramname from @TabParam where id = @Count)
--        SET @Minval = (select Paramname+'_Min' from @TabParam where id = @Count)
--        SET @Maxval = (select Paramname+'_Max' from @TabParam where id = @Count)		 
--		 SET @BCount =1;
--         SET @BTotalCount = (select Count(*) from @Boxids)	
--		 WHILE @BCount <= @BTotalCount
--          BEGIN
--		      DECLARE  @TBoxid1 varchar(50) = (SELECT Boxid FROM @Boxids WHERE ID= @BCount)
--		      SET @Paramlst =RTRIM(LTRIM(@TBoxid1))+'_'+RTRIM(LTRIM(@param+''));			  
--              declare @valD varchar(MAX)=''
--              set @valD='Insert  into #TblParamMM (ParamName, Minvalue, Maxvalue) ' + 'select '''+ @Paramlst +''',ISNULL('+ @Minval + ',''0''), ISNULL('+@Maxval + ',''0'')  from rvlfParamRange pr inner join rvlfVehicleAssignment va
--              on pr.Boxid = va.BoxId inner join rvlfVehicle v on v.VehicleId = va.VehicleId
--              where pr.BoxId = '''+@TBoxid1+''''; 
--             EXECUTE(@valD) 
--			SET @BCount = @BCount +1  
--	      END
--        SET @Count = @Count +1  
--      END

--   SELECT  * FROM #TblParamMM
-- END 

End     




GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetTrendHistory_Test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----USE [VXLSystem]
----GO
----/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetTrendHistory_Test]    Script Date: 27-09-2019 10:40:34 ******/
----SET ANSI_NULLS ON
----GO
----SET QUOTED_IDENTIFIER ON
----GO
CREATE procedure [dbo].[RVLT_SP_GetTrendHistory_Test]    
(
 @vehicleId varchar(max)=NULL,                  
 @startdate as datetime =NULL,
 @enddate datetime =NULL,
 @interval as int=2000,                  
 @orderby varchar(10)='desc',                  
 @bigQueryingUser bigint = NULL,
 @controller varchar(50)=NULL,                  
 @bitIsMDTMsg bit=0 ,                
 @bitIsMessage bit = 0,          
 @bigLastHours int = NULL,
 @Params varchar(Max)= NULL, 
 @VType tinyint = NULL
)
AS
/******************************************************************************/                  
-- Name  : RVLT_SP_GetTrendHistory_Test 926,'8/7/2019 12:00:00 AM','8/8/2019 12:00:00 AM',2000,'desc',453,null,0,0,null,'5,6,7,8'         
-- Description : To get the messages that needs to be shown in the grid                  
-- Author  : N.Ranjith
-- Company  : Angler Technologies                  
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                  
/******************************************************************************/      

Begin                 


 Declare @vehicleId1 varchar(max)=@vehicleId,                  
 @startdate1 as datetime =@startdate,
 @enddate1 datetime =@enddate,
 @interval1 as int=@interval,                  
 @orderby1 varchar(10)=@orderby,                  
 @bigQueryingUser1 bigint = @bigQueryingUser,
 @controller1 varchar(50)=@controller,                  
 @bitIsMDTMsg1 bit=@bitIsMDTMsg ,                
 @bitIsMessage1 bit = @bitIsMessage,          
 @bigLastHours1 int = @bigLastHours,
 @Params1 varchar(Max)= @Params 

	declare @Lang varchar(50),  @LangSetting varchar(20)  
	declare @param varchar(100);  
	DECLARE @sqlX NVARCHAR(Max); 
	DECLARE @MMvalues nvarchar(Max); 
                 
	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)  ,
			@Lang=isnull(Lang,'LanguageEn'),@LangSetting=o.OrgLangSettings                
    FROM rvlfUserPreferences up INNER JOIN rvlfTimeZones tz                  
    ON up.TimeZoneId = tz.TimeZoneId AND up.UserId = @bigQueryingUser1                  
    INNER JOIN rvlfUser u ON u.UserId = up.UserId    
	inner join rvlfOrganization o on u.OrganizationId = o.OrganizationId                               
                      
	DECLARE @userIds table (userId bigint)   
	
	Declare @Boxids Table(ID INT Identity(1,1),Boxid Varchar(50))     
	
	Insert into @Boxids(Boxid)
	Select B.BoxId from rvlfBoxId B Inner join rvlfVehicleAssignment VA On B.BoxId = VA.BoxId
	Inner join rvlfVehicle V On V.VehicleId = VA.VehicleId Where v.VehicleId IN(select  FieldValue FROM rvlf_fn_ConvertArrayToTable('926,965',','))
                   
	IF @bigOrganizationID > 1                   
		INSERT INTO @userIds SELECT UserID FROM rvlfUser WHERE OrganizationId = @bigOrganizationID                   
                      
	-------------------date conversion--included by Narayanasamy on 03-Nov-09---------------------------------                  
	 SET @startdate1=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@startdate1))                  
	 SET @enddate1=DATEADD(HOUR,(@HoursToBeAdded*-1),DATEADD(MINUTE,(@MinsToBeAdded*-1),@enddate1))        
	----------------------------------------------------------------------------------------------------------                  
    if(@bigLastHours1 <> 0)               
    Begin                  
		SET @enddate1=@startdate1                        
		SET @startdate1= DATEADD(hh,(-1 * @bigLastHours1) ,@startdate1)            
    End            
                
DECLARE @TabParam TABLE(id INT IDENTITY(1,1), Paramname VARCHAR(20))

INSERT INTO @TabParam (Paramname)
SELECT ParamDescr FROM rvlfTrendParamMst  WHERE ParamId IN(select FieldValue FROM rvlf_fn_ConvertArrayToTable(@Params1,','))

select
@param = STUFF((SELECT ', ' + CAST(Paramname AS VARCHAR(10)) [text()]
         FROM @TabParam         
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') FROM @TabParam 

DECLARE @BCount INT, @BTotalCount INT

CREATE  TABLE #TblParamMM ( ParamName VARCHAR(100), Minvalue VARCHAR(50), Maxvalue VARCHAR(50))

CREATE Table #TabParamsvalue  (OrigindateTime datetime, T1 VARCHAR(10),T2 VARCHAR(10),T3 VARCHAR(10),T4 VARCHAR(10),T5 VARCHAR(10), P1 VARCHAR(10),P2 VARCHAR(10),P3 VARCHAR(10),P4 VARCHAR(10), Ps VARCHAR(10), Pp1 VARCHAR(10), Pp2 VARCHAR(10),
P5 VARCHAR(10),P6 VARCHAR(10),P7 VARCHAR(10), P8 VARCHAR(10),P9 VARCHAR(10),P10 VARCHAR(10),P11 VARCHAR(10), PO1 VARCHAR(10), PO2 VARCHAR(10),PO3 VARCHAR(10),PO4 VARCHAR(10),PO5 VARCHAR(10),PO6 VARCHAR(10),
PO7 VARCHAR(10), PO8 VARCHAR(10),PO9 VARCHAR(10),PO10 VARCHAR(10),PO11 VARCHAR(10),PO12 VARCHAR(10),PO13 VARCHAR(10),PO14 VARCHAR(10),PO15 VARCHAR(10),PO16 VARCHAR(10),PO17 VARCHAR(10),PO18 VARCHAR(10),PO19 VARCHAR(10))

CREATE Table #TabDevicesvalue  ( BoxId Varchar(50), OrigindateTime datetime, T1 VARCHAR(10),T2 VARCHAR(10),T3 VARCHAR(10),T4 VARCHAR(10),T5 VARCHAR(10), P1 VARCHAR(10),P2 VARCHAR(10),P3 VARCHAR(10),P4 VARCHAR(10), Ps VARCHAR(10), Pp1 VARCHAR(10), Pp2 VARCHAR(10),
P5 VARCHAR(10),P6 VARCHAR(10),P7 VARCHAR(10), P8 VARCHAR(10),P9 VARCHAR(10),P10 VARCHAR(10),P11 VARCHAR(10), PO1 VARCHAR(10), PO2 VARCHAR(10),PO3 VARCHAR(10),PO4 VARCHAR(10),PO5 VARCHAR(10),PO6 VARCHAR(10),
PO7 VARCHAR(10), PO8 VARCHAR(10),PO9 VARCHAR(10),PO10 VARCHAR(10),PO11 VARCHAR(10),PO12 VARCHAR(10),PO13 VARCHAR(10),PO14 VARCHAR(10),PO15 VARCHAR(10),PO16 VARCHAR(10),PO17 VARCHAR(10),PO18 VARCHAR(10),PO19 VARCHAR(10))

IF(@VType='1')
BEGIN  
   SET @BCount =1;

   SET @BTotalCount = (select Count(*) from @Boxids)

   CREATE TABLE #TblDeviceBased (OriginDateTime DATETIME)       
   INSERT INTO #TabDevicesvalue 
   SELECT TOP 5000 h.BoxId ,cast(dbo.rvlf_fn_DayLightSavings(@startdate1,@bigQueryingUser1,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,h.OriginDateTime) as datetime) as OriginDateTime,-- pr.BoxId as DeviceID, Messageinid as MessageInID
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T1=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T1=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS T1, 
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS T2,
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS T3, 
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T4=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T4=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS T4, 
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T5=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T5=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS T5, 
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';'),'0') ='NOT'THEN 'null' ELSE ISNULL(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';') AS numeric(18,2)),'null') END AS VARCHAR(10)) AS T2,
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';'),'0') ='NOT'THEN 'null' ELSE  ISNULL(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';') AS numeric(18,2)),'null') END AS VARCHAR(10)) AS T3, 
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T4=',';'),'0') ='NOT'THEN 'null' ELSE  ISNULL(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T4=',';') AS numeric(18,2)),'null') END AS VARCHAR(10)) AS T4, 
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T5=',';'),'0') ='NOT'THEN 'null' ELSE  ISNULL(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T5=',';') AS numeric(18,2)),'null') END AS VARCHAR(10)) AS T5,  
cast(ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(replace(CustomProp,'DPp1','DPp11'), 'P1=',';'),'null') AS VARCHAR(10)) AS P1,
cast(ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P2=',';'),'null') AS VARCHAR(10)) AS P2,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P3=',';'),'0')='NOT' THEN 'null' ELSE  ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P3=',';'),'null') END AS VARCHAR(10)) AS P3,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P4=',';'),'0')='NOT' THEN 'null' ELSE  ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P4=',';'),'null') END AS VARCHAR(10)) AS P4,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPs=',';'),'0')='NOT' THEN 'null' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPs=',';'),'null') END AS VARCHAR(10)) AS Ps,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp=',';'),'0')='NOT' THEN 'null' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp=',';'),'null') END AS VARCHAR(10)) AS Pp1,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp1=',';'),'0')='NOT' THEN 'null' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp1=',';'),'null') END AS VARCHAR(10)) AS Pp2,
ISNULL(cast(SM.P5 as varchar(10)),'null') AS P5, ISNULL(cast(PM.P6 as varchar(10)),'null') AS P6, ISNULL(cast(PM.P7 as varchar(10)),'null') AS P7, ISNULL(cast(FM.P8 as varchar(10)),'null') AS P8, ISNULL(cast(FM.P9 as varchar(10)),'null') AS P9, ISNULL(cast(FM.P10 as varchar(10)),'null')AS P10, ISNULL(cast(FM.P11 as varchar(10)),'null') AS P11, 
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS PO1, 
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO2=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO2=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS PO2,
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';'),'0')='NOT' THEN 'null' ELSE ISNULL(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';')AS numeric(18,2)),'null')END AS VARCHAR(10)) AS PO1,
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO2=',';'),'0')='NOT' THEN 'null' ELSE ISNULL(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO2=',';')AS numeric(18,2)),'null') END AS VARCHAR(10)) AS PO2,
ISNULL(cast(PO3 as varchar(10)),'null') AS PO3,  ISNULL(cast(PO4 as varchar(10)),'null')AS PO4,ISNULL(cast(PO5 as varchar(10)),'null') AS PO5,ISNULL(cast(PO6 as varchar(10)),'null') AS PO6,ISNULL(cast(PO7 as varchar(10)),'null') AS PO7,ISNULL(cast(PO8 as varchar(10)),'null') AS PO8,ISNULL(cast(PO9 as varchar(10)),'null') AS PO9,ISNULL(cast(PO10 as varchar(10)),'null') AS PO10,ISNULL(cast(PO11 as varchar(10)),'null') AS PO11,
ISNULL(cast(PO12 as varchar(10)),'null') AS PO12,ISNULL(cast(PO13 as varchar(10)),'null') AS PO13,ISNULL(cast(PO14 as varchar(10)),'null') AS PO14,ISNULL(cast(PO15 as varchar(10)),'null') AS PO15,ISNULL(cast(PO16 as varchar(10)),'null') AS PO16,ISNULL(cast(PO17 as varchar(10)),'null') AS PO17,
ISNULL(cast(PO18 as varchar(10)),'null')AS PO18, ISNULL(cast(PO19 as varchar(10)),'null') AS PO19
   FROM rvlfMsgInHst h
   inner join rvlfvehicleassignment va on va.boxid =h.boxid
   inner join rvlfvehicle v on v.vehicleid=va.vehicleid
   Left outer join rvlfMsgInHst_Primary PM On PM.MessageInID = h.MessageInID
   Left outer join rvlfMsgInHst_Secondary SM on SM.MessageInID = h.MessageInID
   Left outer join rvlfMsgInHst_FibreCompactor FM on Fm.MessageInID = h.MessageInID
   WHERE 
   --h.BoxId IN ('AA0003','AA0051') and BoxMsgInTypeId =1 and CONVERT(date,h.OriginDateTime) >= CONVERT(date,'2019-09-01 19:49:38.000') order by h.OriginDateTime desc 
 h.OriginDateTime between @startdate1 and @enddate1 and v.vehicleid IN(SELECT FieldValue FROM rvlf_fn_ConvertArrayToTable(@vehicleId1,',')) and  h.BoxMsgInTypeId=1
  ORDER BY OriginDateTime DESC

   declare @Colnname varchar(20), @addcol varchar(max), @upcol varchar(max); 

   WHILE @BCount <= @BTotalCount
    BEGIN
	   DECLARE  @TBoxid varchar(50) = (SELECT Boxid FROM @Boxids WHERE ID= @BCount)  
	   SET @Colnname =RTRIM(LTRIM(@TBoxid))+'_'+RTRIM(LTRIM(@param+''));
	   if(@BCount = 1)
	   BEGIN
	       SET @addcol = 'ALTER TABLE #TblDeviceBased ADD '+Cast(@Colnname as varchar(20)) +' varchar(20)';	       
	       EXEC(@addcol)

	       SET @sqlX = ' SELECT '+'OriginDateTime,'+ @param+' FROM #TabDevicesvalue where BoxId = '''+@TBoxid+'''';  
	       INSERT INTO #TblDeviceBased
	       exec sp_executesql @sqlX
	   END
	   ELSE
	   BEGIN
	      SET @addcol = 'ALTER TABLE #TblDeviceBased ADD '+Cast(@Colnname as varchar(20)) +' varchar(20)';	      
	      exec(@addcol)  

	      SET @sqlX = 'SELECT '+'OriginDateTime, '''+'null'+''','+@param+' FROM #TabDevicesvalue where BoxId = '''+@TBoxid+'''order by OriginDateTime desc ';	      
	      INSERT INTO #TblDeviceBased 
	      exec sp_executesql @sqlX 
		   
		 SET @upcol = 'update #TblDeviceBased set '+@Colnname+'= '''+'null'+''' Where '+@Colnname+' is null';
		
		exec(@upcol) 

	  END
	   SET @BCount = @BCount +1     
	END 
	
    SELECT * FROM #TblDeviceBased  

    DROP TABLE #TblDeviceBased
	

SELECT 'DeviceBased' AS DevType

END
ELSE   ------------ Param Based --------------------------------------------------------
BEGIN
INSERT INTO #TabParamsvalue 
Select top 5000 cast(dbo.rvlf_fn_DayLightSavings(@startdate1,@bigQueryingUser1,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,h.OriginDateTime) as datetime) as OriginDateTime,-- pr.BoxId as DeviceID, Messageinid as MessageInID
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T1=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T1=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS T1, 
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS T2,
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS T3, 
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T4=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T4=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS T4, 
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T5=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T5=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS T5, 
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';'),'0') ='NOT'THEN 'null' ELSE ISNULL(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T2=',';') AS numeric(18,2)),'null') END AS VARCHAR(10)) AS T2,
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';'),'0') ='NOT'THEN 'null' ELSE  ISNULL(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T3=',';') AS numeric(18,2)),'null') END AS VARCHAR(10)) AS T3, 
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T4=',';'),'0') ='NOT'THEN 'null' ELSE  ISNULL(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T4=',';') AS numeric(18,2)),'null') END AS VARCHAR(10)) AS T4, 
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T5=',';'),'0') ='NOT'THEN 'null' ELSE  ISNULL(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'T5=',';') AS numeric(18,2)),'null') END AS VARCHAR(10)) AS T5,  
cast(ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(replace(CustomProp,'DPp1','DPp11'), 'P1=',';'),'null') AS VARCHAR(10)) AS P1,
cast(ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P2=',';'),'null') AS VARCHAR(10)) AS P2,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P3=',';'),'0')='NOT' THEN 'null' ELSE  ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P3=',';'),'null') END AS VARCHAR(10)) AS P3,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P4=',';'),'0')='NOT' THEN 'null' ELSE  ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'P4=',';'),'null') END AS VARCHAR(10)) AS P4,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPs=',';'),'0')='NOT' THEN 'null' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPs=',';'),'null') END AS VARCHAR(10)) AS Ps,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp=',';'),'0')='NOT' THEN 'null' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp=',';'),'null') END AS VARCHAR(10)) AS Pp1,
cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp1=',';'),'0')='NOT' THEN 'null' ELSE ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'DPp1=',';'),'null') END AS VARCHAR(10)) AS Pp2,
ISNULL(cast(SM.P5 as varchar(10)),'null') AS P5, ISNULL(cast(PM.P6 as varchar(10)),'null') AS P6, ISNULL(cast(PM.P7 as varchar(10)),'null') AS P7, ISNULL(cast(FM.P8 as varchar(10)),'null') AS P8, ISNULL(cast(FM.P9 as varchar(10)),'null') AS P9, ISNULL(cast(FM.P10 as varchar(10)),'null')AS P10, ISNULL(cast(FM.P11 as varchar(10)),'null') AS P11, 
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS PO1, 
CASE WHEN dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO2=',';') IS NOT NULL THEN CAST(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO2=',';') AS numeric(18,2))As varchar(10)) ELSE 'null' END AS PO2,
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';'),'0')='NOT' THEN 'null' ELSE ISNULL(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO1=',';')AS numeric(18,2)),'null')END AS VARCHAR(10)) AS PO1,
--cast(CASE WHEN ISNULL(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO2=',';'),'0')='NOT' THEN 'null' ELSE ISNULL(CAST(dbo.rvlf_fn_GetParamValueWithIndex(H.CustomProp, 'PO2=',';')AS numeric(18,2)),'null') END AS VARCHAR(10)) AS PO2,
ISNULL(cast(PO3 as varchar(10)),'null') AS PO3,  ISNULL(cast(PO4 as varchar(10)),'null')AS PO4,ISNULL(cast(PO5 as varchar(10)),'null') AS PO5,ISNULL(cast(PO6 as varchar(10)),'null') AS PO6,ISNULL(cast(PO7 as varchar(10)),'null') AS PO7,ISNULL(cast(PO8 as varchar(10)),'null') AS PO8,ISNULL(cast(PO9 as varchar(10)),'null') AS PO9,ISNULL(cast(PO10 as varchar(10)),'null') AS PO10,ISNULL(cast(PO11 as varchar(10)),'null') AS PO11,
ISNULL(cast(PO12 as varchar(10)),'null') AS PO12,ISNULL(cast(PO13 as varchar(10)),'null') AS PO13,ISNULL(cast(PO14 as varchar(10)),'null') AS PO14,ISNULL(cast(PO15 as varchar(10)),'null') AS PO15,ISNULL(cast(PO16 as varchar(10)),'null') AS PO16,ISNULL(cast(PO17 as varchar(10)),'null') AS PO17,
ISNULL(cast(PO18 as varchar(10)),'null')AS PO18, ISNULL(cast(PO19 as varchar(10)),'null') AS PO19
from rvlfMsgInHst h
inner join rvlfvehicleassignment va on va.boxid =h.boxid
inner join rvlfvehicle v on v.vehicleid=va.vehicleid
Inner join rvlfMsgInHst_Primary PM On PM.MessageInID = h.MessageInID
Inner join rvlfMsgInHst_Secondary SM on SM.MessageInID = h.MessageInID
Left outer join rvlfMsgInHst_FibreCompactor FM on Fm.MessageInID = h.MessageInID
Where 
h.OriginDateTime between @startdate1 and @enddate1 and v.vehicleid IN(select FieldValue FROM rvlf_fn_ConvertArrayToTable(@vehicleId1,',')) and  h.BoxMsgInTypeId=1
order by OriginDateTime desc
   
   SET @sqlX = ' SELECT '+'OriginDateTime,'+ @param + ' FROM #TabParamsvalue order by OriginDateTime desc';
   
   exec sp_executesql @sqlX
   
   Select 'ParamBased' as DevType 

END
--------------------------------------- Min and Max values ------------------------------------------------------


DECLARE @Count INT, @TotalCount INT, @Minval VARCHAR(50), @Maxval VARCHAR(50)
DECLARE @Paramlst VARCHAR(50)

    SET @Count =1;
    SET @TotalCount = (select Count(*) from @TabParam) 
	

     WHILE @Count <= @TotalCount
      BEGIN	 
        SET @Paramlst=(select Paramname from @TabParam where id = @Count) 

		INSERT INTO #TblParamMM(ParamName)
		select @Paramlst 		     
        SET @MMvalues = 'Update  #TblParamMM set Minvalue =  (SELECT ISNULL(MIN(CONVERT(float,'+@Paramlst+')),''0'') FROM #TabParamsvalue WHERE '+@Paramlst+' NOT IN(''null'')),Maxvalue =  (SELECT ISNULL(MAX(CONVERT(float,'+@Paramlst+')),''0'') FROM #TabParamsvalue WHERE '+@Paramlst+' NOT IN(''null''))  where ParamName= '''+@Paramlst+''''      
        exec sp_executesql @MMvalues 
        SET @Count = @Count +1  
      END

 SELECT  * FROM #TblParamMM

 DROP TABLE #TabParamsvalue
 DROP TABLE #TabDevicesvalue
 DROP TABLE #TblParamMM

--DECLARE @Count INT, @TotalCount INT, @Minval VARCHAR(50), @Maxval VARCHAR(50)
--DECLARE @Paramlst VARCHAR(50)

--    SET @Count =1;
--    SET @TotalCount = (select Count(*) from @TabParam)

--IF(@VType = 2)
-- BEGIN
--    WHILE @Count <= @TotalCount
--      BEGIN
--        SET @Paramlst=(select Paramname from @TabParam where id = @Count)
--        SET @Minval = (select Paramname+'_Min' from @TabParam where id = @Count)
--        SET @Maxval = (select Paramname+'_Max' from @TabParam where id = @Count)
	 
--        declare @val varchar(MAX)=''
--        set @val='Insert  into #TblParamMM (ParamName, Minvalue, Maxvalue) ' + 'select '''+ @Paramlst +''',ISNULL('+ @Minval + ',''0''), ISNULL('+@Maxval + ',''0'')  from rvlfParamRange pr inner join rvlfVehicleAssignment va
--        on pr.Boxid = va.BoxId inner join rvlfVehicle v on v.VehicleId = va.VehicleId
--        where V.VehicleId IN (select FieldValue FROM rvlf_fn_ConvertArrayToTable('+''''+@vehicleId1+''''+','',''))'; 
--        EXECUTE(@val) 	 
--        SET @Count = @Count +1  
--      END
--SELECT  * FROM #TblParamMM
--END
--ELSE
--BEGIN
--       WHILE @Count <= @TotalCount
--       BEGIN
--        SET @Paramlst=(select Paramname from @TabParam where id = @Count)
--        SET @Minval = (select Paramname+'_Min' from @TabParam where id = @Count)
--        SET @Maxval = (select Paramname+'_Max' from @TabParam where id = @Count)		 
--		 SET @BCount =1;
--         SET @BTotalCount = (select Count(*) from @Boxids)	
--		 WHILE @BCount <= @BTotalCount
--          BEGIN
--		      DECLARE  @TBoxid1 varchar(50) = (SELECT Boxid FROM @Boxids WHERE ID= @BCount)
--		      SET @Paramlst =RTRIM(LTRIM(@TBoxid1))+'_'+RTRIM(LTRIM(@param+''));			  
--              declare @valD varchar(MAX)=''
--              set @valD='Insert  into #TblParamMM (ParamName, Minvalue, Maxvalue) ' + 'select '''+ @Paramlst +''',ISNULL('+ @Minval + ',''0''), ISNULL('+@Maxval + ',''0'')  from rvlfParamRange pr inner join rvlfVehicleAssignment va
--              on pr.Boxid = va.BoxId inner join rvlfVehicle v on v.VehicleId = va.VehicleId
--              where pr.BoxId = '''+@TBoxid1+''''; 
--             EXECUTE(@valD) 
--			SET @BCount = @BCount +1  
--	      END
--        SET @Count = @Count +1  
--      END

--   SELECT  * FROM #TblParamMM
-- END 

End     




GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetVehicleByFleetID]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[RVLT_SP_GetVehicleByFleetID](           
@FleetID bigint=null,                                        
@bigQueryingUser bigint = 0,                                        
@bigVehicleId bigint = null,                                        
@bigOrganizationID bigint =NULL,
@CustomerID bigint=null                           
)                                                        
AS                                           
/******************************************************************************/                                        
-- Name  : RVLT_SP_GetVehicleByFleetID 176,453,null,86,139                         
-- Description : To get the ESP details for monitor                                        
-- Company  : Angler Technologies                                        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
/******************************************************************************/                                                     
BEGIN 

if @bigOrganizationID Is null              
set @bigOrganizationID=(select organizationID from rvlfFleet where FleetId=@FleetID)
--DECLARE THE VARIABLES FOR GET THE TIMEZONE DETAILS                                    
DECLARE @HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@SpeedUnit varchar(50),@DefaultDateFormat INT = 0,@ConversionFactor numeric (10,2) = 1.0                                            
DECLARE @Lang varchar(50),  @LangSetting varchar(20)                                     
SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,--@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                                        
--@SpeedUnit = CASE WHEN up.Distance = 0 THEN 'MPH' ELSE 'KMPH' 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   


-------------------------------GET THE VEHICLES BASED ON THE FLEET ----------------------------------------------              

	SELECT  B.MessageInID, MD.VehicleID, B.BoxID as DeviceID, Md.EquipmentName as VehicleDescription, VT.VehicleTypeName AS EquipmentTypeName, VT.VehicleTypeId,C.CustomerName, 
	ISNULL((SELECT FleetName FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From 
 rvlfFleetVehicles Where VehicleId = MD.VehicleId and FleetId <> 176)), 'Site Not Assigned') as SiteName, '' AS ControllerName, '' as ControllerPositionID, '' as dcsimid, 
					B.LastStreetAddress  as StreetAddress, CAST(ISNULL((Case WHEN @Lang='LanguageArNew' THEN ISNULL(B.LastStreetAddress_AR,B.LastStreetAddress) ELSE B.LastStreetAddress END),'Address is not resolved')AS NVARCHAR(MAX))  AS Address, 
			[DateTime] =dbo.rvlf_fn_DayLightSavings(GETDATE(),@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,B.LastValidDateTime), 
		CASE WHEN B.LastLatitude = 0 AND B.LastLongitude = 0 AND B.LastValidDateTime = B.LastStatusDateTime THEN 
				0
			 WHEN B.LastValidDateTime = B.LastStatusDateTime THEN 
				1 
			ELSE 
				0 
			END as IsCurrent,                                           
	OriginDateTime = dbo.rvlf_fn_DayLightSavings(B.LastStatusDateTime,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,B.LastStatusDateTime),                             
	DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,B.LastStatusDateTime)) as OriginDateTimeSort,
	H.BoxMsgInTypeId,
		--CASE 
		--      WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) >= 480  THEN 'Offline' 
		--	  WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND (SUBSTRING(ISNULL(h.Digital_OP,'0000000000000000'),10,1)='1' or SUBSTRING(ISNULL(hh.Digital_OP,'0000000000000000'),7,1)='1') THEN 'Running' 
		--     WHEN B.DeviceStatus =1 THEN 'Information'   
		--     WHEN B.DeviceStatus =2 THEN 'Warning'
		--	 WHEN B.DeviceStatus =3 THEN 'Electrical Trip'
		--	 WHEN B.DeviceStatus =4 THEN 'Shutdown'  
		--	 WHEN B.DeviceStatus =5 THEN 'Controlled Shutdown'
		--	 WHEN B.DeviceStatus =6 THEN 'Engine' 			
		--	 Else '-'
		--	 END AS [Status],
			 
			 CASE WHEN VT.VehicleTypeId =1  THEN 
			  CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) >= 480  THEN 'Offline' 
			  WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND (SUBSTRING(ISNULL(h.Digital_OP,'0000000000000000'),10,1)='1') THEN 'Running' 
		     WHEN B.DeviceStatus =1 THEN 'Information'   
		     WHEN B.DeviceStatus =2 THEN 'Warning'
			 WHEN B.DeviceStatus =3 THEN 'Electrical Trip'
			 WHEN B.DeviceStatus =4 THEN 'Shutdown'  
			 WHEN B.DeviceStatus =5 THEN 'Controlled Shutdown'
			 WHEN B.DeviceStatus =6 THEN 'Engine' 			
			 Else '-'
			 END 
			 ELSE CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) >= 480  THEN 'Offline' 
			  WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND 
			  (SUBSTRING(ISNULL(hh.Digital_IP,'0000000000000000'),9,1)='1' OR SUBSTRING(isnull(hh.Digital_IP,'0000000000000000'),8,1) ='1')
			   THEN 'Running' 
		     WHEN B.DeviceStatus =1 THEN 'Information'   
		     WHEN B.DeviceStatus =2 THEN 'Warning'
			 WHEN B.DeviceStatus =3 THEN 'Electrical Trip'
			 WHEN B.DeviceStatus =4 THEN 'Shutdown'  
			 WHEN B.DeviceStatus =5 THEN 'Controlled Shutdown'
			 WHEN B.DeviceStatus =6 THEN 'Engine' 			
			 Else '-'
			 END END AS [Status],

			 DeviceStatus,	
			 B.LastLatitude, B.LastLongitude, ISNULL(CT.BoxMsgInTypeName,CTT.BoxMsgInTypeName)  as MessageDetails, h.CustomProp,--dbo.rvlf_fn_GetSensorMaskInformationCommand_New(B.LastSensorMask,B.BoxId,@Lang) as 'SensorDetails',
	CAST(B.LastLatitude as VARCHAR) + ',' + CAST(B.LastLongitude as VARCHAR) as LatLng,     
	CASE WHEN B.LastValidDateTime <> B.LastStatusDateTime THEN 
			 -1 
		 ELSE 
			 B.Heading 
		 END as Heading,

	--dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop, H.BoxMsgInTypeID, H.BoxId, h.MessageInID, h.OriginDateTime, @Lang) as MessageDetails,  
	--REPLACE((select mapitvalues from dbo.rvlf_Fn_GetMapItValues_New(B.BoxID,@bigQueryingUser,'M',@FleetID)), '''','\''') AS Mapitvalues,  
	 REPLACE(  
  --(select mapitvalues from dbo.rvlf_Fn_GetMapItValues_New(B.BoxID,@bigQueryingUser1,'M'))  
  ( 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 VT.VehicleTypeId =1  THEN 
			  CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) >= 480  THEN 'Offline' 
			  WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND (SUBSTRING(ISNULL(h.Digital_OP,'0000000000000000'),10,1)='1') THEN 'Running' 
		     WHEN B.DeviceStatus =1 THEN 'Information'   
		     WHEN B.DeviceStatus =2 THEN 'Warning'
			 WHEN B.DeviceStatus =3 THEN 'Electrical Trip'
			 WHEN B.DeviceStatus =4 THEN 'Shutdown'  
			 WHEN B.DeviceStatus =5 THEN 'Controlled Shutdown'
			 WHEN B.DeviceStatus =6 THEN 'Engine' 			
			 Else '-'
			 END 
			 ELSE CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) >= 480  THEN 'Offline' 
			  WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND 
			  (SUBSTRING(ISNULL(hh.Digital_IP,'0000000000000000'),9,1)='1' OR SUBSTRING(isnull(hh.Digital_IP,'0000000000000000'),8,1) ='1')
			   THEN 'Running' 
		     WHEN B.DeviceStatus =1 THEN 'Information'   
		     WHEN B.DeviceStatus =2 THEN 'Warning'
			 WHEN B.DeviceStatus =3 THEN 'Electrical Trip'
			 WHEN B.DeviceStatus =4 THEN 'Shutdown'  
			 WHEN B.DeviceStatus =5 THEN 'Controlled Shutdown'
			 WHEN B.DeviceStatus =6 THEN 'Engine' 			
			 Else '-'
			 END END) AS VARCHAR) 	                        
     + '~#~' + V.VehicleDescription  
     + '~#~' + ISNULL(ct.BoxMsgInTypeName,CTT.BoxMsgInTypeName)                          
     + '~#~' + '-'  + '~#~' + '-'                          
     + '~#~' + '-'     
     + '~#~' + '-'                             
     + '~#~' +  (Case WHEN @Lang='LanguageArNew' THEN N'اتصل'            
       When @Lang='LanguageHindi' THEN N'संपर्क'             
    ELSE 'Contact' END)+ '~#~' + '-'            
  )    
  , '''','\''')AS Mapitvalues,  
	
	 '' AS Notcurposveh, 
	(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, B.BoxArmed,0 as OdometerValues, 0 AS IsSetOdometer, '' as TotDuration,' ' AS LandMarkvalues, ' ' AS LandMarkIds, NULL AS FuelStatus, 4 as IsTop, 2 as IgnitionStatus, ''  as Distance, '-' AS Landmark, '' as LandMarkID,'' 



as LandmarkName,'' as Latitude,'' as Longitude,'' as Radius,''  as LandmarkAddress,0 as LastSpeed,@SpeedUnit as Units,Odometer =  0,'' as 'SensorDetails',

 1 AS NonReportingVehicles,
 CASE WHEN DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN 
				'1' 
			 ELSE 
				'0'
			END AS IsOnline,
			CASE WHEN VT.VehicleTypeId =1  THEN 
			  CASE  WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND SUBSTRING(ISNULL(h.Digital_OP,'0000000000000000'),10,1)='1' THEN '~/Images/Running_Gen.png'  
			  WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN '~/Images/Information_Gen.png'			  			 
		        WHEN B.DeviceStatus =2 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN '~/Images/Warning_Gen.png'
			    WHEN B.DeviceStatus =3 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN '~/Images/ElectricalTrip_Gen.png'
			    WHEN B.DeviceStatus =4 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN '~/Images/Shutdown_gen.png'  
			    WHEN B.DeviceStatus =5 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN '~/Images/ControlledShutdown_gen.png'
			    WHEN B.DeviceStatus =6 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN '~/Images/Engine_Gen.png' 
			  Else '~/Images/Gen.png'
			 END 
			 ELSE CASE 
			  WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 AND  SUBSTRING(hh.Digital_IP,9,1)='1' OR SUBSTRING(hh.Digital_IP,8,1) ='1' THEN '~/Images/Running_S.png'  	
			 WHEN B.DeviceStatus =1 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN '~/Images/Information_S.png'  	
				 
		       WHEN B.DeviceStatus =2 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN '~/Images/Warning_S.png'
			   WHEN B.DeviceStatus =3 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN '~/Images/ElectricalTrip_S.png'
			   WHEN B.DeviceStatus =4 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN '~/Images/Shutdown_S.png'  
			   WHEN B.DeviceStatus =5 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN '~/Images/ControlledShutdown_S.png'
			   WHEN B.DeviceStatus =6 AND DATEDIFF(SECOND,B.LastStatusDateTime,GETUTCDATE()) <= 480 THEN '~/Images/Engine_S.png'
			 Else '~/Images/S1.png'
			 END END AS StatusImg
	FROM rvlfMAKDevices MD 
	inner join rvlfVehicle V on md.VehicleId=v.VehicleId     
	INNER JOIN rvlfFleetVehicles RFV ON MD.VehicleId = RFV.vehicleId
	INNER JOIN rvlfVehicleAssignment va ON va.VehicleId = V.VehicleId
	INNER JOIN rvlfBoxID B ON B.BoxID = MD.BoxId         
	LEFT OUTER JOIN rvlfMsgInHst_Techno h ON h.MessageInID = B.MessageInID
	LEFT OUTER JOIN rvlfMsgInHst_Techno_355 hh ON hh.MessageInID =B.MessageInId
	LEFT OUTER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId
	LEFT OUTER JOIN rvlfBoxMsgInType CTT ON hh.BoxMsgInTypeId = CTT.BoxMsgInTypeId	
	LEFT OUTER JOIN rvlfVehicleType VT On MD.SubTypeId = VT.VehicleTypeId                                        
	LEFT OUTER JOIN rvlfCustomers C On MD.CustomerId = C.CustomerId	
	WHERE (@FleetID IS NULL OR @FleetID = '' OR (RFV.FleetId = @FleetID)) and B.OrganizationID=@bigOrganizationID                                   
	AND (@bigVehicleId IS NULL or @bigVehicleId = '' OR MD.VehicleId= @bigVehicleId)  
	--and (@CustomerID IS NULL or @CustomerID = '' or @CustomerID = 0 OR MD.CustomerId= @CustomerID)
	ORDER BY b.LastStatusDateTime  desc
   
	SELECT null AS LandmarkEntries

	--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
 -- 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 = @bigVehicleId  and Md.IsDelete= 0 

  SELECT md.BoxId,v.VehicleId,V.VehicleDescription,v.VehicleTypeId,vt.VehicleTypeName, C.CompType,    
   C.CompModel,CASE WHEN C.IsVentilator =1 THEN '1' ELSE '0' END AS IsVentilator,C.VentilatorModel ,C.SeqNo, Md.VFantype AS NoofFan
  FROM  rvlfMAKDevices Md 
   inner join rvlfVehicleAssignment VA ON VA.BoxId = Md.BoxId
   Inner join rvlfVehicle V ON V.VehicleId = VA.VehicleId
   inner join rvlfVehicleType vt on vt.VehicleTypeId = V.VehicleTypeId 
   Left outer join rvlf_CompactorDetails c on c.DeviceId = Md.BoxId
   WHERE V.VehicleId = @bigVehicleId  and Md.IsDelete= 0 
                                      
END


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetVehicleByFleetID_MApp]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_GetVehicleByFleetID_MApp]
@bigQueryingUser int,
@bigFleetId bigint,
@From tinyint,
@To tinyint,
@OrgCode varchar(3)
AS
/******************************************************************************/        
-- Name  : RVLT_SP_GetVehicleByFleetID_MApp 94,8,1,5,'int'
-- Description : To get the vehicle details for monitor        
-- Author  : SAKTHI GOPINATH S
-- Company  : Angler Technologies        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason        
/******************************************************************************/ 
BEGIN
SET NOCOUNT ON

	IF EXISTS (SELECT 1 FROM rvlfUser WHERE UserId=@bigQueryingUser)
	BEGIN
		--DECLARE THE VARIABLES FOR GET THE TIMEZONE DETAILS    
		DECLARE @HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0

		SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded FROM rvlfUserPreferences up     
		INNER JOIN rvlfTimeZones tz ON up.TimeZoneId = tz.TimeZoneId        
		WHERE UP.UserId  = @bigQueryingUser
		
		SELECT '1' AS [Status]

		SELECT a.* FROM 
		(SELECT ROW_NUMBER()OVER(ORDER BY v.VehicleId) Sno,
		v.VehicleId,v.VehicleDescription,b.LastLatitude,b.LastLongitude,ISNULL(b.LastStreetAddress,'N/A') AS StreetAddress,
		REPLACE(CONVERT(VARCHAR,DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,B.LastValidDateTime)),102),'.','-')+ 
		' ' + CONVERT(VARCHAR,CAST(DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,B.LastValidDateTime))AS TIME),22) as [DateTime],
		dbo.rvlf_fn_GetAlarmDetails(H.customprop,H.BoxMsgInTypeID, H.BoxId, h.MessageInID, h.OriginDateTime) as MessageDetails,
		CASE WHEN B.LastValidDateTime = B.LastStatusDateTime THEN 1 ELSE 0 END as IsCurrent FROM rvlfBoxId b 
		INNER JOIN rvlfMsgInHst h ON h.MessageInID=b.MessageInId
		INNER JOIN rvlfOrganization o ON o.OrganizationId=b.OrganizationId
		INNER JOIN rvlfVehicleAssignment va ON va.BoxId=b.BoxId
		INNER JOIN rvlfVehicle v ON v.VehicleId=va.VehicleId
		INNER JOIN rvlfFleetVehicles fv ON fv.VehicleId=v.VehicleId
		WHERE o.OrganizationCode=@OrgCode AND fv.FleetId=@bigFleetId) a WHERE a.Sno BETWEEN @From AND @To
	END
	ELSE
	BEGIN
		SELECT '0' AS [Status]
	END
	
SET NOCOUNT OFF
END

GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetVehicleByFleetID_PhoneGap]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[RVLT_SP_GetVehicleByFleetID_PhoneGap](                      
@FleetID bigint=null,                      
@bigQueryingUser bigint = 0,                      
@bigVehicleId bigint = null,                      
@bigOrganizationID bigint =NULL                      
)                                      
AS                         
/******************************************************************************/                      
-- Name  : RVLT_SP_GetVehicleByFleetID_PhoneGap 176,18,null,86
-- Description : To get the vehicle details for monitor                      
-- Author  : T. Sathish Kumar                      
-- Company  : Angler Technologies                      
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason                      
--    : 07-Nov-2009 MJJC Updated to have the sensor mask details and vehicle search  
/******************************************************************************/                                   
BEGIN                      
 --DECLARE THE VARIABLES FOR GET THE TIMEZONE DETAILS                  
 DECLARE @HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@SpeedUnit varchar(50),@DefaultDateFormat INT = 0,@ConversionFactor numeric (10,2) = 1.0                          
 DECLARE @Lang varchar(50),  @LangSetting varchar(20)                   
 SELECT @HoursToBeAdded = tz.HoursToBeAdded, @MinsToBeAdded = tz.MinToBeAdded, @ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                      
		@SpeedUnit = CASE WHEN up.Distance = 0 THEN 'MPH' ELSE 'KMPH' 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
           
 SELECT 
 row_number() over (order by RV.VehicleDescription) as AutoNocolumn,  
 RV.VehicleID, B.BoxID as DeviceID, RV.VehicleDescription, 
  Replace(ISNULL(B.LastStreetAddress,'Address is not resolved'),'''','\''') AS Address, B.BoxArmed,                  
 0 as LastSpeed,                        
 OriginDateTime = dbo.rvlf_fn_DayLightSavings(B.LastStatusDateTime,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,isnull(h.OriginDateTime,HH.OriginDateTime)),           
 CONVERT(varchar(max),DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,B.LastStatusDateTime)),21) as OriginDateTimeSort,                  
  CASE WHEN DATEDIFF(MINUTE,B.LastStatusDateTime,GETUTCDATE()) > 10 THEN 'Offline' ELSE 'Online' END AS [Status],
  @SpeedUnit as Units, B.LastLatitude, B.LastLongitude,  
 isnull(ct.BoxMsgInTypeName,ctt.BoxMsgInTypeName) as MessageDetails,                        
  '' AS Mapitvalues,                 
 ' ' AS LandMarkvalues,                  
 ' ' AS LandMarkIds,                  
 '' AS Notcurposveh,   
 (case	when B.LastLatitude IS NOT NULL and B.LastLongitude IS NOT NULL and 
		B.LastStreetAddress not like 'N/A' and B.LastStreetAddress not like '%Address could not be Resolved!%'  
		then 1 else 0 end) as isMapIT,  
 (Case when (DATEDIFF(DD,isnull(h.OriginDateTime,hh.OriginDateTime),GETUTCDATE())) > 1 then 0 else 1 end) as VehActiveStatus, VT.VehicleTypeName AS ControllerType,VT.VehicleTypeId as ControllerID,
 F.FleetName SiteName1, F.PowerPlantRating RatingOfPlant, F.RatingOfHVREquip RatingOfTRSets, 
 0 as NoOfTRSets, c.CustomerName,  
 ISNULL((SELECT FleetName FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From rvlfFleetVehicles Where VehicleId = RV.VehicleId and FleetId <> 176)), '-') as SiteName,MD.CustomerId
 FROM rvlfVehicle RV                   
 INNER JOIN rvlfFleetVehicles RFV ON RV.VehicleId = RFV.vehicleId                   
 INNER JOIN rvlfFleet F ON F.FleetId = RFV.FleetId 
 INNER JOIN rvlfVehicleAssignment RVA ON RVA.VehicleId = RFV.VehicleId              
 INNER JOIN rvlfBoxID B ON B.BoxID = RVA.BoxId    
 
 LEFT OUTER JOIN rvlfMsgInHst_Techno h ON h.MessageInID = B.MessageInID
	LEFT OUTER JOIN rvlfMsgInHst_Techno_355 hh ON hh.MessageInID =B.MessageInId
	LEFT OUTER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId
	LEFT OUTER JOIN rvlfBoxMsgInType CTT ON hh.BoxMsgInTypeId = CTT.BoxMsgInTypeId	
	
 INNER JOIN rvlfMAKDevices MD ON MD.VehicleId = RV.VehicleId
 LEFT OUTER JOIN rvlfVehicleType VT On RV.VehicleTypeId = VT.VehicleTypeId                                        
  LEFT OUTER JOIN rvlfCustomers C On MD.CustomerId = C.CustomerId
 WHERE (@FleetID IS NULL OR @FleetID = '' OR (RFV.FleetId = @FleetID))
 AND (@bigVehicleId IS NULL or @bigVehicleId = '' OR rv.VehicleId= @bigVehicleId)
 AND RV.OrganizationId = @bigOrganizationID
 ORDER BY h.OriginDateTime desc                   
END
GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetVehicleByFleetID_test]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
 CREATE  PROCEDURE [dbo].[RVLT_SP_GetVehicleByFleetID_test](           
@FleetID bigint=null,                                        
@bigQueryingUser bigint = 0,                                        
@bigVehicleId bigint = null,                                        
@bigOrganizationID bigint =NULL                                        
)                                                        
AS                                           
/******************************************************************************/                                        
-- Name  : RVLT_SP_GetVehicleByFleetID_test 176,453,null,86                          
-- Description : To get the vehicle details for monitor                                        
-- Author  : T. Sathish Kumar                                        
-- Company  : Angler Technologies                                        
-- History  : <<Date(dd-MON-yyyy)>> Initial Reason  
/******************************************************************************/                                                     
BEGIN 

if @bigOrganizationID Is null              
set @bigOrganizationID=(select organizationID from rvlfFleet where FleetId=@FleetID)              
 
 --DECLARE THE VARIABLES FOR GET THE TIMEZONE DETAILS                                    
 DECLARE @HoursToBeAdded INT = 0,@MinsToBeAdded INT = 0,@SpeedUnit varchar(50),@DefaultDateFormat INT = 0,@ConversionFactor numeric (10,2) = 1.0                                            
 DECLARE @Lang varchar(50),  @LangSetting varchar(20)                                     
 SELECT @HoursToBeAdded = tz.HoursToBeAdded,@MinsToBeAdded = tz.MinToBeAdded,--@ConversionFactor = CASE WHEN up.Distance = 0 THEN 0.62 ELSE 1.0 END,                                        
   --@SpeedUnit = CASE WHEN up.Distance = 0 THEN 'MPH' ELSE 'KMPH' 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   
  
 -------------------------------GET THE VEHICLES BASED ON THE FLEET ----------------------------------------------              

 SELECT h.MessageInID,MD.VehicleID,B.BoxID as DeviceID,Md.EquipmentName as VehicleDescription,
 VT.VehicleTypeName AS ControllerType, C.CustomerName, 
   ISNULL((SELECT FleetName FROM rvlfFleet WHERE FleetId = (Select top 1 FleetId From rvlfFleetVehicles Where VehicleId = MD.VehicleId
  and FleetId <> 176)), 'Site Not Assigned') as SiteName,ISNULL(ADR.ControllerName,'-') AS ControllerName ,ADR.ControllerPositionID,adr.dcsimid
  , Replace(ISNULL((Case WHEN @Lang='LanguageArNew' and @LangSetting like '%3%' THEN ISNULL(B.LastStreetAddress_AR,B.LastStreetAddress)                         
 When @Lang='LanguageHindi' and @LangSetting like '%2%' THEN ISNULL(B.LastStreetAddress_Hin,B.LastStreetAddress)                         
 ELSE B.LastStreetAddress END),'Address is not resolved'),'''','\''') as StreetAddress, 
 Replace(ISNULL(B.LastStreetAddress ,'Address is not resolved'),'''','\''') AS Address,                    
  [DateTime] =dbo.rvlf_fn_DayLightSavings(GETDATE(),@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,B.LastValidDateTime),                                      
  CASE	WHEN B.LastLatitude = 0 AND B.LastLongitude = 0 AND B.LastValidDateTime = B.LastStatusDateTime THEN 0                            
		WHEN B.LastValidDateTime = B.LastStatusDateTime THEN 1 ELSE 0 END as IsCurrent,                                           
  OriginDateTime = dbo.rvlf_fn_DayLightSavings(B.LastStatusDateTime,@bigQueryingUser,@HoursToBeAdded,@MinsToBeAdded,@DefaultDateFormat,OriginDateTime),                             
  DATEADD(n,@MinsToBeAdded,DATEADD(hh,@HoursToBeAdded,B.LastStatusDateTime)) as OriginDateTimeSort,H.BoxMsgInTypeId,                                    
  CASE	WHEN H.Alarm=1 THEN 'Alarm' ELSE (CASE WHEN DATEDIFF(HH,B.LastStatusDateTime,GETUTCDATE()) > 1 THEN 'Offline' ELSE 'Online' END) END AS [Status],
  B.LastLatitude, B.LastLongitude,ct.BoxMsgInTypeName as MessageDetails, h.CustomProp,
  --dbo.rvlf_fn_GetSensorMaskInformationCommand_New(B.LastSensorMask,B.BoxId,@Lang) as 'SensorDetails',
   CAST(B.LastLatitude as VARCHAR) + ',' + CAST(B.LastLongitude as VARCHAR) as LatLng,                                
   CASE WHEN B.LastValidDateTime <> B.LastStatusDateTime THEN -1 ELSE B.Heading END as Heading,
  --dbo.rvlf_fn_GetAlarmDetails_Optimzd(H.customprop, H.BoxMsgInTypeID, H.BoxId, h.MessageInID, h.OriginDateTime, @Lang) as MessageDetails,  
  REPLACE((select mapitvalues from dbo.rvlf_Fn_GetMapItValues_New(B.BoxID,@bigQueryingUser,'M',@FleetID)), '''','\''') AS Mapitvalues,  
  REPLACE((select Notcurposveh from dbo.rvlf_Fn_GetMapItValues(B.BoxID,@bigQueryingUser,'P')), '''','\''') AS Notcurposveh,                    
  (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,          
   B.BoxArmed,0 as OdometerValues, 0 AS IsSetOdometer,'' as TotDuration,' ' AS LandMarkvalues,  ' ' AS LandMarkIds, 
  NULL AS FuelStatus, 4 as IsTop,2 as IgnitionStatus,  H.NearestLandMark as Distance,'-' AS Landmark,
  '' as LandMarkID, '' as LandmarkName, '' as Latitude, '' as Longitude,'' as Radius, ''  as LandmarkAddress,0 as LastSpeed,@SpeedUnit as Units,Odometer =  0
  ,'' as 'SensorDetails'
   FROM rvlfMAKDevices MD                                     
    INNER JOIN rvlfFleetVehicles RFV ON MD.VehicleId = RFV.vehicleId
    --INNER JOIN rvlfFleet F ON RFV.FleetId = F.FleetId
   -- INNER JOIN rvlfVehicleAssignment RVA ON RVA.VehicleId = RFV.VehicleId
    INNER JOIN rvlfBoxID B ON B.BoxID = MD.BoxId                        
    INNER JOIN rvlfMsgInHst h ON h.MessageInID = B.MessageInId --AND h.ControllerID =B.ControllerID   
    INNER JOIN rvlfBoxMsgInType CT ON h.BoxMsgInTypeId = CT.BoxMsgInTypeId
	--INNER JOIN rvlfMAKDevices MD ON MD.VehicleId = RV.VehicleId
	LEFT OUTER JOIN rvlfVehicleType VT On MD.SubTypeId = VT.VehicleTypeId                                        
	LEFT OUTER JOIN rvlfCustomers C On MD.CustomerId = C.CustomerId
	LEFT OUTER join adrControllerMaster ADR ON ADR.EquipmentId = B.BoxId AND (ADR.ControllerPositionId = b.ControllerId) AND ADR.MessageInID = h.MessageINID AND ADR.IsDeleted=0
   WHERE (@FleetID IS NULL OR @FleetID = '' OR (RFV.FleetId = @FleetID)) and B.OrganizationID=@bigOrganizationID                                   
   AND (@bigVehicleId IS NULL or @bigVehicleId = '' OR MD.VehicleId= @bigVehicleId)
                  
   ORDER BY h.OriginDateTime  desc 
   
  SELECT null AS LandmarkEntries                  
                                      
END



GO
/****** Object:  StoredProcedure [dbo].[rvlt_sp_GetWOStatistics]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE  PROCEDURE [dbo].[rvlt_sp_GetWOStatistics]          
(
	 @bigQueryingUser bigint = Null ,
	  @bigOrganizationId bigint = Null                   
)              
AS              
/****************************************************************************************************************/              
-- Name           : rvlt_sp_GetWOStatistics     328,6
-- Description    : To Add or Update or view the WO Approval
-- Author         : Ranjith N
-- Created Date   : 10-Dec-15              
/****************************************************************************************************************/              
BEGIN              
          
 --SELECT isnull(SUM(1),0) as WOTotal,  
 --isnull(SUM(CASE WHEN [Status] =1 THEN 1 ELSE 0 END),0) as WOGenerationTotal,    
 --isnull(SUM(CASE WHEN [Status] =2 THEN 1 ELSE 0 END),0)  as WOApprovedTotal,  
 --isnull(SUM(CASE WHEN [Status] =3 THEN 1 ELSE 0 END),0)  as WORedoTotal,  
 --isnull( SUM(CASE WHEN [Status] =4 THEN 1 ELSE 0 END),0)  as WORejectedTotal, 
 -- isnull(SUM(CASE WHEN [Status] =5 THEN 1 ELSE 0 END),0)  as WOClosedTotal, 
 --isnull( SUM(CASE WHEN [Status] =6 THEN 1 ELSE 0 END),0)  as WOReopenedTotal
 -- From rvlfWOGeneration
 -- WHERE   (CreatedBY = @bigQueryingUser or (@bigQueryingUser is null) or (@bigQueryingUser = ''))   and   
 --  OrganizationId = @bigOrganizationID    and IsDelete = 0


Select (WOGenerationTotal + WOApprovedTotal + WORedoTotal + WORejectedTotal + WOClosedTotal + WOReopenedTotal + WOPendingApproval+ WOPendingClosing) as WOTotal,* from(
 SELECT
  (select  isnull(count (distinct WONO),0) from rvlfWOGeneration w  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = w.VehiclePlanId
   where OrganizationId = @bigOrganizationID  and (CreatedBY =  @bigQueryingUser or (@bigQueryingUser is null) or (@bigQueryingUser = ''))
  and [Status] = 1 and  IsDelete = 0)  as WOGenerationTotal,  

(select  isnull(count (distinct WONO),0) from rvlfWOGeneration w  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = w.VehiclePlanId
where OrganizationId = @bigOrganizationID  and  [Status] = 2 and  IsDelete = 0 and WONO in (
 (select  distinct WONO from rvlfWOApproval where  [StatusType] = 2 and (ApprovedBy = @bigQueryingUser or (@bigQueryingUser is null) or (@bigQueryingUser = '')) )))  as WOApprovedTotal,  

(select  isnull(count (distinct WONO),0) from rvlfWOGeneration w  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = w.VehiclePlanId
where OrganizationId = @bigOrganizationID  and  [Status] = 3 and  IsDelete = 0 and WONO in (
 (select  distinct WONO from rvlfWOApproval where  [StatusType] = 3 and (ApprovedBy = @bigQueryingUser or (@bigQueryingUser is null) or (@bigQueryingUser = '')) )))   as WORedoTotal,  

(select  isnull(count (distinct WONO),0) from rvlfWOGeneration w  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = w.VehiclePlanId
where OrganizationId = @bigOrganizationID  and  [Status] = 4 and  IsDelete = 0 and WONO in (
 (select  distinct WONO from rvlfWOApproval where  [StatusType] = 4 and (ApprovedBy = @bigQueryingUser or (@bigQueryingUser is null) or (@bigQueryingUser = '')) )))   as WORejectedTotal, 

(select  isnull(count (distinct WONO),0) from rvlfWOGeneration w  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = w.VehiclePlanId
 where OrganizationId = @bigOrganizationID  and  [Status] = 5 and  IsDelete = 0 and WONO in (
 (select  distinct WONO from rvlfWOClosure where  [StatusType] = 5 and (ClosedBy = @bigQueryingUser or (@bigQueryingUser is null) or (@bigQueryingUser = '')) )))  as WOClosedTotal, 

(select  isnull(count (distinct WONO),0) from rvlfWOGeneration w  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = w.VehiclePlanId
 where OrganizationId = @bigOrganizationID  and  [Status] = 6 and  IsDelete = 0 and WONO in (
 (select  distinct WONO from rvlfWOClosure where  [StatusType] = 6 and (ClosedBy = @bigQueryingUser or (@bigQueryingUser is null) or (@bigQueryingUser = '')) )))   as WOReopenedTotal,

 (select  isnull(count (distinct WONO),0) from rvlfWOGeneration w  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = w.VehiclePlanId
  where OrganizationId = @bigOrganizationID  and  [Status] = 1 and  IsDelete = 0 and WONO in (
 (select  distinct WONO from rvlfWOGeneration where (AssignedTo = @bigQueryingUser or (@bigQueryingUser is null) or (@bigQueryingUser = '')) )))   as WOPendingApproval,

 (select  isnull(count (distinct WONO),0) from rvlfWOGeneration w  INNER JOIN rvlfVehiclePlanAssignment vp ON vp.VehiclePlanId = w.VehiclePlanId
  where OrganizationId = @bigOrganizationID  and  [Status] = 2 and  IsDelete = 0 and WONO in (
 (select  distinct WONO from rvlfWOApproval where (AssignedTo = @bigQueryingUser or (@bigQueryingUser is null) or (@bigQueryingUser = '')) )))   as WOPendingClosing) as A
        
END   
  
  


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_SelectAllFleets]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE PROCEDURE [dbo].[RVLT_SP_SelectAllFleets]  
/******************************************************  
Stored Procedure Name : RVLT_SP_SelectAllFleets 1,null,18
Purpose     : Retrieve fleet details  
Created by    : N.Uma Maheswari  
Created date   : 09-Jul-09  
Updated by    : Uma  
Updated date   : 15-Jul-09, excluded   
     17-Sep-2009 Jaya Chitra Included the Email and SMS list 
      : 07-Dec-2013 Kapilraj Included Arabic Language & Hindi for Severity 
*******************************************************/   
  
   @FleetID  int = null,  
   @bigOrganizationId bigint = NULL,  
   @bigUserId bigint = NULL  
     
AS  
        
BEGIN  
  
   DECLARE @varGroupName AS Varchar(30)  
   DECLARE @varUserName AS Varchar(30)  
   DECLARE @bigUserGroupId bigint  
  
       
   DECLARE @Lang varchar(50)         
   
	select @Lang=isnull(Lang,'LanguageEn') from rvlfUserPreferences where UserId = @bigUserId 
    
    
  
   SELECT @varGroupName = ug.UserGroupName, @varUserName = u.UserName,@bigUserGroupId=ug.UserGroupId  FROM rvlfUser u  
   INNER JOIN rvlfUserGroupAssignment uga ON uga.UserId = u.UserId  
   INNER JOIN rvlfUserGroup ug ON ug.UserGroupId = uga.UserGroupId  
   WHERE u.UserId = @bigUserId  
  
   IF(@varUserName = 'Administrator' OR @varGroupName = 'Angler Admin' OR @bigUserId = 0 OR @bigUserGroupId=35)  
 BEGIN  
  
  SET @bigUserId = NULL  
  
 END  
  
 SELECT fl.FleetId,fl.FleetName,fl.OrganizationId,fl.Description,REPLACE(fl.Email,';','; ') as Email,REPLACE(fl.SMS,';','; ') as SMS,fl.TimeZone,fl.DayLightSaving,fl.Notify,fl.Warning,fl.Critical,  
 fl.AutoAdjustDayLightSaving,  
case when  
     (case when fl.Notify='true' then (case when @Lang='LanguageArNew' THEN N'معلومة' when @Lang='LanguageHindi' THEN N'सूचित करना'  else  'Notify' end) else '' end +    
    case when fl.Warning='true' then (case when @Lang='LanguageArNew' THEN N'تحذير' when @Lang='LanguageHindi' THEN N'चेतावनी'  else  'Warning' end) else '' end +   
    case when fl.Critical='true' then (case when @Lang='LanguageArNew' THEN N'خطير' when @Lang='LanguageHindi' THEN N'आलोचनात्मक'  else  'Critical' end) else '' end)='' 
    then (case when @Lang='LanguageArNew' THEN N'لا تنبيه' when @Lang='LanguageHindi' THEN N'कोई अलार्म' else  'No Alarm' end)  else  
    (case  when fl.Notify='true' then (case when (fl.Warning='true' or fl.Critical='true') then (case when @Lang='LanguageArNew' THEN N'معلومة;' when @Lang='LanguageHindi' THEN N'सूचित करना;'  else  'Notify;' end) else (case when @Lang='LanguageArNew' 
	THEN N'معلومة' when @Lang='LanguageHindi' THEN N'सूचित करना'  else  'Notify' end) end ) else '' end +  
    case when fl.Warning='true' then (case when fl.Critical='true' then (case when @Lang='LanguageArNew' THEN N'تحذير;' when @Lang='LanguageHindi' THEN N'चेतावनी;'  else  'Warning;' end) else (case when @Lang='LanguageArNew' THEN N'تحذير' when @Lang='Lang
uageHindi' THEN N'चेतावनी'  else  'Warning' end) end ) else '' end +   
    case when fl.Critical='true' then (case when @Lang='LanguageArNew' THEN N'خطير' when @Lang='LanguageHindi' THEN N'आलोचनात्मक'  else  'Critical' end) else '' end)  
    end as Severity,  
    CASE   
  WHEN EXISTS(SELECT F.FleetId FROM rvlfFleetVehicles F WHERE F.FleetId = fl.FleetId)   
   OR EXISTS(SELECT U.FleetId FROM rvlfFleetUsers U WHERE U.FleetId = fl.FleetId)   
  THEN 1 ELSE 0 END  
  AS AssignedStatus,   
    ISNULL(dbo.rvlf_fn_GetNotificationsList(3, fl.fleetid, 1,1,0),'') as EmailList,   
    ISNULL(dbo.rvlf_fn_GetNotificationsList(3, fl.fleetid, 0,1,0),'') as SMSList,  
    REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(3, fl.fleetid, 1,0,1),''),',',', ') as EmailUserNameList,  
    REPLACE(ISNULL(dbo.rvlf_fn_GetNotificationsList(3, fl.fleetid, 0,0,1),''),',',', ') as SMSUserNameList,  
    fl.IsDefault, PowerPlantRating, RatingOfHVREquip, ControllerType  
      
 FROM rvlfFleet fl WHERE fl.FleetId <> 335 AND  
 --((@FleetID is null AND @bigUserId IS NULL) or (@FleetID = 0 AND @bigUserId IS NULL) OR ((@FleetID IS NULL OR @FleetID = '' OR @FleetID = 0) AND @bigUserId IS NOT NULL AND fl.FleetId IN (SELECT fu.FleetId FROM rvlfFleetUsers fu WHERE 
 --fu.FleetId = fl.FleetId AND fu.UserId = @bigUserId)) or (fl.FleetId=@FleetID AND @bigUserId IS NULL)) AND  
   (@FleetID IS NULL OR @FleetID='' OR @FleetID = 0 or fl.FleetId = @FleetID) AND  
  (@bigUserId IS NULL OR @bigUserId='' OR @bigUserId = 0 or 
  fl.FleetId IN (SELECT fu.FleetId FROM rvlfFleetUsers fu WHERE fu.FleetId = fl.FleetId AND fu.UserId = @bigUserId)) AND  
 ((@bigOrganizationId is null OR @bigOrganizationId = '') or (fl.OrganizationId = @bigOrganizationId))  
 ORDER BY fl.FleetName ASC  
          
END   
-- RVLT_SP_SelectAllFleets 8,null,null  
  
   
GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_SelectAllFleetsgso]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_SelectAllFleetsgso]     
/******************************************************    
Stored Procedure Name : RVLT_SP_SelectAllFleetsgso
Purpose     : Retrieve fleet details
Created by    : N.Uma Maheswari    
Created date   : 09-Jul-09    
Updated by    :    
Updated date   :    
*******************************************************/    
 
-- @UserID		int	= Null
       
AS  
   
BEGIN     
     
 Select * from rvlfFleet 
    
END


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_UpdateAlarmsByID]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_UpdateAlarmsByID](@alarmID varchar(50),@value int)    
AS    
BEGIN    
DECLARE @Query varchar(1000)
SET @Query = ''
SET @Query = 'Update rvlfAlarm SET IsClosed = 1 where AlarmID in ('+@alarmID+')'

exec(@Query)
END  

-- RVLT_SP_UpdateAlarmsByID '1,2',1


GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_UpdateLandMarks]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RVLT_SP_UpdateLandMarks](@Landmarkname varchar(150),@Latitude varchar(20),@Longitude varchar(20),
												@Description varchar(500),@radius int,@Email varchar(200),
												@StreetAddress varchar(500))
AS
BEGIN
		
	Update rvlfLandMark Set Latitude = @Latitude,Longitude = @Longitude,Description = @Description,
	Radius = @radius, Email = @Email,StreetAddress = @StreetAddress where LandmarkName = @Landmarkname
		
END


GO
/****** Object:  StoredProcedure [dbo].[SearchAllTables]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[SearchAllTables]
(
        @SearchStr nvarchar(100)
)
AS
/*******************************************************************************************/
-- Name		: SearchAllTables
-- Author	: M. Jebamalai Jaya Chitra
-- Purpose	: In order to search all the tables in a specfic database in which this procedure 
--			  exists and get all the columns and the value matches with the given value
-- Company	: Angler Technologies
-- Date		: 10-Mar-2009
-- History	: 10-Mar-2009 MJJC Created the Procedure
/*******************************************************************************************/
BEGIN
        CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

        SET NOCOUNT ON

        DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
        SET  @TableName = ''
        SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

        WHILE @TableName IS NOT NULL
        BEGIN
                SET @ColumnName = ''
                SET @TableName =
                (
                        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
                        FROM         INFORMATION_SCHEMA.TABLES
                        WHERE                 TABLE_TYPE = 'BASE TABLE' 
                                AND        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                                AND        OBJECTPROPERTY(
                                                OBJECT_ID(
                                                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                                                         ), 'IsMSShipped'
                                                       ) = 0
                )

                WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
                BEGIN
                        SET @ColumnName =
                        (
                                SELECT MIN(QUOTENAME(COLUMN_NAME))
                                FROM         INFORMATION_SCHEMA.COLUMNS
                                WHERE                 TABLE_SCHEMA        = PARSENAME(@TableName, 2)
                                        AND        TABLE_NAME        = PARSENAME(@TableName, 1)
                                        AND        DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar','int')
                                        AND        QUOTENAME(COLUMN_NAME) > @ColumnName
                        )
        
                        IF @ColumnName IS NOT NULL
                        BEGIN
                                INSERT INTO #Results
                                EXEC
                                (
                                        'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                                        ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                                )
                        END
                END        
        END

        SELECT * FROM #Results
END


GO
/****** Object:  StoredProcedure [dbo].[sp_alterdiagram]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

	CREATE PROCEDURE [dbo].[sp_alterdiagram]
	(
		@diagramname 	sysname,
		@owner_id	int	= null,
		@version 	int,
		@definition 	varbinary(max)
	)
	WITH EXECUTE AS 'dbo'
	AS
	BEGIN
		set nocount on
	
		declare @theId 			int
		declare @retval 		int
		declare @IsDbo 			int
		
		declare @UIDFound 		int
		declare @DiagId			int
		declare @ShouldChangeUID	int
	
		if(@diagramname is null)
		begin
			RAISERROR ('Invalid ARG', 16, 1)
			return -1
		end
	
		execute as caller;
		select @theId = DATABASE_PRINCIPAL_ID();	 
		select @IsDbo = IS_MEMBER(N'db_owner'); 
		if(@owner_id is null)
			select @owner_id = @theId;
		revert;
	
		select @ShouldChangeUID = 0
		select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname 
		
		if(@DiagId IS NULL or (@IsDbo = 0 and @theId <> @UIDFound))
		begin
			RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1);
			return -3
		end
	
		if(@IsDbo <> 0)
		begin
			if(@UIDFound is null or USER_NAME(@UIDFound) is null) -- invalid principal_id
			begin
				select @ShouldChangeUID = 1 ;
			end
		end

		-- update dds data			
		update dbo.sysdiagrams set definition = @definition where diagram_id = @DiagId ;

		-- change owner
		if(@ShouldChangeUID = 1)
			update dbo.sysdiagrams set principal_id = @theId where diagram_id = @DiagId ;

		-- update dds version
		if(@version is not null)
			update dbo.sysdiagrams set version = @version where diagram_id = @DiagId ;

		return 0
	END
	
GO
/****** Object:  StoredProcedure [dbo].[sp_creatediagram]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

	CREATE PROCEDURE [dbo].[sp_creatediagram]
	(
		@diagramname 	sysname,
		@owner_id		int	= null, 	
		@version 		int,
		@definition 	varbinary(max)
	)
	WITH EXECUTE AS 'dbo'
	AS
	BEGIN
		set nocount on
	
		declare @theId int
		declare @retval int
		declare @IsDbo	int
		declare @userName sysname
		if(@version is null or @diagramname is null)
		begin
			RAISERROR (N'E_INVALIDARG', 16, 1);
			return -1
		end
	
		execute as caller;
		select @theId = DATABASE_PRINCIPAL_ID(); 
		select @IsDbo = IS_MEMBER(N'db_owner');
		revert; 
		
		if @owner_id is null
		begin
			select @owner_id = @theId;
		end
		else
		begin
			if @theId <> @owner_id
			begin
				if @IsDbo = 0
				begin
					RAISERROR (N'E_INVALIDARG', 16, 1);
					return -1
				end
				select @theId = @owner_id
			end
		end
		-- next 2 line only for test, will be removed after define name unique
		if EXISTS(select diagram_id from dbo.sysdiagrams where principal_id = @theId and name = @diagramname)
		begin
			RAISERROR ('The name is already used.', 16, 1);
			return -2
		end
	
		insert into dbo.sysdiagrams(name, principal_id , version, definition)
				VALUES(@diagramname, @theId, @version, @definition) ;
		
		select @retval = @@IDENTITY 
		return @retval
	END
	
GO
/****** Object:  StoredProcedure [dbo].[sp_dropdiagram]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

	CREATE PROCEDURE [dbo].[sp_dropdiagram]
	(
		@diagramname 	sysname,
		@owner_id	int	= null
	)
	WITH EXECUTE AS 'dbo'
	AS
	BEGIN
		set nocount on
		declare @theId 			int
		declare @IsDbo 			int
		
		declare @UIDFound 		int
		declare @DiagId			int
	
		if(@diagramname is null)
		begin
			RAISERROR ('Invalid value', 16, 1);
			return -1
		end
	
		EXECUTE AS CALLER;
		select @theId = DATABASE_PRINCIPAL_ID();
		select @IsDbo = IS_MEMBER(N'db_owner'); 
		if(@owner_id is null)
			select @owner_id = @theId;
		REVERT; 
		
		select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname 
		if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId))
		begin
			RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1)
			return -3
		end
	
		delete from dbo.sysdiagrams where diagram_id = @DiagId;
	
		return 0;
	END
	
GO
/****** Object:  StoredProcedure [dbo].[sp_helpdiagramdefinition]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

	CREATE PROCEDURE [dbo].[sp_helpdiagramdefinition]
	(
		@diagramname 	sysname,
		@owner_id	int	= null 		
	)
	WITH EXECUTE AS N'dbo'
	AS
	BEGIN
		set nocount on

		declare @theId 		int
		declare @IsDbo 		int
		declare @DiagId		int
		declare @UIDFound	int
	
		if(@diagramname is null)
		begin
			RAISERROR (N'E_INVALIDARG', 16, 1);
			return -1
		end
	
		execute as caller;
		select @theId = DATABASE_PRINCIPAL_ID();
		select @IsDbo = IS_MEMBER(N'db_owner');
		if(@owner_id is null)
			select @owner_id = @theId;
		revert; 
	
		select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname;
		if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId ))
		begin
			RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1);
			return -3
		end

		select version, definition FROM dbo.sysdiagrams where diagram_id = @DiagId ; 
		return 0
	END
	
GO
/****** Object:  StoredProcedure [dbo].[sp_helpdiagrams]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

	CREATE PROCEDURE [dbo].[sp_helpdiagrams]
	(
		@diagramname sysname = NULL,
		@owner_id int = NULL
	)
	WITH EXECUTE AS N'dbo'
	AS
	BEGIN
		DECLARE @user sysname
		DECLARE @dboLogin bit
		EXECUTE AS CALLER;
			SET @user = USER_NAME();
			SET @dboLogin = CONVERT(bit,IS_MEMBER('db_owner'));
		REVERT;
		SELECT
			[Database] = DB_NAME(),
			[Name] = name,
			[ID] = diagram_id,
			[Owner] = USER_NAME(principal_id),
			[OwnerID] = principal_id
		FROM
			sysdiagrams
		WHERE
			(@dboLogin = 1 OR USER_NAME(principal_id) = @user) AND
			(@diagramname IS NULL OR name = @diagramname) AND
			(@owner_id IS NULL OR principal_id = @owner_id)
		ORDER BY
			4, 5, 1
	END
	
GO
/****** Object:  StoredProcedure [dbo].[sp_permutate]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Proc [dbo].[sp_permutate] (@n smallint)
as
begin 
 set nocount on 
 declare @sqlStmt varchar(8000)
 declare @base varchar(1000)
 declare @list varchar(3000)
 declare @i int
 declare @j int

 /* set @base = '(' + 
	'SELECT 0 AS X, ' + '''' + 'A' + '''' + ' as Y ' + ' UNION ALL ' + 
	'SELECT 1 , ' + '''' + 'B' + '''' +  ' UNION ALL ' + 
	'SELECT 2 , ' + '''' + 'C' + '''' +  ' UNION ALL ' + 
	'SELECT 3 , ' + '''' + 'D' + '''' + ' UNION ALL ' + 
	'SELECT 4 , ' + '''' + 'E' + '''' + ' UNION ALL ' + 
	'SELECT 5 , ' + '''' + 'F' + '''' + ' UNION ALL ' + 
	'SELECT 6 , ' + '''' + 'G' + '''' + ' UNION ALL ' + 
	'SELECT 7 , ' + '''' + 'H' + '''' + ' UNION ALL ' + 
	'SELECT 8 , ' + '''' + 'I' + '''' + ' UNION ALL ' + 
	'SELECT 9 , ' + '''' + 'J' + '''' + ' UNION ALL ' + 
	'SELECT 10 , ' + '''' + 'K' + '''' + ' UNION ALL ' + 
	'SELECT 11 , ' + '''' + 'L' + '''' + ' UNION ALL ' + 
	'SELECT 12 , ' + '''' + 'M' + '''' + ' UNION ALL ' + 
	'SELECT 13 , ' + '''' + 'N' + '''' + ' UNION ALL ' + 
	'SELECT 14 , ' + '''' + 'O' + '''' +  
	' ) '
*/
set @base = '(' + 
	'SELECT EmployeeID AS X from rvlfEmployee UNION ALL ' + 
	'SELECT EmployeeID  from rvlfEmployee )'

 -- DO the select list
 set @i=1
 set @list = 'SELECT '
 while @i <= @n begin 
     SET @list = @list + 'T' + convert (varchar(2),@i) + '.X,'
     SET @i = @i + 1
 end

 set @list = substring (@list,1,len (@list)-1)
 set @list = @list + ' FROM ' 
 
 -- DO the FROM list
 set @sqlStmt = @list 
 set @i=1
  while @i <= @n begin 
     SET @sqlStmt = @sqlStmt + @base +' as T' + convert (varchar(2),@i) +' ,'
     SET @i = @i + 1
 end
 set @sqlStmt = substring (@sqlStmt,1,len (@sqlStmt)-1)

 -- DO first where clauses
 set @sqlStmt = @sqlStmt + ' WHERE ' 
 set @i=1
  while @i <= @n begin 
     SET @sqlStmt = @sqlStmt + 'T' + convert (varchar(2),@i) + 
	'.X < ' + convert (varchar(2),@n) + ' AND ' 
     SET @i = @i + 1
 end

 -- continue the WHERE clauses
 set @i=1
 while @i < @n begin 
     set @j = @i + 1 
     while @j <= @n begin 
       SET @sqlStmt = @sqlStmt + 'T' + convert (varchar(2),@i) + 
	'.X <> ' + 'T' + convert (varchar(2),@j) + '.X AND ' 
        SET @j = @j + 1
     end
     SET @i = @i + 1
 end
 set @sqlStmt = substring (@sqlStmt,1,len (@sqlStmt)-4) 

 print @sqlStmt
 exec (@sqlStmt)

 set nocount off
end


GO
/****** Object:  StoredProcedure [dbo].[sp_renamediagram]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

	CREATE PROCEDURE [dbo].[sp_renamediagram]
	(
		@diagramname 		sysname,
		@owner_id		int	= null,
		@new_diagramname	sysname
	
	)
	WITH EXECUTE AS 'dbo'
	AS
	BEGIN
		set nocount on
		declare @theId 			int
		declare @IsDbo 			int
		
		declare @UIDFound 		int
		declare @DiagId			int
		declare @DiagIdTarg		int
		declare @u_name			sysname
		if((@diagramname is null) or (@new_diagramname is null))
		begin
			RAISERROR ('Invalid value', 16, 1);
			return -1
		end
	
		EXECUTE AS CALLER;
		select @theId = DATABASE_PRINCIPAL_ID();
		select @IsDbo = IS_MEMBER(N'db_owner'); 
		if(@owner_id is null)
			select @owner_id = @theId;
		REVERT;
	
		select @u_name = USER_NAME(@owner_id)
	
		select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname 
		if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId))
		begin
			RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1)
			return -3
		end
	
		-- if((@u_name is not null) and (@new_diagramname = @diagramname))	-- nothing will change
		--	return 0;
	
		if(@u_name is null)
			select @DiagIdTarg = diagram_id from dbo.sysdiagrams where principal_id = @theId and name = @new_diagramname
		else
			select @DiagIdTarg = diagram_id from dbo.sysdiagrams where principal_id = @owner_id and name = @new_diagramname
	
		if((@DiagIdTarg is not null) and  @DiagId <> @DiagIdTarg)
		begin
			RAISERROR ('The name is already used.', 16, 1);
			return -2
		end		
	
		if(@u_name is null)
			update dbo.sysdiagrams set [name] = @new_diagramname, principal_id = @theId where diagram_id = @DiagId
		else
			update dbo.sysdiagrams set [name] = @new_diagramname where diagram_id = @DiagId
		return 0
	END
	
GO
/****** Object:  StoredProcedure [dbo].[sp_upgraddiagrams]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

	CREATE PROCEDURE [dbo].[sp_upgraddiagrams]
	AS
	BEGIN
		IF OBJECT_ID(N'dbo.sysdiagrams') IS NOT NULL
			return 0;
	
		CREATE TABLE dbo.sysdiagrams
		(
			name sysname NOT NULL,
			principal_id int NOT NULL,	-- we may change it to varbinary(85)
			diagram_id int PRIMARY KEY IDENTITY,
			version int,
	
			definition varbinary(max)
			CONSTRAINT UK_principal_name UNIQUE
			(
				principal_id,
				name
			)
		);


		/* Add this if we need to have some form of extended properties for diagrams */
		/*
		IF OBJECT_ID(N'dbo.sysdiagram_properties') IS NULL
		BEGIN
			CREATE TABLE dbo.sysdiagram_properties
			(
				diagram_id int,
				name sysname,
				value varbinary(max) NOT NULL
			)
		END
		*/

		IF OBJECT_ID(N'dbo.dtproperties') IS NOT NULL
		begin
			insert into dbo.sysdiagrams
			(
				[name],
				[principal_id],
				[version],
				[definition]
			)
			select	 
				convert(sysname, dgnm.[uvalue]),
				DATABASE_PRINCIPAL_ID(N'dbo'),			-- will change to the sid of sa
				0,							-- zero for old format, dgdef.[version],
				dgdef.[lvalue]
			from dbo.[dtproperties] dgnm
				inner join dbo.[dtproperties] dggd on dggd.[property] = 'DtgSchemaGUID' and dggd.[objectid] = dgnm.[objectid]	
				inner join dbo.[dtproperties] dgdef on dgdef.[property] = 'DtgSchemaDATA' and dgdef.[objectid] = dgnm.[objectid]
				
			where dgnm.[property] = 'DtgSchemaNAME' and dggd.[uvalue] like N'_EA3E6268-D998-11CE-9454-00AA00A3F36E_' 
			return 2;
		end
		return 1;
	END
	
GO
/****** Object:  StoredProcedure [dbo].[StoredProcedure1]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[StoredProcedure1]
	/*
	(
	@parameter1 int = 5,
	@parameter2 datatype OUTPUT
	)
	*/
AS
	/* SET NOCOUNT ON */
	RETURN


GO
/****** Object:  StoredProcedure [dbo].[tsp_TestBulKInsert]    Script Date: 02/01/2022 04:05:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[tsp_TestBulKInsert]
  (
   @xmlReviewComments VARCHAR(MAX) 
  )
AS
/*******************************************************************************/
--	Name		: tsp_TestBulKInsert
--	Description	: To perform bulk insert in which the data is sent through XML.
--	Author		: M. Jebamalai Jaya Chitra.
--	Company		: Anlger Technologies
--	History		: <<Date>> <<Initial>> <<Purpose>>
--				: 27-Mar-2009 MJJC Created the procedure
/*******************************************************************************/
BEGIN
 DECLARE @index int

 EXEC sp_xml_preparedocument @index OUTPUT, @xmlReviewComments

 INSERT INTO MyTable
  (
    firstname ,
    lastname
  )
 SELECT firstname , lastname
 FROM OPENXML (@index, '/ROOT/employee')
 WITH (
  firstname VARCHAR(100) 'firstname',
  lastname VARCHAR(100) 'lastname')

 EXEC sp_xml_removedocument @index

END


GO
