GO
/****** Object:  StoredProcedure [dbo].[RVLT_SP_GetLatLng2_Optimzd]    Script Date: 02/01/2022 04:08:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER 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_GetVehicleByFleetID]    Script Date: 02/01/2022 04:08:56 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER 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_GetMonitorData]    Script Date: 02/01/2022 04:09:32 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
ALTER 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].[rvlf_Sp_EngineHours_Rpt]    Script Date: 02/01/2022 04:10:06 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_Instrument_Rpt]    Script Date: 02/01/2022 04:10:39 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
ALTER 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_GetAlarms_Opt_VXL]    Script Date: 02/01/2022 04:11:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

ALTER 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_GetAlarms_Opt_Techno]    Script Date: 02/01/2022 04:12:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

ALTER 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                   
                             
END 

-----------------------------------------------------------------------------------------------------------------------------------------

GO
/****** Object:  StoredProcedure [dbo].[rvlf_sp_UpdateMessageReceived_TP]    Script Date: 02/01/2022 04:14:08 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetServiceCategoryDetails]    Script Date: 02/01/2022 04:15:51 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER 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_CheckOrgRestrictions]    Script Date: 02/01/2022 04:16:48 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetReport_Param]    Script Date: 02/01/2022 04:19:40 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
ALTER 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].[RVLT_SP_GetLatLng2_Optimzd_TechnoMobile]    Script Date: 02/01/2022 04:21:08 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetVehicleByFleetID_PhoneGap]    Script Date: 02/01/2022 04:21:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER  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].[rvlf_sp_GetVehiclesByTypeId]    Script Date: 02/01/2022 04:22:09 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetDeviceList_PhoneGap]    Script Date: 02/01/2022 04:22:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER 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_GetDashboardOverview_PhoneGap]    Script Date: 02/01/2022 04:23:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Asanraj
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
ALTER 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_DeviceAlarm]    Script Date: 02/01/2022 04:24:23 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'
-- =============================================
ALTER 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_sp_GetOrganizationModules]    Script Date: 02/01/2022 04:24:53 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetUserGroupPriviledges]    Script Date: 02/01/2022 04:25:23 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetAlarmsForMonitor_Techno]    Script Date: 02/01/2022 04:25:55 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetSeverities_Alarm]    Script Date: 02/01/2022 04:28:28 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_LogNotificaitons_ForAlarms]    Script Date: 02/01/2022 04:29:01 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_UpdateVehicleNearingPercentage]    Script Date: 02/01/2022 04:29:32 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
ALTER 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_GetVehicleNearingMaintenance]    Script Date: 02/01/2022 04:30:01 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER  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_GetBoxCommInfo]    Script Date: 02/01/2022 04:30:28 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetDeviceSeverity]    Script Date: 02/01/2022 04:30:57 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
-- =============================================
ALTER 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_ModuleInfromation]    Script Date: 02/01/2022 04:31:27 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
-- =============================================
ALTER 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_sp_UpdateAddress_BgProcessTest]    Script Date: 02/01/2022 04:31:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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  
  
/*****************************************************************************************************/           
     
            
--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****************************/                    
/*****************************************************************************************************/                         
                                           
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_GetLatLng_ForBG_ParallelBatchProcess]    Script Date: 02/01/2022 04:32:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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                                              
              
       
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_GetVehicleServiceHistory]    Script Date: 02/01/2022 04:33:24 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER  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].[RVLT_SP_GetLatLng2_Optimzd_backupwithscaling]    Script Date: 02/01/2022 04:33:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER 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].[rvlf_sp_GetAlarms]    Script Date: 02/01/2022 04:34:23 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER  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_SaveDeviceMgmt]    Script Date: 02/01/2022 04:34:58 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetAlarmsForMonitor]    Script Date: 02/01/2022 04:35:23 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetVehicles]    Script Date: 02/01/2022 04:36:09 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetOrgStatistics_PhoneGap]    Script Date: 02/01/2022 04:36:38 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

           
ALTER  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_GetVehiclePlanAssignments]    Script Date: 02/01/2022 04:37:28 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER  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_SaveorupdateSparesRequest]    Script Date: 02/01/2022 04:38:07 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'
-- =============================================
ALTER 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_GetUserGroupAssignments]    Script Date: 02/01/2022 04:38:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER 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_GetUserDetails]    Script Date: 02/01/2022 04:39:04 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER  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_GetMakDevicesForSystemConfig]    Script Date: 02/01/2022 04:39:30 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetMakDevices_MngEquip]    Script Date: 02/01/2022 04:40:04 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetFleetUsers]    Script Date: 02/01/2022 04:40:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER 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_GetAlarms_Opt]    Script Date: 02/01/2022 04:41:01 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER 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_GetUserlist]    Script Date: 02/01/2022 04:41:28 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER 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_GetPartnerDetails]    Script Date: 02/01/2022 04:41:57 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER 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_CustomerFilterddl]    Script Date: 02/01/2022 04:42:24 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'
-- =============================================
ALTER 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


END

